private void ResolveMwmPaths(MyModContext modContext, MyObjectBuilder_AnimationTreeNode objBuilderNode)
 {
     // ------- tree node track -------
     var objBuilderNodeTrack = objBuilderNode as VRage.Game.ObjectBuilders.MyObjectBuilder_AnimationTreeNodeTrack;
     if (objBuilderNodeTrack != null)
     {
         string testMwmPath = Path.Combine(modContext.ModPath, objBuilderNodeTrack.PathToModel);
         if (MyFileSystem.FileExists(testMwmPath))
         {
             objBuilderNodeTrack.PathToModel = testMwmPath;
         }
     }
     // ------ tree node mix -----------------------
     var objBuilderNodeMix1D = objBuilderNode as MyObjectBuilder_AnimationTreeNodeMix1D;
     if (objBuilderNodeMix1D != null)
     {
         if (objBuilderNodeMix1D.Children != null)
         {
             foreach (var mappingObjBuilder in objBuilderNodeMix1D.Children)
                 if (mappingObjBuilder.Node != null)
                     ResolveMwmPaths(modContext, mappingObjBuilder.Node);
         }
     }
     // ------ tree node add -----------------------
     var objBuilderNodeAdd = objBuilderNode as MyObjectBuilder_AnimationTreeNodeAdd;
     if (objBuilderNodeAdd != null)
     {
         if (objBuilderNodeAdd.BaseNode.Node != null)
             ResolveMwmPaths(modContext, objBuilderNodeAdd.BaseNode.Node);
         if (objBuilderNodeAdd.AddNode.Node != null)
             ResolveMwmPaths(modContext, objBuilderNodeAdd.AddNode.Node);
     }
 }
Example #2
0
        private Image TryGetPlanetTexture(string name, MyModContext context, string p, out string fullPath)
        {
            bool found = false;

            name    += p;
            fullPath = Path.Combine(context.ModPathData, "PlanetDataFiles", name) + ".png";

            // Check for modded textures
            if (!context.IsBaseGame)
            {
                if (!MyFileSystem.FileExists(fullPath))
                {
                    fullPath = Path.Combine(context.ModPathData, "PlanetDataFiles", name) + ".dds";
                    if (MyFileSystem.FileExists(fullPath))
                    {
                        found = true;
                    }
                }
                else
                {
                    found = true;
                }
            }

            // Check for default textures
            if (!found)
            {
                fullPath = Path.Combine(m_planetDataFolder, name) + ".png";

                if (!MyFileSystem.FileExists(fullPath))
                {
                    fullPath = Path.Combine(m_planetDataFolder, name) + ".dds";
                    if (!MyFileSystem.FileExists(fullPath))
                    {
                        return(null);
                    }
                }
            }

            if (fullPath.Contains(".sbm"))
            {
                string archivePath             = fullPath.Substring(0, fullPath.IndexOf(".sbm") + 4);
                string fileRelativeArchivePath = fullPath.Replace(archivePath + "\\", "");
                using (var sbm = VRage.Compression.MyZipArchive.OpenOnFile(archivePath))
                {
                    try
                    {
                        return(SharpDXImage.Load(sbm.GetFile(fileRelativeArchivePath).GetStream()));
                    }
                    catch (Exception ex)
                    {
                        MyDebug.FailRelease("Failed to load existing " + p + " file from .sbm archive. " + fullPath);
                        return(null);
                    }
                }
            }

            return(SharpDXImage.Load(fullPath));
        }
