Guest User

EvilSensor Patch #7

a guest
Nov 15th, 2014
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Diff 19.81 KB | None | 0 0
  1. diff --git a/Data/Scripts/EvilSensor/EvilSensor.cs b/Data/Scripts/EvilSensor/EvilSensor.cs
  2. index cdf99f5..e851c4d 100644
  3. --- a/Data/Scripts/EvilSensor/EvilSensor.cs
  4. +++ b/Data/Scripts/EvilSensor/EvilSensor.cs
  5. @@ -4,23 +4,24 @@
  6.  using Sandbox.ModAPI;
  7.  using Sandbox.ModAPI.Ingame;
  8.  using System;
  9. +using System.Collections;
  10. +using System.Collections.Generic;
  11. +using System.Linq;
  12. +using System.Text;
  13.  
  14.  namespace EvilSensor_1
  15.  {
  16.      [MyEntityComponentDescriptor(typeof(MyObjectBuilder_SensorBlock))]
  17.      public class EvilSensor : MyGameLogicComponent
  18.      {
  19. -        // Initialize them variables
  20. -        static String[] OreNames;
  21.  
  22.          IMySensorBlock Sensor;
  23.  
  24. +        StringBuilder logCache = new StringBuilder();
  25. +
  26.          public override void Close()
  27.          {
  28. -            /* State changed! I'm not sure how this part works since sensor_StateChanged  returns void?
  29. -             * Maybe someone could enlighten me?
  30. -             * I'm probably confused by the use of the -= operator.
  31. -             */
  32. +            // Remove sensor_StateChanged from the actions for Sensor.StateChanged
  33.              Sensor.StateChanged -= sensor_StateChanged;
  34.          }
  35.  
  36. @@ -32,53 +33,86 @@ public override MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false)
  37.  
  38.          public override void Init(MyObjectBuilder_EntityBase objectBuilder)
  39.          {
  40. -            // If OreNames is empty, get the String[] of names from one of our references
  41. -            if (OreNames == null)
  42. +            try
  43.              {
  44. -                MyDefinitionManager.Static.GetOreTypeNames(out OreNames);
  45. +                // Try to remove the old logs
  46. +                RemoveLocalFile();
  47. +                RemoveFile();
  48. +            }
  49. +            catch (Exception ex)
  50. +            {
  51. +                logCache.Append(ex + "\r\n");
  52. +            }
  53. +            try
  54. +            {
  55. +                // Go through all the ore & component names and put them in the logCache to be printed out later. Was having massive issues with writing to logs during Init.
  56. +                String[] oreNames;
  57. +                MyDefinitionManager.Static.GetOreTypeNames(out oreNames);
  58. +                List<MyComponentDefinition> componentList = Enumerable.OfType<MyComponentDefinition>((IEnumerable)MyDefinitionManager.Static.GetAllDefinitions()).ToList();
  59. +                foreach (var c in componentList)
  60. +                {
  61. +                    if (c != null)
  62. +                    {
  63. +                        logCache.Append(String.Format("ComponentList: {0}\r\n", c.Id.SubtypeName));
  64. +                    }
  65. +                }
  66. +                foreach (var o in oreNames)
  67. +                {
  68. +                    if (o != null)
  69. +                    {
  70. +                        logCache.Append(String.Format("OreList: {0}\r\n", o));
  71. +                    }
  72. +                }
  73. +                // Define that Sensor is a SensorBlock
  74. +                Sensor = Entity as IMySensorBlock;
  75. +                // Add sensor_StateChanged to the actions for Sensor.StateChanged
  76. +                Sensor.StateChanged += sensor_StateChanged;
  77. +            }
  78. +            catch (Exception ex)
  79. +            {
  80. +                logCache.Append(ex + "\r\n");
  81. +                return;
  82.              }
  83. -            // Define that Sensor is a SensorBloack
  84. -            Sensor = Entity as IMySensorBlock;
  85. -            /* State changed! I'm not sure how this part works since sensor_StateChanged  returns void?
  86. -             * Maybe someone could enlighten me?
  87. -             * I'm probably confused by the use of the += operator.
  88. -             */
  89. -            Sensor.StateChanged += sensor_StateChanged;
  90.          }
  91.  
  92.          void sensor_StateChanged(bool obj)
  93.          {
  94. +            // If the logCache has data, attempt to write and clear it. Append the exception otherwise.
  95. +            if (logCache.Length > 0)
  96. +            {
  97. +                try
  98. +                {
  99. +                    Logging.Instance.WriteLine(logCache.ToString());
  100. +                    logCache.Clear();
  101. +                }
  102. +                catch (Exception ex)
  103. +                {
  104. +                    logCache.Append(ex + "\r\n");
  105. +                }
  106. +            }
  107. +            /*
  108. +             * Check to make sure this is a server instance of the mod (It runs on the client as well),
  109. +             * otherwise a duplicate, non-functional object will be spawned by the client as well. (Duplicate bug)
  110. +             */
  111. +            if (!Sandbox.ModAPI.MyAPIGateway.Multiplayer.IsServer) return;
  112. +
  113.              // I think this part is depending on whether you entered or exited the range.
  114.              // !obj would be when you exited the range, so nothing happens.
  115.              if (!obj) return;
  116.  
  117.              // Define some mo' variables
  118. -            string ore = null;
  119. +            string objectName = "Iron";
  120.  
  121. -            string sensorName = Sensor.CustomName.ToLowerInvariant();
  122. +            string spawnType = "Ore";
  123. +
  124. +            string sensorName = Sensor.CustomName;
  125.  
  126.              VRageMath.Vector3 direction = Sensor.WorldMatrix.Forward;
  127.  
  128. -            var oreAmount = 100;
  129. +            var amount = 100;
  130.  
  131.              var distance = 1.5f;
  132.  
  133. -            string dataString = "";
  134. -
  135. -            //Loop through the ore names in the array and see if the sensor's name contains one of them
  136. -            foreach (var o in OreNames)
  137. -            {
  138. -                if (sensorName.Contains(o.ToLowerInvariant()))
  139. -                {
  140. -                    ore = o;
  141. -                    break;
  142. -                }
  143. -            }
  144. -            // If the sensor name does not contain an ore name, we exit here
  145. -            if (ore == null)
  146. -                return;
  147. -            // See if the sensor name contains the "data string" as defined
  148. -            // by beginning with "[" and ending with "]"
  149.              if (sensorName.Contains("[") && sensorName.Contains("]"))
  150.              {
  151.                  /*
  152. @@ -88,27 +122,60 @@ void sensor_StateChanged(bool obj)
  153.                  */
  154.                  try
  155.                  {
  156. -                    dataString = sensorName.Slice(sensorName.IndexOf("[") + 1, sensorName.LastIndexOf("]")).ToLowerInvariant().Replace(" ", "");
  157. +                    // Get the data string, convert it to lowercase, and remove all the spaces.
  158. +                    string dataString = sensorName.Slice(sensorName.IndexOf("[") + 1, sensorName.LastIndexOf("]")).Replace(" ", "");
  159.                      string dataSection;
  160.                      bool control = true;
  161. +                    // Loop through the string till all the data is gone
  162.                      while (control)
  163.                      {
  164. -                        if (dataString.Contains(";"))
  165. +                        // Check to see if the string contains any separators
  166. +                        if (dataString.Contains(";") || dataString.Contains(","))
  167.                          {
  168. -                            dataSection = dataString.Slice(0, dataString.IndexOf(";"));
  169. -                            dataString = dataString.Substring(dataString.IndexOf(";") + 1);
  170. -                            string tag = dataSection.Slice(0, dataSection.IndexOf(":") + 1);
  171. +                            // Separate the data section and remove it from the data string
  172. +                            if (dataString.Contains(";"))
  173. +                            {
  174. +                                dataSection = dataString.Slice(0, dataString.IndexOf(";"));
  175. +                                dataString = dataString.Substring(dataString.IndexOf(";") + 1);
  176. +                            }
  177. +                            else
  178. +                            {
  179. +                                dataSection = dataString.Slice(0, dataString.IndexOf(","));
  180. +                                dataString = dataString.Substring(dataString.IndexOf(",") + 1);
  181. +                            }
  182. +                            // Get the tag and data from the section we just got from the original string
  183. +                            string tag = dataSection.Slice(0, dataSection.IndexOf(":") + 1).ToLowerInvariant();
  184.                              string data = dataSection.Substring(dataSection.IndexOf(":") + 1);
  185. +                            // Set the data depending on what it is
  186.                              switch (tag)
  187.                              {
  188. +                                case "type:":
  189. +                                    // Check for / and \ as the separator
  190. +                                    if (data.Contains("/"))
  191. +                                    {
  192. +                                        spawnType = data.Slice(0, data.IndexOf("/"));
  193. +                                        objectName = data.Substring(data.IndexOf("/") + 1);
  194. +                                    }
  195. +                                    else if (data.Contains("\\"))
  196. +                                    {
  197. +                                        spawnType = data.Slice(0, data.IndexOf("\\"));
  198. +                                        objectName = data.Substring(data.IndexOf("\\") + 1);
  199. +                                    }
  200. +                                    else
  201. +                                    {
  202. +                                        // Set the default since its missing a separator
  203. +                                        spawnType = "Ore";
  204. +                                        objectName = "Iron";
  205. +                                    }
  206. +                                    break;
  207.                                  case "amt:":
  208. -                                    oreAmount = Convert.ToInt32(data);
  209. +                                    amount = Convert.ToInt32(data);
  210.                                      break;
  211.                                  case "dst:":
  212.                                      distance = Convert.ToSingle(data);
  213.                                      break;
  214.                                  case "dir:":
  215. -                                    switch (data)
  216. +                                    switch (data.ToLowerInvariant())
  217.                                      {
  218.                                          case "up":
  219.                                              direction = Sensor.WorldMatrix.Up;
  220. @@ -137,21 +204,34 @@ void sensor_StateChanged(bool obj)
  221.                                      break;
  222.                              }
  223.                          }
  224. +                        // Just get the data from the string since there are no separators
  225.                          else
  226.                          {
  227.                              dataSection = dataString;
  228. -                            string tag = dataSection.Slice(0, dataSection.IndexOf(":") + 1);
  229. +                            string tag = dataSection.Slice(0, dataSection.IndexOf(":") + 1).ToLowerInvariant();
  230.                              string data = dataSection.Substring(dataSection.IndexOf(":") + 1);
  231.                              switch (tag)
  232.                              {
  233. +                                case "type:":
  234. +                                    if (data.Contains("/"))
  235. +                                    {
  236. +                                        spawnType = data.Slice(0, data.IndexOf("/"));
  237. +                                        objectName = data.Substring(data.IndexOf("/") + 1);
  238. +                                    }
  239. +                                    else if (data.Contains("\\"))
  240. +                                    {
  241. +                                        spawnType = data.Slice(0, data.IndexOf("\\"));
  242. +                                        objectName = data.Substring(data.IndexOf("\\") + 1);
  243. +                                    }
  244. +                                    break;
  245.                                  case "amt:":
  246. -                                    oreAmount = Convert.ToInt32(data);
  247. +                                    amount = Convert.ToInt32(data);
  248.                                      break;
  249.                                  case "dst:":
  250.                                      distance = Convert.ToSingle(data);
  251.                                      break;
  252.                                  case "dir:":
  253. -                                    switch (data)
  254. +                                    switch (data.ToLowerInvariant())
  255.                                      {
  256.                                          case "up":
  257.                                              direction = Sensor.WorldMatrix.Up;
  258. @@ -182,31 +262,13 @@ void sensor_StateChanged(bool obj)
  259.                              control = false;
  260.                          }
  261.                      }
  262. -                    /* Old string handling
  263. -                    if (dataString.Contains("amt:") && dataString.Contains("dst:"))
  264. -                    {
  265. -                        if (dataString.IndexOf("amt:") < dataString.IndexOf("dst:")) {
  266. -                            oreAmount = Convert.ToInt32(dataString.Slice(dataString.IndexOf(":") + 1, dataString.IndexOf(";")));;
  267. -                            distance = Convert.ToSingle(dataString.Substring(dataString.LastIndexOf(":") + 1));
  268. -                        } else {
  269. -                            distance = Convert.ToSingle(dataString.Slice(dataString.IndexOf(":") + 1, dataString.IndexOf(";")));
  270. -                            oreAmount = Convert.ToInt32(dataString.Substring(dataString.LastIndexOf(":") + 1));
  271. -                        }
  272. -                    }
  273. -                    else if (dataString.Contains("amt:"))
  274. -                    {
  275. -                        oreAmount = Convert.ToInt32(dataString.Substring(dataString.LastIndexOf(":") + 1));
  276. -                    }
  277. -                    else if (dataString.Contains("dst:"))
  278. -                    {
  279. -                        distance = Convert.ToSingle(dataString.Substring(dataString.LastIndexOf(":") + 1));
  280. -                    }
  281. -                    */
  282.                  }
  283.                  catch (Exception ex)
  284.                  {
  285.                      // If something got fubar'ed, set the defaults and try to continue without crashing the damn game
  286. -                    oreAmount = 100;
  287. +                    spawnType = "Ore";
  288. +                    objectName = "Iron";
  289. +                    amount = 100;
  290.                      distance = 1.5f;
  291.                      direction = Sensor.WorldMatrix.Forward;
  292.                      Logging.Instance.WriteLine(String.Format("sensor_StateChanged(), String Parser: {0}", ex.ToString()));
  293. @@ -216,17 +278,30 @@ void sensor_StateChanged(bool obj)
  294.              {
  295.                  // Create the object to be spawned
  296.                  MyObjectBuilder_FloatingObject floatingBuilder = new MyObjectBuilder_FloatingObject();
  297. -                // Specify that the object is an ore inventory item of the amount & type specified by the user
  298. -                floatingBuilder.Item = new MyObjectBuilder_InventoryItem() { Amount = oreAmount, Content = new MyObjectBuilder_Ore() { SubtypeName = ore } };
  299. +
  300.                  floatingBuilder.PersistentFlags = MyPersistentEntityFlags2.InScene; // Very important, but I'm not sure why. I guess if not flagged as InScene, it won't be recognized as actually being there would be my guess.
  301. +
  302.                  // Set the postition and orientation of the object in the world.
  303.                  floatingBuilder.PositionAndOrientation = new MyPositionAndOrientation(Sensor.WorldMatrix.Translation + direction * distance, Sensor.WorldMatrix.Forward, Sensor.WorldMatrix.Up);
  304. -                // Check to make sure this is a server instance of the mod (I think it runs on client as well), otherwise a duplicate, non-functional object will be spawned by the client as well. (Duplicate bug)
  305. -                if (Sandbox.ModAPI.MyAPIGateway.Multiplayer.IsServer)
  306. +
  307. +                // Specify that the object is an inventory item of the type and amount specified
  308. +                switch (spawnType.ToLowerInvariant())
  309.                  {
  310. -                    // Finally, we actually create & spawn the damn thing in the world here. Enjoy!
  311. -                    var floatingObject = Sandbox.ModAPI.MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(floatingBuilder);
  312. +                    case "component":
  313. +                        floatingBuilder.Item = new MyObjectBuilder_InventoryItem() { Amount = amount, Content = new MyObjectBuilder_Component { SubtypeName = objectName } };
  314. +                        break;
  315. +                    case "ingot":
  316. +                        floatingBuilder.Item = new MyObjectBuilder_InventoryItem() { Amount = amount, Content = new MyObjectBuilder_Ingot() { SubtypeName = objectName } };
  317. +                        break;
  318. +                    case "ore":
  319. +                        floatingBuilder.Item = new MyObjectBuilder_InventoryItem() { Amount = amount, Content = new MyObjectBuilder_Ore() { SubtypeName = objectName } };
  320. +                        break;
  321. +                    default:
  322. +                        break;
  323.                  }
  324. +
  325. +                // Finally, we actually create & spawn the damn thing in the world here. Enjoy!
  326. +                var floatingObject = Sandbox.ModAPI.MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(floatingBuilder);
  327.              }
  328.              catch (Exception ex)
  329.              {
  330. @@ -248,6 +323,7 @@ public override void UpdateAfterSimulation10()
  331.  
  332.          public override void UpdateAfterSimulation100()
  333.          {
  334. +
  335.          }
  336.  
  337.          public override void UpdateBeforeSimulation()
  338. @@ -265,9 +341,25 @@ public override void UpdateBeforeSimulation100()
  339.          public override void UpdateOnceBeforeFrame()
  340.          {
  341.          }
  342. +
  343. +        internal void RemoveFile()
  344. +        {
  345. +            if (MyAPIGateway.Utilities.FileExistsInGlobalStorage("EvilSensor.log"))
  346. +            {
  347. +                MyAPIGateway.Utilities.DeleteFileInGlobalStorage("EvilSensor.log");
  348. +            }
  349. +        }
  350. +
  351. +        internal void RemoveLocalFile()
  352. +        {
  353. +            if (MyAPIGateway.Utilities.FileExistsInLocalStorage("EvilSensor.log", typeof(EvilSensor)))
  354. +            {
  355. +                MyAPIGateway.Utilities.DeleteFileInLocalStorage("EvilSensor.log", typeof(EvilSensor));
  356. +            }
  357. +        }
  358.      }
  359.  
  360. -    public static class Extensions
  361. +    internal static class Extensions
  362.      {
  363.          /// <summary>
  364.          /// Get the string slice between the two indexes.
  365. @@ -275,12 +367,20 @@ public static class Extensions
  366.          /// </summary>
  367.          public static string Slice(this string source, int start, int end)
  368.          {
  369. -            if (end < 0) // Keep this for negative end support
  370. +            try
  371. +            {
  372. +                if (end < 0) // Keep this for negative end support
  373. +                {
  374. +                    end = source.Length + end;
  375. +                }
  376. +                int len = end - start;               // Calculate length
  377. +                return source.Substring(start, len); // Return Substring of length
  378. +            }
  379. +            catch (Exception ex)
  380.              {
  381. -                end = source.Length + end;
  382. +                Logging.Instance.WriteLine(String.Format("Slice(): {0}", ex.ToString()));
  383. +                return null;
  384.              }
  385. -            int len = end - start;               // Calculate length
  386. -            return source.Substring(start, len); // Return Substring of length
  387.          }
  388.      }
  389.  }
  390. diff --git a/Data/Scripts/EvilSensor/Logging.cs b/Data/Scripts/EvilSensor/Logging.cs
  391. index 93962a5..8bd054b 100644
  392. --- a/Data/Scripts/EvilSensor/Logging.cs
  393. +++ b/Data/Scripts/EvilSensor/Logging.cs
  394. @@ -37,7 +37,7 @@ public Logging(string logFile)
  395.          {
  396.             try
  397.             {
  398. -               m_writer = MyAPIGateway.Utilities.WriteFileInLocalStorage(logFile, typeof(Logging));
  399. +               m_writer = MyAPIGateway.Utilities.WriteFileInGlobalStorage(logFile);
  400.                 m_instance = this;
  401.             }
  402.             catch { }
  403. @@ -74,7 +74,6 @@ public void Write(string text)
  404.              m_cache.Append(text);
  405.          }
  406.  
  407. -
  408.          internal void Close()
  409.          {
  410.              if (m_cache.Length > 0)
Advertisement
Add Comment
Please, Sign In to add comment