Example #3
0
        public MyModContext GetModContext()
        {
            MyModContext modContext = new MyModContext();

            modContext.Init(new MyObjectBuilder_Checkpoint.ModItem(WorkshopId, "Steam"));
            modContext.Init(WorkshopId.ToString(), null, ModLocation);
            return(modContext);
        }
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped)
        {
            Assembly assembly = null;
            bool     compiled = false;
            var      c        = new MyModContext();

            c.Init(assemblyName, assemblyName);
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream  = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(c, string.Format("Cannot load {0}", Path.GetFileName(file)), TErrorSeverity.Error);
                        MyDefinitionErrors.Add(c, e.Message, TErrorSeverity.Error);
                    }
                }
                compiled = IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
            }
            else
            {
                compiled = IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
            }
            Debug.Assert(compiled == (assembly != null), "Compile results inconsistency!");
            if (assembly != null && compiled)
            {
                AddAssembly(MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(c, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var error in m_errors)
                {
                    MyDefinitionErrors.Add(c, error.ToString(), TErrorSeverity.Error);
                    Debug.Assert(false, error.ToString());
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
        }
Example #5
0
        private void TryAddEntityScripts(MyModContext context, Assembly assembly)
        {
            var gameLogicType = typeof(MyGameLogicComponent);
            var builderType   = typeof(MyObjectBuilder_Base);

            foreach (var type in assembly.GetTypes())
            {
                var descriptorArray = type.GetCustomAttributes(typeof(MyEntityComponentDescriptor), false);
                if (descriptorArray != null && descriptorArray.Length > 0)
                {
                    var descriptor = (MyEntityComponentDescriptor)descriptorArray[0];
                    try
                    {
                        var component = (MyGameLogicComponent)Activator.CreateInstance(type);

                        if (descriptor.EntityBuilderSubTypeNames != null && descriptor.EntityBuilderSubTypeNames.Length > 0)
                        {
                            foreach (string subTypeName in descriptor.EntityBuilderSubTypeNames)
                            {
                                if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                                {
                                    if (!SubEntityScripts.ContainsKey(new Tuple <Type, string>(descriptor.EntityBuilderType, subTypeName)))
                                    {
                                        SubEntityScripts.Add(new Tuple <Type, string>(descriptor.EntityBuilderType, subTypeName), new HashSet <Type>());
                                    }
                                    else
                                    {
                                        MyDefinitionErrors.Add(context, "Possible entity type script logic collision", TErrorSeverity.Warning);
                                    }

                                    SubEntityScripts[new Tuple <Type, string>(descriptor.EntityBuilderType, subTypeName)].Add(type);
                                }
                            }
                        }
                        else
                        {
                            if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                            {
                                if (!EntityScripts.ContainsKey(descriptor.EntityBuilderType))
                                {
                                    EntityScripts.Add(descriptor.EntityBuilderType, new HashSet <Type>());
                                }
                                else
                                {
                                    MyDefinitionErrors.Add(context, "Possible entity type script logic collision", TErrorSeverity.Warning);
                                }

                                EntityScripts[descriptor.EntityBuilderType].Add(type);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MySandboxGame.Log.WriteLine("Exception during loading of type : " + type.Name);
                    }
                }
            }
        }
 public void Add(MyModContext context, MyDefinitionId obj)
 {
     Debug.Assert(context != null);
     if (context == null)
     {
         MyLog.Default.WriteLine("Writing to scripted group definition without context");
         return;
     }
     m_scriptedObjects.Add(obj);
 }
        private void LoadScripts(string path, MyModContext mod = null)
        {
#if XB1
#if !XB1_SKIPASSERTFORNOW
            System.Diagnostics.Debug.Assert(false, "Unsupported runtime script compilation on XB1.");
#endif // !XB1_SKIPASSERTFORNOW
#else
            if (!MyFakes.ENABLE_SCRIPTS)
            {
                return;
            }

            var fsPath      = Path.Combine(path, "Data", "Scripts");
            var scriptFiles = MyFileSystem.GetFiles(fsPath, "*.cs");//, searchOption: VRage.FileSystem.SearchOption.TopDirectoryOnly);
            try
            {
                if (scriptFiles.Count() == 0)
                {
                    return;
                }
            }
            catch (Exception)
            {
                MySandboxGame.Log.WriteLine(string.Format("Failed to load scripts from: {0}", path));
                return;
            }
            var           isZip     = VRage.FileSystem.MyZipFileProvider.IsZipFile(path);
            List <string> files     = new List <string>();
            var           split     = scriptFiles.First().Split('\\');
            string        scriptDir = split[split.Length - 2];
            foreach (var scriptFile in scriptFiles)
            {
                split = scriptFile.Split('\\');
                var extension = split[split.Length - 1].Split('.').Last();
                if (extension != "cs")
                {
                    continue;
                }
                var idx = Array.IndexOf(split, "Scripts") + 1; //index of script directory (there can be any dir hierarchy above it)
                if (split[idx] == scriptDir)
                {
                    files.Add(scriptFile);
                }
                else
                {
                    Compile(files, string.Format("{0}_{1}", mod.ModId, scriptDir), isZip, mod);
                    files.Clear();
                    scriptDir = split[split.Length - 2];
                    files.Add(scriptFile);
                }
            }
            Compile(files.ToArray(), Path.Combine(MyFileSystem.ModsPath, string.Format("{0}_{1}", mod.ModId, scriptDir)), isZip, mod);
            files.Clear();
#endif
        }
Example #8
0
        public void AcceptMod(MyModContext mod, SlimProfilerEntry spe)
        {
            if (Type != ProfilerRequestType.Mod)
            {
                return;
            }
            var desc = mod.ModName ?? mod.ModId ?? mod.ModPath ?? "Unknown Mod";

            if (mod == MyModContext.BaseGame)
            {
                desc = "Base Game";
            }
            Accept(desc, null, "", spe);
        }
Example #9
0
 public void CheckLoadingErrors(MyModContext context, out bool errorFound)
 {
     if (ExportedWrong && m_loadingErrorProcessed == false)
     {
         errorFound = true;
         // generation of an error message delegated to the caller
         // Sandbox.Definitions.MyDefinitionErrors.Add(context, "There was error during loading of model, please check log file.", Sandbox.Definitions.TErrorSeverity.Error);
         m_loadingErrorProcessed = true;
     }
     else
     {
         errorFound = false;
     }
 }
        private void ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acAddress = msgReload.ACAddress;
                    string acName    = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var          firstDef = allDefinitions.Definitions[0];
                        MyModContext context  = new MyModContext();
                        context.Init("AnimationControllerDefinition", Path.GetFileName(acAddress));
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);

                        // swap animation controller for each entity
                        foreach (MyEntity entity in MyEntities.GetEntities())
                        {
                            MyCharacter character = entity as MyCharacter;
                            if (character != null && character.Definition.AnimationController == acName)
                            {
                                character.AnimationController.InitFromDefinition(animationControllerDefinition);
                                character.ObtainBones();
                            }
                        }

                        // update in def. manager
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);
                        MyAnimationControllerDefinition animControllerDefInManager =
                            MyDefinitionManager.Static.GetDefinition <MyAnimationControllerDefinition>(animSubtypeNameHash);
                        animControllerDefInManager.Init(firstDef, context);
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
        public void LoadData()
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyScriptManager.LoadData");
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - START");
            MySandboxGame.Log.IncreaseIndent();
            Static = this;
            Scripts.Clear();
            EntityScripts.Clear();
            SubEntityScripts.Clear();
            if (Sync.IsServer)
            {
                LoadScripts(MyFileSystem.ContentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.CurrentPath != null)
            {
                LoadScripts(MySession.Static.CurrentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.Mods != null)
            {
                foreach (var mod in MySession.Static.Mods)
                {
                    var mc = new MyModContext();
                    mc.Init(mod);
                    LoadScripts(Path.Combine(MyFileSystem.ModsPath, mod.Name), mc);
                }
            }

            foreach (var ass in Scripts.Values)
            {
#if XB1 // XB1_ALLINONEASSEMBLY
                System.Diagnostics.Debug.Assert(false, "XB1 TODO?");
#else // !XB1
                if (MyFakes.ENABLE_TYPES_FROM_MODS) // Highly experimental!
                {
                    MyGlobalTypeMetadata.Static.RegisterAssembly(ass);
                }

                MySandboxGame.Log.WriteLine(string.Format("Script loaded: {0}", ass.FullName));
#endif // !XB1
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - END");

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
Example #12
0
        public MyHeightCubemap(string folderName, MyModContext context)
        {
            m_faces = new MyHeightmapFace[6];

            var useDefault = false;

            for (int i = 0; i < MyCubemapHelpers.NUM_MAPS; ++i)
            {
                m_faces[i] = MyHeightMapLoadingSystem.Static.GetHeightMap(folderName, MyCubemapHelpers.GetNameForFace(i), context);
                if (m_faces[i] == null)
                {
                    useDefault = true;
                }
                else if (m_faces[i].Resolution != m_resolution && m_resolution != 0)
                {
                    useDefault = true;
                    MyLog.Default.WriteLine("Error: Cubemap faces must be all the same size!");
                }
                else
                {
                    m_resolution = m_faces[i].Resolution;
                }

                if (useDefault)
                {
                    break;
                }
            }

            Name = folderName;

            if (useDefault)
            {
                MyLog.Default.WriteLine(String.Format("Error loading heightmap {0}, using fallback instead. See rest of log for details.", folderName));
                for (int i = 0; i < MyCubemapHelpers.NUM_MAPS; ++i)
                {
                    m_faces[i]   = MyHeightmapFace.Default;
                    m_resolution = m_faces[i].Resolution;
                }
            }

            ProfilerShort.Begin("MyHeightCubemap::PrepareSides()");
            PrepareSides();
            ProfilerShort.End();
        }
Example #13
0
        public void LoadData()
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyScriptManager.LoadData");
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - START");
            MySandboxGame.Log.IncreaseIndent();
            Static = this;
            Scripts.Clear();
            EntityScripts.Clear();
            SubEntityScripts.Clear();
            if (Sync.IsServer)
            {
                LoadScripts(MyFileSystem.ContentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.CurrentPath != null)
            {
                LoadScripts(MySession.Static.CurrentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.Mods != null)
            {
                foreach (var mod in MySession.Static.Mods)
                {
                    var mc = new MyModContext();
                    mc.Init(mod);
                    LoadScripts(Path.Combine(MyFileSystem.ModsPath, mod.Name), mc);
                }
            }

            foreach (var ass in Scripts.Values)
            {
#if XB1 // XB1_ALLINONEASSEMBLY
                System.Diagnostics.Debug.Assert(false, "XB1 TODO?");
#else // !XB1
                if (MyFakes.ENABLE_TYPES_FROM_MODS) // Highly experimental!
                {
                    MyGlobalTypeMetadata.Static.RegisterAssembly(ass);
                }

                MySandboxGame.Log.WriteLine(string.Format("Script loaded: {0}", ass.FullName));
#endif // !XB1
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - END");

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
        private static MyBehaviorDefinition LoadBehaviorTreeFromFile(string path)
        {
            MyObjectBuilder_Definitions allDefinitions = null;

            MyObjectBuilderSerializer.DeserializeXML(path, out allDefinitions);

            if (allDefinitions != null && allDefinitions.AIBehaviors != null && allDefinitions.AIBehaviors.Length > 0)
            {
                var firstDef = allDefinitions.AIBehaviors[0]; // only one tree can be uploaded at one time

                MyBehaviorDefinition behaviorDefinition = new MyBehaviorDefinition();
                MyModContext         context            = new MyModContext();
                context.Init("BehaviorDefinition", Path.GetFileName(path));
                behaviorDefinition.Init(firstDef, context);
                return(behaviorDefinition);
            }
            return(null);
        }
Example #15
0
        private static MyBehaviorDefinition LoadBehaviorTreeFromFile(string path)
        {
            MyObjectBuilder_Definitions objectBuilder = null;

            MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_Definitions>(path, out objectBuilder);
            if (((objectBuilder == null) || (objectBuilder.AIBehaviors == null)) || (objectBuilder.AIBehaviors.Length == 0))
            {
                return(null);
            }
            MyObjectBuilder_BehaviorTreeDefinition builder = objectBuilder.AIBehaviors[0];
            MyModContext modContext = new MyModContext();

            modContext.Init("BehaviorDefinition", Path.GetFileName(path), null);
            MyBehaviorDefinition definition1 = new MyBehaviorDefinition();

            definition1.Init(builder, modContext);
            return(definition1);
        }
Example #16
0
        private void ResolveMwmPaths(MyModContext modContext, MyObjectBuilder_AnimationTreeNode objBuilderNode)
        {
            // ------- tree node track -------
            var objBuilderNodeTrack = objBuilderNode as VRage.Game.ObjectBuilders.MyObjectBuilder_AnimationTreeNodeTrack;

            if (objBuilderNodeTrack != null && objBuilderNodeTrack.PathToModel != null)
            {
                string testMwmPath = Path.Combine(modContext.ModPath, objBuilderNodeTrack.PathToModel);
                if (MyFileSystem.FileExists(testMwmPath))
                {
                    objBuilderNodeTrack.PathToModel = testMwmPath;
                }
            }
            // ------ tree node mix -----------------------
            var objBuilderNodeMix1D = objBuilderNode as MyObjectBuilder_AnimationTreeNodeMix1D;

            if (objBuilderNodeMix1D != null)
            {
                if (objBuilderNodeMix1D.Children != null)
                {
                    foreach (var mappingObjBuilder in objBuilderNodeMix1D.Children)
                    {
                        if (mappingObjBuilder.Node != null)
                        {
                            ResolveMwmPaths(modContext, mappingObjBuilder.Node);
                        }
                    }
                }
            }
            // ------ tree node add -----------------------
            var objBuilderNodeAdd = objBuilderNode as MyObjectBuilder_AnimationTreeNodeAdd;

            if (objBuilderNodeAdd != null)
            {
                if (objBuilderNodeAdd.BaseNode.Node != null)
                {
                    ResolveMwmPaths(modContext, objBuilderNodeAdd.BaseNode.Node);
                }
                if (objBuilderNodeAdd.AddNode.Node != null)
                {
                    ResolveMwmPaths(modContext, objBuilderNodeAdd.AddNode.Node);
                }
            }
        }
Example #17
0
        public static bool ChangeMask(long?playerMask, long?factionMask, long?entityMask, MyModContext modMask)
        {
            lock (_requests)
            {
                if (_playerMask == playerMask && _factionMask == factionMask && _entityMask == entityMask && modMask == _modMask)
                {
                    return(true);
                }

                if (_requests.Count > 0)
                {
                    return(false);
                }
                _playerMask  = playerMask;
                _factionMask = factionMask;
                _entityMask  = entityMask;
                _modMask     = modMask;
                return(true);
            }
        }
Example #18
0
        public void LoadData()
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyScriptManager.LoadData");
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - START");
            MySandboxGame.Log.IncreaseIndent();
            Static = this;
            Scripts.Clear();
            EntityScripts.Clear();
            SubEntityScripts.Clear();
            if (Sync.IsServer)
            {
                LoadScripts(MyFileSystem.ContentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.CurrentPath != null)
            {
                LoadScripts(MySession.Static.CurrentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.Mods != null)
            {
                foreach (var mod in MySession.Static.Mods)
                {
                    var mc = new MyModContext();
                    mc.Init(mod);
                    LoadScripts(Path.Combine(MyFileSystem.ModsPath, mod.Name), mc);
                }
            }

            foreach (var ass in Scripts.Values)
            {
                if (MyFakes.ENABLE_TYPES_FROM_MODS) // Highly experimental!
                {
                    MyObjectFactories.RegisterFromAssembly(ass);
                }

                MySandboxGame.Log.WriteLine(string.Format("Script loaded: {0}", ass.FullName));
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - END");

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
Example #19
0
        public MyHeightCubemap GetHeightMap(string folderName, MyModContext context)
        {
            string modId = context.ModId;
            string name  = $"{modId ?? "BaseGame"}:{folderName}";
            bool   flag  = false;

            MyHeightmapFace[] faces = new MyHeightmapFace[6];
            int resolution          = 0;

            for (int i = 0; i < 6; i++)
            {
                faces[i] = this.GetHeightMap(folderName, MyCubemapHelpers.GetNameForFace(i), context);
                if (faces[i] == null)
                {
                    flag = true;
                }
                else if ((faces[i].Resolution == resolution) || (resolution == 0))
                {
                    resolution = faces[i].Resolution;
                }
                else
                {
                    flag = true;
                    MyLog.Default.Error("Cubemap faces must be all the same size!", Array.Empty <object>());
                }
                if (flag)
                {
                    break;
                }
            }
            if (flag)
            {
                MyLog.Default.WriteLine($"Error loading heightmap {folderName}, using fallback instead. See rest of log for details.");
                for (int j = 0; j < 6; j++)
                {
                    faces[j]   = MyHeightmapFace.Default;
                    resolution = faces[j].Resolution;
                }
            }
            return(new MyHeightCubemap(name, faces, resolution));
        }
Example #20
0
        private MyHeightmapFace GetHeightMap(string folderName, string faceName, MyModContext context)
        {
            string          path = this.GetPath(folderName, faceName, context);
            MyHeightmapFace map  = null;

            try
            {
                using (Image image = this.LoadTexture(path))
                {
                    if (image == null)
                    {
                        object[] args = new object[] { path };
                        MyLog.Default.Error("Could not load texture {0}, no suitable format found. ", args);
                    }
                    else
                    {
                        PixelBuffer imageData = image.GetPixelBuffer(0, 0, 0);
                        map = new MyHeightmapFace(imageData.Height);
                        if (imageData.Format == Format.R16_UNorm)
                        {
                            PrepareHeightMap(map, imageData);
                        }
                        else if (imageData.Format == Format.R8_UNorm)
                        {
                            PrepareHeightMap8Bit(map, imageData);
                        }
                        else
                        {
                            MyLog.Default.Error($"Heighmap texture {path}: Invalid format {imageData.Format} (expecting R16_UNorm or R8_UNorm).", Array.Empty <object>());
                        }
                        image.Dispose();
                    }
                }
            }
            catch (Exception exception)
            {
                MyLog.Default.WriteLine(exception.Message);
            }
            return(map);
        }
Example #21
0
        public Type GetScriptType(MyModContext context, string qualifiedTypeName)
        {
            HashSet <MyStringId> scripts;

            if (!ScriptsPerMod.TryGetValue(context, out scripts))
            {
                return(null);
            }

            foreach (var script in scripts)
            {
                var ass = Scripts[script];

                var t = ass.GetType(qualifiedTypeName);
                if (t != null)
                {
                    return(t);
                }
            }

            return(null);
        }
Example #22
0
        public Type GetScriptType(MyModContext context, string qualifiedTypeName)
        {
            HashSet<MyStringId> scripts;
            if (!ScriptsPerMod.TryGetValue(context, out scripts)) return null;

            foreach (var script in scripts)
            {
                var ass = Scripts[script];

                var t = ass.GetType(qualifiedTypeName);
                if (t != null) return t;
            }

            return null;
        }
        private void Compile(IEnumerable<string> scriptFiles, string assemblyName, bool zipped)
        {
            Assembly assembly = null;
            bool compiled = false;
            var c = new MyModContext();
            c.Init(assemblyName, assemblyName);
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(c, string.Format("Cannot load {0}",Path.GetFileName(file)) , TErrorSeverity.Error);
                        MyDefinitionErrors.Add(c, e.Message, TErrorSeverity.Error);
                    }
                }
                compiled = IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
            }
            else
            {
                compiled = IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
            }
            Debug.Assert(compiled == (assembly != null), "Compile results inconsistency!");
            if(assembly != null && compiled)
                AddAssembly(MyStringId.GetOrCompute(assemblyName), assembly);
            else
            {
                MyDefinitionErrors.Add(c, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
				foreach (var error in m_errors)
				{
					MyDefinitionErrors.Add(c, error.ToString(), TErrorSeverity.Error);
					Debug.Assert(false, error.ToString());
				}
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
        }
Example #24
0
        // receiving messages
        private void LiveDebugging_ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acContentPath = msgReload.ACContentAddress;
                    string acAddress     = msgReload.ACAddress;
                    string acName        = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var          firstDef = allDefinitions.Definitions[0];
                        MyModContext context  = new MyModContext();
                        context.Init("AnimationControllerDefinition", acAddress, acContentPath);
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);

                        // post process and update in def. manager
                        MyAnimationControllerDefinition originalAnimationControllerDefinition =
                            MyDefinitionManagerBase.Static.GetDefinition <MyAnimationControllerDefinition>(
                                animSubtypeNameHash);

                        var postprocessor = MyDefinitionManagerBase.GetPostProcessor(typeof(MyObjectBuilder_AnimationControllerDefinition));
                        if (postprocessor != null)
                        {
                            MyDefinitionPostprocessor.Bundle originalBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context     = MyModContext.BaseGame,
                                Definitions = new Dictionary <MyStringHash, MyDefinitionBase>
                                {
                                    { animSubtypeNameHash, originalAnimationControllerDefinition }
                                },
                                Set = new MyDefinitionSet()
                            };
                            originalBundle.Set.AddDefinition(originalAnimationControllerDefinition);

                            MyDefinitionPostprocessor.Bundle overridingBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context     = context,
                                Definitions = new Dictionary <MyStringHash, MyDefinitionBase>
                                {
                                    { animSubtypeNameHash, animationControllerDefinition }
                                },
                                Set = new MyDefinitionSet()
                            };
                            overridingBundle.Set.AddDefinition(animationControllerDefinition);

                            // postprocess -> override existing definition in memory
                            postprocessor.AfterLoaded(ref overridingBundle);
                            postprocessor.OverrideBy(ref originalBundle, ref overridingBundle);
                        }

                        // swap animation controller for each entity
                        foreach (var component in m_skinnedEntityComponents)
                        {
                            if (component != null && component.SourceId.SubtypeName == acName)
                            {
                                component.Clear();
                                component.InitFromDefinition(originalAnimationControllerDefinition, forceReloadMwm: true); // reload from original def that was modified by postprocessor
                                if (component.ReloadBonesNeeded != null)
                                {
                                    component.ReloadBonesNeeded();
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
Example #25
0
 public void CheckLoadingErrors(MyModContext context, out bool errorFound)
 {
     if (ExportedWrong && m_loadingErrorProcessed == false)
     {
         errorFound = true;
         // generation of an error message delegated to the caller
         // Sandbox.Definitions.MyDefinitionErrors.Add(context, "There was error during loading of model, please check log file.", Sandbox.Definitions.TErrorSeverity.Error);
         m_loadingErrorProcessed = true;
     }
     else
     {
         errorFound = false;
     }
 }
        private void AddAssembly(MyModContext context, MyStringId myStringId, Assembly assembly)
        {
            if (Scripts.ContainsKey(myStringId))
            {
                MySandboxGame.Log.WriteLine(string.Format("Script already in list {0}", myStringId.ToString()));
                Debug.Fail(string.Format("Script already in list {0}", myStringId.ToString()));
                return;
            }
            HashSet<MyStringId> names;
            if (!ScriptsPerMod.TryGetValue(context, out names))
            {
                names = new HashSet<MyStringId>();
                ScriptsPerMod.Add(context, names);
            }

            names.Add(myStringId);

            Scripts.Add(myStringId, assembly);
            foreach (var type in assembly.GetTypes())
            {
                MyConsole.AddCommand(new MyCommandScript(type));
            }
            TryAddEntityScripts(context, assembly);
            AddStatScripts(assembly);
        }
        public void GetPlanetMaps(string folder, MyModContext context, MyPlanetMaps mapsToUse, out MyCubemap[] maps)
        {
            if (m_planetMaps.ContainsKey(folder))
            {
                maps = m_planetMaps[folder];
                return;
            }

            maps = new MyCubemap[4];

            MyCubemapData <byte>[] tmpMaps = new MyCubemapData <byte> [4 * 6];

            byte[][] streams = new byte[4][];

            string fullPath;

            ProfilerShort.Begin("MyHeightmapLoadingSystem::GetPlanetMaps()");

            ProfilerShort.Begin("Load _mat");
            // Round one: material, ore, biome
            if (mapsToUse.Material || mapsToUse.Biome || mapsToUse.Ores)
            {
                for (int i = 0; i < 6; ++i)
                {
                    string name = Path.Combine(folder, MyCubemapHelpers.GetNameForFace(i));

                    using (var texture = TryGetPlanetTexture(name, context, "_mat", out fullPath))
                    {
                        if (texture == null)
                        {
                            ClearMatValues(tmpMaps);
                            break;
                        }

                        PixelBuffer buffer = texture.GetPixelBuffer(0, 0, 0);

                        if (buffer.Format != Format.B8G8R8A8_UNorm &&
                            buffer.Format != Format.R8G8B8A8_UNorm)
                        {
                            MyDebug.FailRelease("While loading maps from {1}: Unsupported planet map format: {0}.", buffer.Format, fullPath);
                            break;
                        }

                        if (buffer.Width != buffer.Height)
                        {
                            MyDebug.FailRelease("While loading maps from {0}: Width and height must be the same.", fullPath);
                            break;
                        }

                        if (mapsToUse.Material)
                        {
                            tmpMaps[i * 4] = new MyCubemapData <byte>(buffer.Width);
                            streams[0]     = tmpMaps[i * 4].Data;
                        }

                        if (mapsToUse.Biome)
                        {
                            tmpMaps[i * 4 + 1] = new MyCubemapData <byte>(buffer.Width);
                            streams[1]         = tmpMaps[i * 4 + 1].Data;
                        }

                        if (mapsToUse.Ores)
                        {
                            tmpMaps[i * 4 + 2] = new MyCubemapData <byte>(buffer.Width);
                            streams[2]         = tmpMaps[i * 4 + 2].Data;
                        }

                        // Invert channels for BGRA
                        if (buffer.Format == Format.B8G8R8A8_UNorm)
                        {
                            var tmp = streams[2];
                            streams[2] = streams[0];
                            streams[0] = tmp;
                        }

                        ReadChannelsFromImage(streams, buffer);
                    }
                }
            }

            ProfilerShort.BeginNextBlock("Load _add");
            // round two: add map
            if (mapsToUse.Occlusion)
            {
                for (int i = 0; i < 6; ++i)
                {
                    string name = Path.Combine(folder, MyCubemapHelpers.GetNameForFace(i));

                    using (var texture = TryGetPlanetTexture(name, context, "_add", out fullPath))
                    {
                        if (texture == null)
                        {
                            ClearAddValues(tmpMaps);
                            break;
                        }

                        PixelBuffer buffer = texture.GetPixelBuffer(0, 0, 0);

                        if (buffer.Format != Format.B8G8R8A8_UNorm &&
                            buffer.Format != Format.R8G8B8A8_UNorm)
                        {
                            MyDebug.FailRelease("While loading maps from {1}: Unsupported planet map format: {0}.", buffer.Format, fullPath);
                            break;
                        }

                        if (buffer.Width != buffer.Height)
                        {
                            MyDebug.FailRelease("While loading maps from {0}: Width and height must be the same.", fullPath);
                            break;
                        }

                        if (mapsToUse.Occlusion)
                        {
                            tmpMaps[i * 4 + 3] = new MyCubemapData <byte>(buffer.Width);
                            streams[0]         = tmpMaps[i * 4 + 3].Data;
                        }

                        streams[1] = streams[2] = null;

                        // Invert channels for BGRA
                        if (buffer.Format == Format.B8G8R8A8_UNorm)
                        {
                            var tmp = streams[2];
                            streams[2] = streams[0];
                            streams[0] = tmp;
                        }

                        ReadChannelsFromImage(streams, buffer);
                    }
                }
            }

            ProfilerShort.BeginNextBlock("Finish");

            for (int i = 0; i < 4; ++i)
            {
                if (tmpMaps[i] != null)
                {
                    var cmaps = new MyCubemapData <byte> [6];
                    for (int j = 0; j < 6; j++)
                    {
                        cmaps[j] = tmpMaps[i + j * 4];
                    }
                    maps[i] = new MyCubemap(cmaps);
                }
            }

            m_planetMaps[folder] = maps;

            ProfilerShort.End();
            ProfilerShort.End();
        }
        public MyHeightmapFace GetHeightMap(string folderName, string faceName, MyModContext context)
        {
            ProfilerShort.Begin("MyHeightmapLoadingSystem::GetHeightMap()");
            if (m_first)
            {
                PreloadCrashingData();
                m_first = false;
            }
            string fullPath = null;
            bool   found    = false;


            // Look for modded textures
            if (!context.IsBaseGame)
            {
                fullPath = Path.Combine(Path.Combine(context.ModPathData, "PlanetDataFiles"), folderName, faceName);
                if (MyFileSystem.FileExists(fullPath + ".png"))
                {
                    found     = true;
                    fullPath += ".png";
                }
                else if (MyFileSystem.FileExists(fullPath + ".dds"))
                {
                    found     = true;
                    fullPath += ".dds";
                }
            }

            // Use default ones
            if (!found)
            {
                fullPath = Path.Combine(m_planetDataFolder, folderName, faceName);
                if (MyFileSystem.FileExists(fullPath + ".png"))
                {
                    found     = true;
                    fullPath += ".png";
                }
                else if (MyFileSystem.FileExists(fullPath + ".dds"))
                {
                    fullPath += ".dds";
                }
            }

            MyHeightmapFace value;

            if (m_heightMaps.TryGetValue(fullPath, out value))
            {
                ProfilerShort.End();
                return(value);
            }
            try
            {
                using (SharpDXImage image = LoadTexture(fullPath))
                {
                    if (image == null)
                    {
                        MyLog.Default.WriteLine("Could not load texture {0}, no suitable format found. " + fullPath);
                    }
                    else
                    {
                        PixelBuffer buffer = image.GetPixelBuffer(0, 0, 0);

                        value = new MyHeightmapFace(buffer.Height);

                        if (buffer.Format == Format.R16_UNorm)
                        {
                            PrepareHeightMap(value, buffer);
                        }
                        else if (buffer.Format == Format.R8_UNorm)
                        {
                            PrepareHeightMap8Bit(value, buffer);
                        }
                        else
                        {
                            MyDebug.FailRelease(String.Format("Heighmap texture {0}: Invalid format {1} (expecting R16_UNorm or R8_UNorm).", fullPath, buffer.Format));
                        }
                        buffer = null;
                    }
                }
                m_heightMaps[fullPath] = value;
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine(e.Message);
            }
            ProfilerShort.End();

            return(value);
        }
Example #29
0
        /// <summary>
        /// Compiles the mod
        /// </summary>
        /// <returns></returns>
        public bool Compile()
        {
            // Compile
            if (m_compile)
            {
                if (m_type == WorkshopType.Mod)
                {
                    if (_compileMethod != null)
                    {
                        MySandboxGame.Log.WriteLineAndConsole("Compiling...");
#if SE
                        var mod = new MyModContext();
                        mod.Init(m_title, null, m_modPath);
#else
                        var workshopItem = new MyLocalWorkshopItem(new VRage.ObjectBuilders.SerializableModReference(Path.GetFileName(m_modPath), 0));
                        var mod          = new MyModContext(workshopItem, 0);
#endif
                        _compileMethod(
#if SE
                            m_modPath,
#endif
                            mod
                            );

                        // Process any errors
#if SE
                        var errors = MyDefinitionErrors.GetErrors();
#else
                        var compileMessages = _scriptManager.GetType().GetField("m_messages", BindingFlags.NonPublic | BindingFlags.Instance);
                        var errors          = (compileMessages.GetValue(_scriptManager) as List <MyScriptCompiler.Message>) ?? new List <MyScriptCompiler.Message>();
#endif
                        if (errors.Count > 0)
                        {
                            int errorCount   = 0;
                            int warningCount = 0;

                            // This is not efficient, but I'm lazy
                            foreach (var error in errors)
                            {
                                if (error.Severity >= TErrorSeverity.Error)
                                {
                                    errorCount++;
                                }
                                if (error.Severity == TErrorSeverity.Warning)
                                {
                                    warningCount++;
                                }
                            }

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile errors:", errorCount));
                            }
                            if (warningCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile warnings:", warningCount));
                            }

                            // Output raw message, which is usually in msbuild friendly format, for automated tools
                            foreach (var error in errors)
#if SE
                            { System.Console.WriteLine(error.Message); }
#else
                            { System.Console.WriteLine(error.Text); }
#endif

#if SE
                            MyDefinitionErrors.Clear();     // Clear old ones, so next mod starts fresh
#endif

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole("Compilation FAILED!");
                                return(false);
                            }
                        }
                        MySandboxGame.Log.WriteLineAndConsole("Compilation successful!");
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "LoadScripts"));
                    }
                }
#if SE
                else if (m_type == WorkshopType.IngameScript)
                {
                    // Load the ingame script from the disk
                    // I don't like this, but meh
                    var input   = new StreamReader(Path.Combine(m_modPath, "Script.cs"));
                    var program = input.ReadToEnd();
                    input.Close();
                    var ingamescript = MyScriptCompiler.Static.GetIngameScript(program, "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name, "sealed partial");
                    var messages     = new List <MyScriptCompiler.Message>();
                    var assembly     = MyScriptCompiler.Static.Compile(MyApiTarget.Ingame, null, ingamescript, messages, null).Result;

                    if (messages.Count > 0)
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile messages:", messages.Count));
                        int errors = 0;
                        foreach (var msg in messages)
                        {
                            MySandboxGame.Log.WriteLineAndConsole(msg.Text);

                            if (msg.Severity > TErrorSeverity.Warning)
                            {
                                errors++;
                            }
                        }
                        if (errors > 0)
                        {
                            return(false);
                        }
                    }

                    if (assembly == null)
                    {
                        return(false);
                    }
                }
#endif
                return(true);
            }
            return(true);
        }
Example #30
0
        /// <summary>
        /// Compiles the mod
        /// </summary>
        /// <returns></returns>
        public bool Compile()
        {
            // Compile
            if (m_compile)
            {
                if (m_type == WorkshopType.Mod)
                {
                    if (_compileMethod != null)
                    {
                        MySandboxGame.Log.WriteLineAndConsole("Compiling...");
                        var mod = new MyModContext();
                        mod.Init(m_title, null, m_modPath);
                        _compileMethod.Invoke(_scriptManager, new object[]
                        {
                            m_modPath,
                            mod
                        });

                        // Process any errors
                        var errors = MyDefinitionErrors.GetErrors();
                        if (errors.Count > 0)
                        {
                            int errorCount   = 0;
                            int warningCount = 0;

                            // This is not efficient, but I'm lazy
                            foreach (var error in errors)
                            {
                                if (error.Severity >= TErrorSeverity.Error)
                                {
                                    errorCount++;
                                }
                                if (error.Severity == TErrorSeverity.Warning)
                                {
                                    warningCount++;
                                }
                            }

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile errors:", errorCount));
                            }
                            if (warningCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile warnings:", warningCount));
                            }

                            // Output raw message, which is usually in msbuild friendly format, for automated tools
                            foreach (var error in errors)
                            {
                                System.Console.WriteLine(error.Message);
                            }

                            MyDefinitionErrors.Clear();     // Clear old ones, so next mod starts fresh

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole("Compilation FAILED!");
                                return(false);
                            }
                        }
                        MySandboxGame.Log.WriteLineAndConsole("Compilation successful!");
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "LoadScripts"));
                    }
                }
                else if (m_type == WorkshopType.IngameScript)
                {
                    // Load the ingame script from the disk
                    // I don't like this, but meh
                    var input   = new StreamReader(Path.Combine(m_modPath, "Script.cs"));
                    var program = input.ReadToEnd();
                    input.Close();
                    var ingamescript = MyScriptCompiler.Static.GetIngameScript(program, "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name, "sealed partial");
                    var messages     = new List <MyScriptCompiler.Message>();
                    var assembly     = MyScriptCompiler.Static.Compile(MyApiTarget.Ingame, null, ingamescript, messages).Result;

                    if (messages.Count > 0)
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile messages:", messages.Count));
                        int errors = 0;
                        foreach (var msg in messages)
                        {
                            MySandboxGame.Log.WriteLineAndConsole(msg.Text);

                            if (msg.Severity > TErrorSeverity.Warning)
                            {
                                errors++;
                            }
                        }
                        if (errors > 0)
                        {
                            return(false);
                        }
                    }

                    if (assembly == null)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            return(true);
        }
        private Image TryGetPlanetTexture(string name, MyModContext context, string p, out string fullPath)
        {
            bool found = false;
            name += p;
            fullPath = Path.Combine(context.ModPathData, "PlanetDataFiles", name) + ".png";

            // Check for modded textures
            if (!context.IsBaseGame)
            {
                if (!MyFileSystem.FileExists(fullPath))
                {
                    fullPath = Path.Combine(context.ModPathData, "PlanetDataFiles", name) + ".dds";
                    if (MyFileSystem.FileExists(fullPath))
                        found = true;
                }
                else
                {
                    found = true;
                }
            }

            // Check for default textures
            if (!found)
            {
                fullPath = Path.Combine(m_planetDataFolder, name) + ".png";

                if (!MyFileSystem.FileExists(fullPath))
                {
                    fullPath = Path.Combine(m_planetDataFolder, name) + ".dds";
                    if (!MyFileSystem.FileExists(fullPath))
                    {
                        return null;
                    }
                }
                    
            }

            if (fullPath.Contains(".sbm"))
            {
                string archivePath = fullPath.Substring(0, fullPath.IndexOf(".sbm") + 4);
                string fileRelativeArchivePath = fullPath.Replace(archivePath + "\\", "");
                using (var sbm = VRage.Compression.MyZipArchive.OpenOnFile(archivePath))
                {
                    try
                    {
                        return SharpDXImage.Load(sbm.GetFile(fileRelativeArchivePath).GetStream());
                    }
                    catch (Exception ex)
                    {
                        MyDebug.FailRelease("Failed to load existing " + p + " file from .sbm archive. " + fullPath);
                        return null;
                    }
                }
            }
            
            return SharpDXImage.Load(fullPath);
        }
        private void TryAddEntityScripts(Assembly assembly)
        {
            var gameLogicType = typeof(MyGameLogicComponent);
            var builderType = typeof(MyObjectBuilder_Base);
            foreach (var type in assembly.GetTypes())
            {
                var descriptorArray = type.GetCustomAttributes(typeof(MyEntityComponentDescriptor), false);
                if (descriptorArray != null && descriptorArray.Length > 0)
                {
                    var descriptor = (MyEntityComponentDescriptor)descriptorArray[0];
                    try
                    {
                        var component = (MyGameLogicComponent)Activator.CreateInstance(type);

                        if (descriptor.EntityBuilderSubTypeNames != null && descriptor.EntityBuilderSubTypeNames.Length > 0)
                        {
                            foreach (string subTypeName in descriptor.EntityBuilderSubTypeNames)
                            {
                                if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                                {
                                    if (!SubEntityScripts.ContainsKey(new Tuple<Type, string>(descriptor.EntityBuilderType, subTypeName)))
                                    {
                                        SubEntityScripts.Add(new Tuple<Type, string>(descriptor.EntityBuilderType, subTypeName), new HashSet<Type>());
                                    }
                                    else
                                    {
                                        var c = new MyModContext();
                                        c.Init(assembly.FullName, assembly.FullName);
                                        MyDefinitionErrors.Add(c, "Possible entity type script logic collision", TErrorSeverity.Warning);
                                    }

                                    SubEntityScripts[new Tuple<Type, string>(descriptor.EntityBuilderType, subTypeName)].Add(type);
                                }
                            }
                        }
                        else
                        {
                            if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                            {
                                if (!EntityScripts.ContainsKey(descriptor.EntityBuilderType))
                                {
                                    EntityScripts.Add(descriptor.EntityBuilderType, new HashSet<Type>());
                                }
                                else
                                {
                                    var c = new MyModContext();
                                    c.Init(assembly.FullName, assembly.FullName);
                                    MyDefinitionErrors.Add(c, "Possible entity type script logic collision", TErrorSeverity.Warning);
                                }

                                EntityScripts[descriptor.EntityBuilderType].Add(type);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MySandboxGame.Log.WriteLine("Exception during loading of type : " + type.Name);
                    }
                }
            }
        }
Example #33
0
        private void AddAssembly(MyModContext context, MyStringId myStringId, Assembly assembly)
        {
#if XB1 // XB1_ALLINONEASSEMBLY
            System.Diagnostics.Debug.Assert(false, "XB1 TODO?");
#else // !XB1
            if (Scripts.ContainsKey(myStringId))
            {
                MySandboxGame.Log.WriteLine(string.Format("Script already in list {0}", myStringId.ToString()));
                Debug.Fail(string.Format("Script already in list {0}", myStringId.ToString()));
                return;
            }
            HashSet<MyStringId> names;
            if (!ScriptsPerMod.TryGetValue(context, out names))
            {
                names = new HashSet<MyStringId>();
                ScriptsPerMod.Add(context, names);
            }

            names.Add(myStringId);

            Scripts.Add(myStringId, assembly);
            foreach (var type in assembly.GetTypes())
            {
                MyConsole.AddCommand(new MyCommandScript(type));
            }
            TryAddEntityScripts(context, assembly);
            AddStatScripts(assembly);
#endif // !XB1
        }
Example #34
0
        private void Compile(IEnumerable<string> scriptFiles, string assemblyName, bool zipped, MyModContext context)
        {
#if XB1
            System.Diagnostics.Debug.Assert(false, "Unsupported runtime script compilation on XB1.");
#else
            Assembly assembly = null;
            bool compiled = false;
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(context, string.Format("Cannot load {0}", Path.GetFileName(file)), TErrorSeverity.Error);
                        MyDefinitionErrors.Add(context, e.Message, TErrorSeverity.Error);
                    }
                }
                if (MyFakes.ENABLE_ROSLYN_SCRIPTS)
                {
                    assembly = MyScriptCompiler.Static.Compile(MyApiTarget.Mod, assemblyName, m_cachedFiles.Select(file => new Script(file, IlCompiler.UpdateCompatibility(file))), m_messages).Result;
                    compiled = assembly != null;
                }
                else
                {
                    compiled = IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
                    m_messages.AddRange(m_errors.Select(m => new MyScriptCompiler.Message(TErrorSeverity.Error, m)));
                }
            }
            else
            {
                if (MyFakes.ENABLE_ROSLYN_SCRIPTS)
                {
                    assembly = MyScriptCompiler.Static.Compile(MyApiTarget.Mod, assemblyName, scriptFiles.Select(file => new Script(file, IlCompiler.UpdateCompatibility(file))), m_messages).Result;
                    compiled = assembly != null;
                }
                else
                {
                    compiled = IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
                    m_messages.AddRange(m_errors.Select(m => new MyScriptCompiler.Message(TErrorSeverity.Error, m)));
                }
            }
            Debug.Assert(compiled == (assembly != null), "Compile results inconsistency!");
            if (assembly != null && compiled)
                AddAssembly(context, MyStringId.GetOrCompute(assemblyName), assembly);
            else
            {
                MyDefinitionErrors.Add(context, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var message in m_messages)
                {
                    MyDefinitionErrors.Add(context, message.Text, message.Severity);
                    Debug.Assert(message.Severity != TErrorSeverity.Error, message.Text);
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
#endif
        }
Example #35
0
        public void GetPlanetMaps(string folder, MyModContext context, MyPlanetMapTypeSet mapsToUse, out MyCubemap[] maps)
        {
            int num;
            int num2;

            maps = new MyCubemap[4];
            MyCubemapData <byte>[] dataArray = new MyCubemapData <byte> [0x18];
            byte[][] streams = new byte[4][];
            if (mapsToUse == 0)
            {
                goto TR_000A;
            }
            else
            {
                num = 0;
            }
            goto TR_0026;
TR_000A:
            num2 = 0;
            while (num2 < 4)
            {
                if (dataArray[num2] != null)
                {
                    MyCubemapData <byte>[] faces = new MyCubemapData <byte> [6];
                    int index = 0;
                    while (true)
                    {
                        if (index >= 6)
                        {
                            maps[num2] = new MyCubemap(faces);
                            break;
                        }
                        faces[index] = dataArray[num2 + (index * 4)];
                        index++;
                    }
                }
                num2++;
            }
            return;

TR_000D:
            num++;
TR_0026:
            while (true)
            {
                if (num >= 6)
                {
                    break;
                }
                string name = Path.Combine(folder, MyCubemapHelpers.GetNameForFace(num));
                try
                {
                    string str;
                    Image  image = this.TryGetPlanetTexture(name, context, "_mat", out str);
                    if (image == null)
                    {
                        this.ClearMatValues(dataArray);
                        break;
                    }
                    using (image)
                    {
                        PixelBuffer buffer = image.GetPixelBuffer(0, 0, 0);
                        if ((buffer.Format != Format.B8G8R8A8_UNorm) && (buffer.Format != Format.R8G8B8A8_UNorm))
                        {
                            object[] args = new object[] { buffer.Format, str };
                            MyLog.Default.Error("While loading maps from {1}: Unsupported planet map format: {0}.", args);
                            break;
                        }
                        if (buffer.Width == buffer.Height)
                        {
                            if (mapsToUse.HasFlag(MyPlanetMapTypeSet.Material))
                            {
                                dataArray[num * 4] = new MyCubemapData <byte>(buffer.Width, null);
                                streams[0]         = dataArray[num * 4].Data;
                            }
                            if (mapsToUse.HasFlag(MyPlanetMapTypeSet.Biome))
                            {
                                dataArray[(num * 4) + 1] = new MyCubemapData <byte>(buffer.Width, null);
                                streams[1] = dataArray[(num * 4) + 1].Data;
                            }
                            if (mapsToUse.HasFlag(MyPlanetMapTypeSet.Ore))
                            {
                                dataArray[(num * 4) + 2] = new MyCubemapData <byte>(buffer.Width, null);
                                streams[2] = dataArray[(num * 4) + 2].Data;
                            }
                            if (buffer.Format == Format.B8G8R8A8_UNorm)
                            {
                                streams[2] = streams[0];
                                streams[0] = streams[2];
                            }
                            this.ReadChannelsFromImage(streams, buffer);
                            image.Dispose();
                            goto TR_000D;
                        }
                        else
                        {
                            object[] args = new object[] { str };
                            MyLog.Default.Error("While loading maps from {0}: Width and height must be the same.", args);
                        }
                        break;
                    }
                }
                catch (Exception exception)
                {
                    MyLog.Default.Error(exception.ToString(), Array.Empty <object>());
                    break;
                }
                goto TR_000D;
            }
            goto TR_000A;
        }
        private void Handle(ProfilerRequestType type)
        {
            var          ticks       = SampleTicks;
            var          top         = Top;
            long?        factionMask = null;
            long?        playerMask  = null;
            long?        entityMask  = null;
            MyModContext modFilter   = null;
            long?        reportGPS   = null;

            foreach (var arg in Context.Args)
            {
                if (arg.StartsWith("--ticks="))
                {
                    ticks = ulong.Parse(arg.Substring("--ticks=".Length));
                }
                else if (arg.StartsWith("--top="))
                {
                    top = int.Parse(arg.Substring("--top=".Length));
                }
                else if (arg.StartsWith("--faction="))
                {
                    var name = arg.Substring("--faction=".Length);
                    if (!ResolveFaction(name, out var id))
                    {
                        Context.Respond($"Failed to find faction {name}");
                        return;
                    }

                    factionMask = id?.FactionId ?? 0;
                }
                else if (arg.StartsWith("--player="))
                {
                    var name = arg.Substring("--player=".Length);
                    if (!ResolveIdentity(name, out var id))
                    {
                        Context.Respond($"Failed to find player {name}");
                        return;
                    }

                    playerMask = id?.IdentityId ?? 0;
                }
                else if (arg.StartsWith("--entity="))
                {
                    var id  = long.Parse(arg.Substring("--entity=".Length));
                    var ent = MyEntities.GetEntityById(id);
                    if (ent == null)
                    {
                        Context.Respond($"Failed to find entity with ID={id}");
                        return;
                    }

                    entityMask = ent.EntityId;
                }
                else if (arg == "--this")
                {
                    var controlled = Context.Player?.Controller?.ControlledEntity?.Entity;
                    if (controlled == null)
                    {
                        Context.Respond($"You must have a controlled entity to use the --this argument");
                        return;
                    }

                    MyCubeGrid grid;
                    var        tmp = controlled;
                    do
                    {
                        grid = tmp as MyCubeGrid;
                        if (grid != null)
                        {
                            break;
                        }
                        tmp = tmp.Parent;
                    } while (tmp != null);

                    if (grid == null)
                    {
                        Context.Respond($"You must be controlling a grid to use the --this argument");
                        return;
                    }

                    entityMask = grid.EntityId;
                }
                else if (arg == "--gps")
                {
                    var controlled = Context.Player;
                    if (controlled == null)
                    {
                        Context.Respond($"GPS return can only be used by players");
                        return;
                    }

                    reportGPS = controlled.IdentityId;
                    CleanGPS(reportGPS.Value);
                }
                else if (arg.StartsWith("--mod="))
                {
                    var nam = arg.Substring("--mod=".Length);
                    foreach (var mod in MySession.Static.Mods)
                    {
                        var ctx = new MyModContext();
                        ctx.Init(mod);
                        if (ctx.ModId.Equals(nam, StringComparison.OrdinalIgnoreCase) || ctx.ModId.Equals(nam + ".sbm", StringComparison.OrdinalIgnoreCase) || ctx.ModName.Equals(nam, StringComparison.OrdinalIgnoreCase))
                        {
                            modFilter = ctx;
                            break;
                        }
                    }
                    if (nam.Equals("base", StringComparison.OrdinalIgnoreCase) || nam.Equals("keen", StringComparison.OrdinalIgnoreCase))
                    {
                        modFilter = MyModContext.BaseGame;
                    }

                    // ReSharper disable once InvertIf
                    if (modFilter == null)
                    {
                        Context.Respond($"Failed to find mod {nam}");
                        return;
                    }
                }
            }

            if (!ProfilerData.ChangeMask(playerMask, factionMask, entityMask, modFilter))
            {
                Context.Respond($"Failed to change profiling mask.  There can only be one.");
                return;
            }

            var req     = new ProfilerRequest(type, ticks);
            var context = Context;

            req.OnFinished += (printByPassCount, results) =>
            {
                for (var i = 0; i < Math.Min(top, results.Length); i++)
                {
                    var r             = results[i];
                    var formattedTime = FormatTime(r.MsPerTick);
                    var hits          = results[i].HitsPerTick;
                    var hitsUnit      = results[i].HitsUnit;
                    var formattedName = string.Format(r.Name ?? "unknown", i, formattedTime, hits, hitsUnit);
                    var formattedDesc = string.Format(r.Description ?? "", i, formattedTime, hits, hitsUnit);
                    if (reportGPS.HasValue || !r.Position.HasValue)
                    {
                        context.Respond(printByPassCount
                            ? $"{formattedName} {formattedDesc} took {hits:F1} {hitsUnit}"
                            : $"{formattedName} {formattedDesc} took {formattedTime} ({hits:F1} {hitsUnit})");
                        if (!reportGPS.HasValue || !r.Position.HasValue)
                        {
                            continue;
                        }
                        var gpsDisplay = printByPassCount ? $"{hits:F1} {hitsUnit} {formattedName}" : $"{formattedTime} {formattedName}";
                        var gpsDesc    = formattedDesc + $" {hits:F1} {hitsUnit}";
                        var gps        = new MyGps(new MyObjectBuilder_Gps.Entry
                        {
                            name        = gpsDisplay,
                            DisplayName = gpsDisplay,
                            coords      = r.Position.Value,
                            showOnHud   = true,
                            color       = VRageMath.Color.Purple,
                            description = gpsDesc,
                            entityId    = 0,
                            isFinal     = false
                        });
                        MyAPIGateway.Session?.GPS.AddGps(reportGPS.Value, gps);
                        var set = GpsForIdentity.GetOrAdd(reportGPS.Value, (x) => new HashSet <int>());
                        lock (set)
                            set.Add(gps.Hash);
                        continue;
                    }

                    var posData =
                        $"{r.Position.Value.X.ToString(ProfilerRequest.DistanceFormat)},{r.Position.Value.Y.ToString(ProfilerRequest.DistanceFormat)},{r.Position.Value.Z.ToString(ProfilerRequest.DistanceFormat)}";
                    context.Respond(
                        printByPassCount
                            ? $"{formattedName} {formattedDesc} took ({hits:F1} {hitsUnit})  @ {posData}"
                            : $"{formattedName} {formattedDesc} took {formattedTime} ({hits:F1} {hitsUnit})  @ {posData}");
                }

                {
                    var    totalUpdates = 0d;
                    var    totalTime    = 0d;
                    string hitsUnit     = null;
                    for (var i = Math.Min(top, results.Length) + 1; i < results.Length; i++)
                    {
                        var r = results[i];
                        totalUpdates += r.HitsPerTick;
                        totalTime    += r.MsPerTick;
                        hitsUnit      = r.HitsUnit;
                    }

                    if (totalUpdates > 0)
                    {
                        context.Respond(printByPassCount
                            ? $"Others took {totalUpdates:F1} {hitsUnit}"
                            : $"Others took {FormatTime(totalTime)} ({totalUpdates:F1} {hitsUnit})");
                    }
                }
            };
            var timeEstMs = ticks * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * 1000f / (MyMultiplayer.Static?.ServerSimulationRatio ?? 1);

            context.Respond($"Profiling for {type} started, results in {ticks} ticks (about {FormatTime(timeEstMs)})");
            ProfilerData.Submit(req);
        }
        // receiving messages
        private void LiveDebugging_ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acContentPath = msgReload.ACContentAddress;
                    string acAddress = msgReload.ACAddress;
                    string acName = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var firstDef = allDefinitions.Definitions[0];
                        MyModContext context = new MyModContext();
                        context.Init("AnimationControllerDefinition", acAddress, acContentPath);
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);

                        // post process and update in def. manager
                        MyAnimationControllerDefinition originalAnimationControllerDefinition =
                            MyDefinitionManagerBase.Static.GetDefinition<MyAnimationControllerDefinition>(
                                animSubtypeNameHash);

                        var postprocessor = MyDefinitionManagerBase.GetPostProcessor(typeof(MyObjectBuilder_AnimationControllerDefinition));
                        if (postprocessor != null)
                        {
                            MyDefinitionPostprocessor.Bundle originalBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context = MyModContext.BaseGame,
                                Definitions = new Dictionary<MyStringHash, MyDefinitionBase>
                                {
                                    {animSubtypeNameHash, originalAnimationControllerDefinition}
                                },
                                Set = new MyDefinitionSet()
                            };
                            originalBundle.Set.AddDefinition(originalAnimationControllerDefinition);

                            MyDefinitionPostprocessor.Bundle overridingBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context = context,
                                Definitions = new Dictionary<MyStringHash, MyDefinitionBase>
                                {
                                    {animSubtypeNameHash, animationControllerDefinition}
                                },
                                Set = new MyDefinitionSet()
                            };
                            overridingBundle.Set.AddDefinition(animationControllerDefinition);

                            // postprocess -> override existing definition in memory
                            postprocessor.AfterLoaded(ref overridingBundle);
                            postprocessor.OverrideBy(ref originalBundle, ref overridingBundle);
                        }

                        // swap animation controller for each entity
                        foreach (var component in m_skinnedEntityComponents)
                        {
                            if (component != null && component.SourceId.SubtypeName == acName)
                            {
                                component.Clear();
                                component.InitFromDefinition(originalAnimationControllerDefinition, forceReloadMwm: true); // reload from original def that was modified by postprocessor
                                if (component.ReloadBonesNeeded != null)
                                    component.ReloadBonesNeeded();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
Example #38
0
        /// <summary>
        /// Compiles the mod
        /// </summary>
        /// <returns></returns>
        public bool Compile()
        {
            // Compile
            if (m_compile)
            {
                if (m_type == WorkshopType.Mod)
                {
                    if (_compileMethod != null)
                    {
                        MySandboxGame.Log.WriteLineAndConsole("Compiling...");
#if SE
                        var mod = new MyModContext();

                        // Because of a regression in SE, we need to create a checkpoint ModItem to set the Id.
                        var modob = new MyObjectBuilder_Checkpoint.ModItem();
                        modob.Name = Path.GetFileName(m_modPath);

                        if (ModId.Length > 0)
                        {
                            modob.PublishedFileId      = m_workshopItems[m_modId[0]].Id;
                            modob.PublishedServiceName = m_workshopItems[m_modId[0]].ServiceName;
                            modob.FriendlyName         = m_workshopItems[m_modId[0]].Title;
                            modob.SetModData(m_workshopItems[m_modId[0]]);
                        }
                        else
                        {
                            // Fake it, so the compile still works
                            modob.PublishedFileId      = 0;
                            modob.PublishedServiceName = MyGameService.GetDefaultUGC().ServiceName;
                            modob.FriendlyName         = Title;
                        }
                        mod.Init(modob);

                        // Call init again, to make sure the path in set properly to the local mod directory
                        mod.Init(m_title, null, m_modPath);
#else
                        var workshopItem = new MyLocalWorkshopItem(new VRage.ObjectBuilders.SerializableModReference(Path.GetFileName(m_modPath), 0));
                        var mod          = new MyModContext(workshopItem, 0);
#endif
                        _compileMethod(
#if SE
                            m_modPath,
#endif
                            mod
                            );

                        // Process any errors
#if SE
                        var errors = MyDefinitionErrors.GetErrors();
#else
                        var compileMessages = _scriptManager.GetType().GetField("m_messages", BindingFlags.NonPublic | BindingFlags.Instance);
                        var errors          = (compileMessages.GetValue(_scriptManager) as List <MyScriptCompiler.Message>) ?? new List <MyScriptCompiler.Message>();
#endif
                        if (errors.Count > 0)
                        {
                            int errorCount   = 0;
                            int warningCount = 0;

                            // This is not efficient, but I'm lazy
                            foreach (var error in errors)
                            {
                                if (error.Severity >= TErrorSeverity.Error)
                                {
                                    errorCount++;
                                }
                                if (error.Severity == TErrorSeverity.Warning)
                                {
                                    warningCount++;
                                }
                            }

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile errors:", errorCount));
                            }
                            if (warningCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile warnings:", warningCount));
                            }

                            // Output raw message, which is usually in msbuild friendly format, for automated tools
                            foreach (var error in errors)
#if SE
                            { System.Console.WriteLine(error.Message); }
#else
                            { System.Console.WriteLine(error.Text); }
#endif

#if SE
                            MyDefinitionErrors.Clear();     // Clear old ones, so next mod starts fresh
#endif

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole("Compilation FAILED!");
                                return(false);
                            }
                        }
                        MySandboxGame.Log.WriteLineAndConsole("Compilation successful!");
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "LoadScripts"));
                    }
                }
#if SE
                else if (m_type == WorkshopType.IngameScript)
                {
                    // Load the ingame script from the disk
                    // I don't like this, but meh
                    var input   = new StreamReader(Path.Combine(m_modPath, "Script.cs"));
                    var program = input.ReadToEnd();
                    input.Close();
                    var scripts = new List <Script>();
                    scripts.Add(MyScriptCompiler.Static.GetIngameScript(program, "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name, "sealed partial"));

                    var messages = new List <Message>();
                    var assembly = MyVRage.Platform.Scripting.CompileIngameScriptAsync(Path.Combine(VRage.FileSystem.MyFileSystem.UserDataPath, "SEWT-Script" + Path.GetFileName(m_modPath)), program, out messages, "SEWT Compiled PB Script", "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name).Result;

                    if (messages.Count > 0)
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile messages:", messages.Count));
                        int errors = 0;
                        foreach (var msg in messages)
                        {
                            MySandboxGame.Log.WriteLineAndConsole(msg.Text);

                            if (msg.IsError)
                            {
                                errors++;
                            }
                        }
                        if (errors > 0)
                        {
                            return(false);
                        }
                    }

                    if (assembly == null)
                    {
                        return(false);
                    }
                }
#endif
                return(true);
            }
            return(true);
        }
Example #39
0
        private void LoadScripts(string path, MyModContext mod = null)
        {
#if XB1
#if !XB1_SKIPASSERTFORNOW
			System.Diagnostics.Debug.Assert(false, "Unsupported runtime script compilation on XB1.");
#endif // !XB1_SKIPASSERTFORNOW
#else
            if (!MyFakes.ENABLE_SCRIPTS)
                return;

            var fsPath = Path.Combine(path, "Data", "Scripts");
            var scriptFiles = MyFileSystem.GetFiles(fsPath, "*.cs");//, searchOption: VRage.FileSystem.SearchOption.TopDirectoryOnly);
            try
            {
                if (scriptFiles.Count() == 0)
                    return;
            }
            catch (Exception)
            {
                MySandboxGame.Log.WriteLine(string.Format("Failed to load scripts from: {0}", path));
                return;
            }
            var isZip = VRage.FileSystem.MyZipFileProvider.IsZipFile(path);
            List<string> files = new List<string>();
            var split = scriptFiles.First().Split('\\');
            string scriptDir = split[split.Length - 2];
            foreach (var scriptFile in scriptFiles)
            {
                split = scriptFile.Split('\\');
                var extension = split[split.Length - 1].Split('.').Last();
                if (extension != "cs")
                    continue;
                var idx = Array.IndexOf(split, "Scripts") + 1; //index of script directory (there can be any dir hierarchy above it)
                if (split[idx] == scriptDir)
                    files.Add(scriptFile);
                else
                {
                    Compile(files, string.Format("{0}_{1}", mod.ModId, scriptDir), isZip, mod);
                    files.Clear();
                    scriptDir = split[split.Length - 2];
                    files.Add(scriptFile);
                }
            }
            Compile(files.ToArray(), Path.Combine(MyFileSystem.ModsPath, string.Format("{0}_{1}", mod.ModId, scriptDir)), isZip, mod);
            files.Clear();
#endif
        }
        public void GetPlanetMaps(string folder, MyModContext context, MyPlanetMaps mapsToUse, out MyCubemap[] maps)
        {
            if (m_planetMaps.ContainsKey(folder))
            {
                maps = m_planetMaps[folder];
                return;
            }

            maps = new MyCubemap[4];
            
            MyCubemapData<byte>[] tmpMaps = new MyCubemapData<byte>[4 * 6];

            byte[][] streams = new byte[4][];

            string fullPath;

            ProfilerShort.Begin("MyHeightmapLoadingSystem::GetPlanetMaps()");

            ProfilerShort.Begin("Load _mat");
            // Round one: material, ore, biome
            if (mapsToUse.Material || mapsToUse.Biome || mapsToUse.Ores)
                for (int i = 0; i < 6; ++i)
                {
                    string name = Path.Combine(folder, MyCubemapHelpers.GetNameForFace(i));

                    using (var texture = TryGetPlanetTexture(name, context, "_mat", out fullPath))
                    {
                        if (texture == null)
                        {
                            ClearMatValues(tmpMaps);
                            break;
                        }

                        PixelBuffer buffer = texture.GetPixelBuffer(0, 0, 0);

                        if (buffer.Format != Format.B8G8R8A8_UNorm &&
                            buffer.Format != Format.R8G8B8A8_UNorm)
                        {
                            MyDebug.FailRelease("While loading maps from {1}: Unsupported planet map format: {0}.", buffer.Format, fullPath);
                            break;
                        }

                        if (buffer.Width != buffer.Height)
                        {
                            MyDebug.FailRelease("While loading maps from {0}: Width and height must be the same.", fullPath);
                            break;
                        }

                        if (mapsToUse.Material)
                        {
                            tmpMaps[i * 4] = new MyCubemapData<byte>(buffer.Width);
                            streams[0] = tmpMaps[i * 4].Data;
                        }

                        if (mapsToUse.Biome)
                        {
                            tmpMaps[i * 4 + 1] = new MyCubemapData<byte>(buffer.Width);
                            streams[1] = tmpMaps[i * 4 + 1].Data;
                        }

                        if (mapsToUse.Ores)
                        {
                            tmpMaps[i * 4 + 2] = new MyCubemapData<byte>(buffer.Width);
                            streams[2] = tmpMaps[i * 4 + 2].Data;
                        }

                        // Invert channels for BGRA
                        if (buffer.Format == Format.B8G8R8A8_UNorm)
                        {
                            var tmp = streams[2];
                            streams[2] = streams[0];
                            streams[0] = tmp;
                        }
                        ReadChannelsFromImage(streams, buffer);
                        texture.Dispose();
                    }
                }

            ProfilerShort.BeginNextBlock("Load _add");
            // round two: add map
            if (mapsToUse.Occlusion)
                for (int i = 0; i < 6; ++i)
                {
                    string name = Path.Combine(folder, MyCubemapHelpers.GetNameForFace(i));

                    using (var texture = TryGetPlanetTexture(name, context,"_add", out fullPath))
                    {
                        if (texture == null)
                        {
                            ClearAddValues(tmpMaps);
                            break;
                        }

                        PixelBuffer buffer = texture.GetPixelBuffer(0, 0, 0);

                        if (buffer.Format != Format.B8G8R8A8_UNorm &&
                            buffer.Format != Format.R8G8B8A8_UNorm)
                        {
                            MyDebug.FailRelease("While loading maps from {1}: Unsupported planet map format: {0}.", buffer.Format, fullPath);
                            break;
                        }

                        if (buffer.Width != buffer.Height)
                        {
                            MyDebug.FailRelease("While loading maps from {0}: Width and height must be the same.", fullPath);
                            break;
                        }

                        if (mapsToUse.Occlusion)
                        {
                            tmpMaps[i * 4 + 3] = new MyCubemapData<byte>(buffer.Width);
                            streams[0] = tmpMaps[i * 4 + 3].Data;
                        }

                        streams[1] = streams[2] = null;

                        // Invert channels for BGRA
                        if (buffer.Format == Format.B8G8R8A8_UNorm)
                        {
                            var tmp = streams[2];
                            streams[2] = streams[0];
                            streams[0] = tmp;
                        }

                        ReadChannelsFromImage(streams, buffer);
                        texture.Dispose();
                    }
                }

            ProfilerShort.BeginNextBlock("Finish");

            for (int i = 0; i < 4; ++i)
            {
                if (tmpMaps[i] != null)
                {
                    var cmaps = new MyCubemapData<byte>[6];
                    for (int j = 0; j < 6; j++)
                    {
                        cmaps[j] = tmpMaps[i + j * 4];
                    }
                    maps[i] = new MyCubemap(cmaps);
                }
            }

            m_planetMaps[folder] = maps;

            ProfilerShort.End();
            ProfilerShort.End();
        }
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped, MyModContext context)
        {
#if XB1
            System.Diagnostics.Debug.Assert(false, "Unsupported runtime script compilation on XB1.");
#else
            Assembly assembly = null;
            bool     compiled = false;
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream  = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(context, string.Format("Cannot load {0}", Path.GetFileName(file)), TErrorSeverity.Error);
                        MyDefinitionErrors.Add(context, e.Message, TErrorSeverity.Error);
                    }
                }
                if (MyFakes.ENABLE_ROSLYN_SCRIPTS)
                {
                    assembly = MyScriptCompiler.Static.Compile(MyApiTarget.Mod, assemblyName, m_cachedFiles.Select(file => new Script(file, IlCompiler.UpdateCompatibility(file))), m_messages).Result;
                    compiled = assembly != null;
                }
                else
                {
                    compiled = IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
                    m_messages.AddRange(m_errors.Select(m => new MyScriptCompiler.Message(TErrorSeverity.Error, m)));
                }
            }
            else
            {
                if (MyFakes.ENABLE_ROSLYN_SCRIPTS)
                {
                    assembly = MyScriptCompiler.Static.Compile(MyApiTarget.Mod, assemblyName, scriptFiles.Select(file => new Script(file, IlCompiler.UpdateCompatibility(file))), m_messages).Result;
                    compiled = assembly != null;
                }
                else
                {
                    compiled = IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
                    m_messages.AddRange(m_errors.Select(m => new MyScriptCompiler.Message(TErrorSeverity.Error, m)));
                }
            }
            Debug.Assert(compiled == (assembly != null), "Compile results inconsistency!");
            if (assembly != null && compiled)
            {
                AddAssembly(context, MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(context, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var message in m_messages)
                {
                    MyDefinitionErrors.Add(context, message.Text, message.Severity);
                    Debug.Assert(message.Severity != TErrorSeverity.Error, message.Text);
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
#endif
        }
        public MyHeightmapFace GetHeightMap(string folderName, string faceName, MyModContext context)
        {
            ProfilerShort.Begin("MyHeightmapLoadingSystem::GetHeightMap()");
            if (m_first)
            {
                PreloadCrashingData();
                m_first = false;
            }
            string fullPath = null;
            bool found = false;


            // Look for modded textures
            if (!context.IsBaseGame)
            {
                fullPath = Path.Combine(Path.Combine(context.ModPathData,"PlanetDataFiles"), folderName, faceName);
                if (MyFileSystem.FileExists(fullPath + ".png")) {
                    found = true;
                    fullPath += ".png";
                } else if (MyFileSystem.FileExists(fullPath + ".dds"))
                {
                    found = true;
                    fullPath += ".dds";
                }
            }

            // Use default ones
            if (!found)
            {
                fullPath = Path.Combine(m_planetDataFolder, folderName, faceName);
                if (MyFileSystem.FileExists(fullPath + ".png"))
                {
                    found = true;
                    fullPath += ".png";
                }
                else if (MyFileSystem.FileExists(fullPath + ".dds"))
                {
                    fullPath += ".dds";
                }


            }

            MyHeightmapFace value;
            if (m_heightMaps.TryGetValue(fullPath, out value))
            {
                ProfilerShort.End();
                return value;
            }
            try
            {
                using (SharpDXImage image = LoadTexture(fullPath))
                {
                    if (image == null)
                    {
                        MyLog.Default.WriteLine("Could not load texture {0}, no suitable format found. " + fullPath);
                    }
                    else
                    {
                        PixelBuffer buffer = image.GetPixelBuffer(0, 0, 0);

                        value = new MyHeightmapFace(buffer.Height);

                        if (buffer.Format == Format.R16_UNorm)
                        {
                            PrepareHeightMap(value, buffer);
                        }
                        else if (buffer.Format == Format.R8_UNorm)
                        {
                            PrepareHeightMap8Bit(value, buffer);
                        }
                        else
                        {
                            MyDebug.FailRelease(String.Format("Heighmap texture {0}: Invalid format {1} (expecting R16_UNorm or R8_UNorm).", fullPath, buffer.Format));
                        }
                        buffer = null;
                        image.Dispose();
                    }
                }
                m_heightMaps[fullPath] = value;
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine(e.Message);
            }
            ProfilerShort.End();

            return value;
        }
        // Prepare an environment definition from legacy planet definitions.
        public static MyWorldEnvironmentDefinition FromLegacyPlanet(MyObjectBuilder_PlanetGeneratorDefinition pgdef, MyModContext context)
        {
            var envOb = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ProceduralWorldEnvironment>(pgdef.Id.SubtypeId);;

            envOb.Id = new SerializableDefinitionId(envOb.TypeId, envOb.SubtypeName);

            // storage
            var staticModule = new SerializableDefinitionId(typeof(MyObjectBuilder_ProceduralEnvironmentModuleDefinition), "Static");

            var memoryModule = new SerializableDefinitionId(typeof(MyObjectBuilder_ProceduralEnvironmentModuleDefinition), "Memory");

            // proxies
            var breakable = new SerializableDefinitionId(typeof(MyObjectBuilder_EnvironmentModuleProxyDefinition), "Breakable");

            var voxelmap = new SerializableDefinitionId(typeof(MyObjectBuilder_EnvironmentModuleProxyDefinition), "VoxelMap");

            var botSpawner = new SerializableDefinitionId(typeof(MyObjectBuilder_EnvironmentModuleProxyDefinition), "BotSpawner");

            // TODO: Implement environmental particles.
            var environmentalParticleMarker = new SerializableDefinitionId(typeof(MyObjectBuilder_EnvironmentModuleProxyDefinition), "EnvironmentalParticles");

            envOb.ItemTypes = new[]
            {
                new MyEnvironmentItemTypeDefinition()
                {
                    LodFrom  = -1,
                    Name     = "Tree",
                    Provider = staticModule,
                    Proxies  = new [] { breakable }
                },
                new MyEnvironmentItemTypeDefinition()
                {
                    LodFrom  = 0,
                    Name     = "Bush",
                    Provider = staticModule,
                    Proxies  = new [] { breakable }
                },
                new MyEnvironmentItemTypeDefinition()
                {
                    LodFrom  = 0,
                    Name     = "VoxelMap",
                    Provider = memoryModule,
                    Proxies  = new [] { voxelmap }
                },
                new MyEnvironmentItemTypeDefinition()
                {
                    LodFrom  = 0,
                    Name     = "Bot",
                    Provider = null,
                    Proxies  = new [] { botSpawner }
                },
            };

            envOb.ScanningMethod  = MyProceduralScanningMethod.Random;
            envOb.ItemsPerSqMeter = 0.0017;

            envOb.MaxSyncLod = 0;
            envOb.SectorSize = 384;

            List <MyProceduralEnvironmentMapping> mappings = new List <MyProceduralEnvironmentMapping>();

            List <MyEnvironmentItemInfo> items = new List <MyEnvironmentItemInfo>();

            var defaultRule = new MyPlanetSurfaceRule();

            if (pgdef.EnvironmentItems != null)
            {
                foreach (var matmap in pgdef.EnvironmentItems)
                {
                    var map = new MyProceduralEnvironmentMapping();
                    map.Biomes    = matmap.Biomes;
                    map.Materials = matmap.Materials;

                    var rule = matmap.Rule ?? defaultRule;

                    map.Height    = rule.Height;
                    map.Latitude  = rule.Latitude;
                    map.Longitude = rule.Longitude;
                    map.Slope     = rule.Slope;

                    items.Clear();
                    foreach (var item in matmap.Items)
                    {
                        var it = new MyEnvironmentItemInfo
                        {
                            Density = item.Density,
                            Subtype = MyStringHash.GetOrCompute(item.SubtypeId)
                        };

                        switch (item.TypeId)
                        {
                        case "MyObjectBuilder_DestroyableItems":
                            it.Type = "Bush";
                            break;

                        case "MyObjectBuilder_Trees":
                            it.Type = "Tree";
                            break;

                        case "MyObjectBuilder_VoxelMapStorageDefinition":
                            it.Type = "VoxelMap";

                            if (item.SubtypeId == null)
                            {
                                var subtype = MyStringHash.GetOrCompute(string.Format("G({0})M({1})", item.GroupId, item.ModifierId));

                                var vcolDef = MyDefinitionManager.Static.GetDefinition <MyVoxelMapCollectionDefinition>(subtype);

                                if (vcolDef == null)
                                {
                                    var vdefOb = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_VoxelMapCollectionDefinition>(subtype.ToString());

                                    vdefOb.Id = new SerializableDefinitionId(vdefOb.TypeId, vdefOb.SubtypeName);

                                    vdefOb.StorageDefs = new MyObjectBuilder_VoxelMapCollectionDefinition.VoxelMapStorage[1]
                                    {
                                        new MyObjectBuilder_VoxelMapCollectionDefinition.VoxelMapStorage()
                                        {
                                            Storage = item.GroupId
                                        }
                                    };

                                    vdefOb.Modifier = item.ModifierId;

                                    vcolDef = new MyVoxelMapCollectionDefinition();
                                    vcolDef.Init(vdefOb, context);

                                    MyDefinitionManager.Static.Definitions.AddDefinition(vcolDef);
                                }

                                it.Subtype = subtype;
                            }

                            break;

                        default:
                            MyLog.Default.Error("Planet Generator {0}: Invalid Item Type: {1}", pgdef.SubtypeName, item.SubtypeId);
                            continue;
                            break;
                        }

                        if (it.Subtype == null)
                        {
                            MyLog.Default.Error("Planet Generator {0}: Missing subtype for item of type {1}", pgdef.SubtypeName, it.Type);
                            continue;
                        }

                        items.Add(it);
                    }

                    map.Items = items.ToArray();

                    mappings.Add(map);
                }
            }

            mappings.Capacity = mappings.Count;

            envOb.EnvironmentMappings = mappings.GetInternalArray();

            var def = new MyProceduralEnvironmentDefinition();

            def.Context = context;
            def.Init(envOb);

            return(def);
        }