private static MyObjectBuilder_PrefabDefinition GetClone(MyPrefabDefinition prefab)
        {
            try
            {
                MyObjectBuilder_PrefabDefinition prefabDefinitionBase = (MyObjectBuilder_PrefabDefinition)MyObjectBuilderSerializer.Clone(((MyObjectBuilder_PrefabDefinition)prefab.GetObjectBuilder()));

                List <MyObjectBuilder_CubeGrid> tmpCubes = new List <MyObjectBuilder_CubeGrid>();
                foreach (MyObjectBuilder_CubeGrid tmpCubeGrid in prefab.CubeGrids)
                {
                    tmpCubes.Add((MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.Clone(tmpCubeGrid));
                }

                Core.GeneralLog.WriteToLog("GetClone", $"tmpCubes {tmpCubes.Count}");
                foreach (MyObjectBuilder_CubeGrid prefabX in tmpCubes)
                {
                    Core.GeneralLog.WriteToLog("GetClone", $"prefabX: {prefabX.DisplayName}");
                }

                //MyObjectBuilder_PrefabDefinition prefabDefinitionBase = (MyObjectBuilder_PrefabDefinition) prefab.GetObjectBuilder().Clone();
                //Core.GeneralLog.WriteToLog("GetClone", $"Results: {prefabDefinitionBase} {prefabDefinitionBase.SubtypeName} {prefabDefinitionBase.SubtypeId} {prefabDefinitionBase.TypeId} {prefabDefinitionBase.GetType()}");
                //Core.GeneralLog.WriteToLog("GetClone", $"Cloned: {prefabDefinitionBase.PrefabPath}");


                //MyObjectBuilder_PrefabDefinition myObjectBuilderBase = MyObjectBuilderSerializer.Clone(prefab.GetObjectBuilder()) as MyObjectBuilder_PrefabDefinition;
                //Core.GeneralLog.WriteToLog("GetClone", $"Cloned {myObjectBuilderBase == null}");
                //Core.GeneralLog.WriteToLog("GetClone", $"Cloned {myObjectBuilderBase.}");
                return(null);
            }
            catch (Exception e)
            {
                Core.GeneralLog.WriteToLog("GetClone", $"Prefab Processing Exception! {e}");
                return(null);
            }
        }
Exemple #2
0
        protected override void Init(MyObjectBuilder_DefinitionBase baseBuilder)
        {
            base.Init(baseBuilder);
            MyObjectBuilder_PrefabDefinition definition = baseBuilder as MyObjectBuilder_PrefabDefinition;

            this.PrefabPath  = definition.PrefabPath;
            this.Initialized = false;
        }
Exemple #3
0
        public void InitLazy(MyObjectBuilder_DefinitionBase baseBuilder)
        {
            MyObjectBuilder_PrefabDefinition definition = baseBuilder as MyObjectBuilder_PrefabDefinition;

            if ((definition.CubeGrid != null) || (definition.CubeGrids != null))
            {
                if (definition.CubeGrid == null)
                {
                    this.m_cubeGrids = definition.CubeGrids;
                }
                else
                {
                    this.m_cubeGrids = new MyObjectBuilder_CubeGrid[] { definition.CubeGrid };
                }
                this.m_boundingSphere = new VRageMath.BoundingSphere(Vector3.Zero, float.MinValue);
                this.m_boundingBox    = VRageMath.BoundingBox.CreateInvalid();
                MyObjectBuilder_CubeGrid[] cubeGrids = this.m_cubeGrids;
                int index = 0;
                while (index < cubeGrids.Length)
                {
                    Matrix identity;
                    MyObjectBuilder_CubeGrid grid = cubeGrids[index];
                    VRageMath.BoundingBox    box  = grid.CalculateBoundingBox();
                    if (grid.PositionAndOrientation == null)
                    {
                        identity = Matrix.Identity;
                    }
                    else
                    {
                        identity = (Matrix)grid.PositionAndOrientation.Value.GetMatrix();
                    }
                    this.m_boundingBox.Include(box.Transform(identity));
                    index++;
                }
                this.m_boundingSphere = VRageMath.BoundingSphere.CreateFromBoundingBox(this.m_boundingBox);
                cubeGrids             = this.m_cubeGrids;
                for (index = 0; index < cubeGrids.Length; index++)
                {
                    MyObjectBuilder_CubeGrid grid1 = cubeGrids[index];
                    grid1.CreatePhysics = true;
                    grid1.XMirroxPlane  = null;
                    grid1.YMirroxPlane  = null;
                    grid1.ZMirroxPlane  = null;
                }
                this.Initialized = true;
            }
        }
Exemple #4
0
        public bool SerializeGridsToPath(MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group relevantGroup, string gridTarget, string path, string playername)
        {
            var player = utils.GetPlayerByNameOrId(playername);

            try {
                List <MyObjectBuilder_CubeGrid> objectBuilders = new List <MyObjectBuilder_CubeGrid>();

                foreach (var node in relevantGroup.Nodes)
                {
                    MyCubeGrid grid = node.NodeData;

                    /* We wanna Skip Projections... always */
                    if (grid.Physics == null)
                    {
                        continue;
                    }

                    /* What else should it be? LOL? */
                    if (!(grid.GetObjectBuilder(true) is MyObjectBuilder_CubeGrid objectBuilder))
                    {
                        throw new ArgumentException(grid + " has a ObjectBuilder thats not for a CubeGrid");
                    }
                    objectBuilders.Add(objectBuilder);
                }
                MyObjectBuilder_PrefabDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_PrefabDefinition>();
                definition.Id        = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_PrefabDefinition)), gridTarget);
                definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray();
                long     i             = 0;
                bool     BlockCheck    = false;
                string   SubTypes      = Regex.Replace(Plugin.Config.SubTypes, @"\s+", string.Empty);
                string[] SubTypesArray = SubTypes.Split('-');
                /* Reset ownership as it will be different on the new server anyway and chceck to see if any listed blocks are included*/
                foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids)
                {
                    foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks)
                    {
                        cubeBlock.Owner   = 0L;
                        cubeBlock.BuiltBy = 0L;
                        i++;
                        /* Remove Pilot and Components (like Characters) from cockpits */
                        if (cubeBlock is MyObjectBuilder_Cockpit cockpit)
                        {
                            cockpit.Pilot = null;

                            if (cockpit.ComponentContainer != null)
                            {
                                var components = cockpit.ComponentContainer.Components;

                                if (components != null)
                                {
                                    for (int j = components.Count - 1; j >= 0; j--)
                                    {
                                        var component = components[j];

                                        if (component.TypeId == "MyHierarchyComponentBase")
                                        {
                                            components.RemoveAt(j);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                        if (SubTypesArray.Contains(cubeBlock.SubtypeId.ToString()))
                        {
                            BlockCheck = true;
                        }
                    }
                }
                //Block checking;
                if (Plugin.Config.EnableBlockEnforcement && Plugin.Config.BlockAllow && !BlockCheck)
                {
                    utils.NotifyMessage("You do not have the required block for Switching.", player.SteamUserId);
                    return(false);
                }
                if (Plugin.Config.EnableBlockEnforcement && Plugin.Config.BlockDisallow && BlockCheck)
                {
                    utils.NotifyMessage("You have disallowed blocks on your grid!", player.SteamUserId);
                    return(false);
                }
                //Economy stuff

                /*if (Plugin.Config.EnableEcon && Plugin.Config.PerTransfer && Plugin.Config.PerBlock) {
                 *  Log.Warn("Invalid econ setup");
                 *  utils.NotifyMessage("Invalid econ setup - please notify an admin.", player.SteamUserId);
                 *  return false;
                 * }
                 * if (Plugin.Config.EnableEcon) {
                 *  i = Plugin.Config.TransferCost * i;
                 *  if (Plugin.Config.PerTransfer) {
                 *      i = Plugin.Config.TransferCost;
                 *  }
                 *  long balance;
                 *  long withdraw = i;
                 *  player.TryGetBalanceInfo(out balance);
                 *  long mathResult = (balance - withdraw);
                 *  Log.Info("Cost of transfer for" + player.DisplayName + ": " + i);
                 *  CurrentCooldown cooldown = new CurrentCooldown(Plugin);
                 *  //verify that user wants to go ahead with transfer.
                 *  if (cooldown.Confirm(i, player.SteamUserId)) {
                 *      if (mathResult < 0) {
                 *          Log.Info("Cost of transfer for" + player.DisplayName + ": " + i);
                 *          utils.NotifyMessage("Not enough funds for transfer", player.SteamUserId);
                 *          return false;
                 *      }
                 *      player.RequestChangeBalance(-withdraw);
                 *  }
                 * }
                 */
                MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();
                builderDefinition.Prefabs = new MyObjectBuilder_PrefabDefinition[] { definition };
                bool worked = MyObjectBuilderSerializer.SerializeXML(path, false, builderDefinition);
                Log.Debug("exported " + path + " " + worked);
                return(true);
            } catch (Exception e) {
                Log.Fatal(e.Message);
                return(false);
            }
        }
Exemple #5
0
        private void Process(CommandFeedback feedback, IMyCubeGrid grid)
        {
            if (grid.CustomName == null || !grid.CustomName.StartsWithICase("EqProcBuild"))
            {
                return;
            }
            var ob = grid.GetObjectBuilder(true) as MyObjectBuilder_CubeGrid;

            if (ob == null)
            {
                return;
            }
            this.Info("Begin processing {0}", grid.CustomName);
            feedback?.Invoke("Processing {0}", grid.CustomName);
            try
            {
                var dummyDel  = new List <MyTuple <MyObjectBuilder_CubeBlock, string> >();
                var blockKeep = new List <MyObjectBuilder_CubeBlock>();
                var blockMap  = new Dictionary <Vector3I, MyObjectBuilder_CubeBlock>(Vector3I.Comparer);
                foreach (var block in ob.CubeBlocks)
                {
                    var mount = false;
                    foreach (var name in block.ConfigNames())
                    {
                        if (!name.StartsWithICase(MountDelegated) && !name.StartsWithICase(ReservedSpaceDelegated))
                        {
                            continue;
                        }
                        dummyDel.Add(MyTuple.Create(block, name));
                        mount = true;
                        break;
                    }
                    if (mount)
                    {
                        continue;
                    }

                    var      blockMin = (Vector3I)block.Min;
                    Vector3I blockMax;
                    BlockTransformations.ComputeBlockMax(block, out blockMax);
                    for (var rangeItr = new Vector3I_RangeIterator(ref blockMin, ref blockMax); rangeItr.IsValid(); rangeItr.MoveNext())
                    {
                        blockMap[rangeItr.Current] = block;
                    }
                    blockKeep.Add(block);
                }
                this.Info("Found {0} blocks to keep, {1} block mounts to remap", blockKeep.Count, dummyDel.Count);
                foreach (var pair in dummyDel)
                {
                    var block   = pair.Item1;
                    var useName = pair.Item2;

                    IEnumerable <Base6Directions.Direction> dirs = Base6Directions.EnumDirections;
                    var def       = MyDefinitionManager.Static.GetCubeBlockDefinition(pair.Item1);
                    var transform = new MatrixI(block.BlockOrientation);
                    if (def?.MountPoints != null)
                    {
                        var mountDirs = new HashSet <Base6Directions.Direction>();
                        foreach (var mount in def.MountPoints)
                        {
                            mountDirs.Add(Base6Directions.GetDirection(Vector3I.TransformNormal(mount.Normal, ref transform)));
                        }
                    }

                    var args     = useName.Split(' ');
                    var keepArgs = new List <string>(args.Length);
                    foreach (var arg in args)
                    {
                        if (arg.StartsWithICase(PartDummyUtils.ArgumentMountDirection))
                        {
                            Base6Directions.Direction dir;
                            if (Enum.TryParse(arg.Substring(2), out dir))
                            {
                                dirs = new[] { transform.GetDirection(Base6Directions.GetOppositeDirection(dir)) }
                            }
                            ;
                            else
                            {
                                this.Error("Failed to parse direction argument \"{0}\"", arg);
                                feedback?.Invoke("Error: Failed to parse direction argument \"{0}\"", arg);
                            }
                        }
                        else
                        {
                            keepArgs.Add(arg);
                        }
                    }
                    useName = string.Join(" ", keepArgs);

                    MyObjectBuilder_CubeBlock outputBlock = null;
                    var outputDir = Base6Directions.Direction.Forward;
                    foreach (var dir in dirs)
                    {
                        MyObjectBuilder_CubeBlock tmp;
                        if (!blockMap.TryGetValue(block.Min + Base6Directions.GetIntVector(dir), out tmp))
                        {
                            continue;
                        }
                        if (tmp.ConfigNames().Any(x => x.StartsWithICase(MountDelegated)))
                        {
                            continue;
                        }
                        if (outputBlock != null)
                        {
                            this.Error("Multiple directions found for {0}", pair.Item2);
                            feedback?.Invoke("Error: Multiple directions found for {0}", pair.Item2);
                        }
                        outputBlock = tmp;
                        outputDir   = dir;
                    }
                    if (outputBlock == null || !ApplyDelegate(ob, block, useName, outputBlock, outputDir))
                    {
                        this.Error("Failed to find delegated mount point for {0}", pair.Item2);
                        feedback?.Invoke("Error: Failed to find delegated mount point for {0}", pair.Item2);
                    }
                }
                ob.CubeBlocks = blockKeep;

                // Grab related grids!
                var relatedGrids = new HashSet <IMyCubeGrid> {
                    grid
                };
                var scanRelated           = new Queue <IMyCubeGrid>();
                var relatedGridController = new Dictionary <IMyCubeGrid, IMyCubeBlock>();
                scanRelated.Enqueue(grid);
                while (scanRelated.Count > 0)
                {
                    var          subGrid = scanRelated.Dequeue();
                    IMyCubeBlock controllerForThisGrid = null;
                    relatedGridController.TryGetValue(subGrid, out controllerForThisGrid);

                    subGrid.GetBlocks(null, (y) =>
                    {
                        var x = y?.FatBlock;
                        if (x == null)
                        {
                            return(false);
                        }
                        var childGrid = (x as IMyMechanicalConnectionBlock)?.TopGrid;
                        if (childGrid != null && relatedGrids.Add(childGrid))
                        {
                            scanRelated.Enqueue(childGrid);
                            relatedGridController[childGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        var parentGrid = (x as IMyAttachableTopBlock)?.Base?.CubeGrid;
                        // ReSharper disable once InvertIf
                        if (parentGrid != null && relatedGrids.Add(parentGrid))
                        {
                            scanRelated.Enqueue(parentGrid);
                            relatedGridController[parentGrid] = x.CubeGrid == grid ? x : controllerForThisGrid;
                        }
                        return(false);
                    });
                }
                relatedGrids.Remove(grid);
                var removedNoController = relatedGrids.RemoveWhere(x => !relatedGridController.ContainsKey(x));
                if (removedNoController > 0)
                {
                    this.Error("Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                               removedNoController);
                    feedback?.Invoke("Error: Failed to find the mechanical connection block for all subgrids.  {0} will be excluded",
                                     removedNoController);
                }
                // Need to add reserved space for subgrids so they don't overlap.  So compute that.  Yay!
                foreach (var rel in relatedGrids)
                {
                    IMyCubeBlock root;
                    if (!relatedGridController.TryGetValue(rel, out root))
                    {
                        this.Error("Unable to find the mechanical connection for grid {0}", rel.CustomName);
                        feedback?.Invoke("Error: Unable to find the mechanical connection for grid {0}",
                                         rel.CustomName);
                        continue;
                    }
                    MyObjectBuilder_CubeBlock blockDest;
                    if (blockMap.TryGetValue(root.Min, out blockDest))
                    {
                        var blockLocal = (MatrixD) new MatrixI(blockDest.BlockOrientation).GetFloatMatrix();
                        blockLocal.Translation = (Vector3I)blockDest.Min * grid.GridSize;
                        var blockWorld = MatrixD.Multiply(blockLocal, grid.WorldMatrix);

                        var worldAABB = rel.WorldAABB;
                        worldAABB = Utilities.TransformBoundingBox(worldAABB, MatrixD.Invert(blockWorld));
                        var gridAABB = new BoundingBoxI(Vector3I.Floor(worldAABB.Min / grid.GridSize), Vector3I.Ceiling(worldAABB.Max / grid.GridSize));
                        var code     = $"{PartMetadata.ReservedSpacePrefix} NE:{gridAABB.Min.X}:{gridAABB.Min.Y}:{gridAABB.Min.Z} PE:{gridAABB.Max.X}:{gridAABB.Max.Y}:{gridAABB.Max.Z}";
                        this.Info("Added reserved space for subgrid {0}: Spec is \"{1}\"", rel.CustomName, code);
                        if (blockDest.Name == null || blockDest.Name.Trim().Length == 0)
                        {
                            blockDest.Name = code;
                        }
                        else
                        {
                            blockDest.Name += PartMetadata.MultiUseSentinel + code;
                        }
                    }
                    else
                    {
                        this.Error("Unable to find the OB for grid block {0} ({1}, {2}, {3}).  Is it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                        feedback?.Invoke("Unable to the find OB for grid block {0} ({1}, {2}, {3}).  Was it a delegate?", (root as IMyTerminalBlock)?.CustomName ?? root.Name, root.Min.X, root.Min.Y, root.Min.Z);
                    }
                }

                var allGrids = new List <MyObjectBuilder_CubeGrid>(relatedGrids.Count + 1)
                {
                    ob
                };
                allGrids.AddRange(relatedGrids.Select(relGrid => relGrid.GetObjectBuilder(false)).OfType <MyObjectBuilder_CubeGrid>());

                // Compose description: TODO I'd love if this actually worked :/
                // var storage = new MyPartMetadata();
                // storage.InitFromGrids(ob, allGrids);
                // var data = Convert.ToBase64String(MyAPIGateway.Utilities.SerializeToBinary(storage.GetObjectBuilder()));

                var defOut = new MyObjectBuilder_PrefabDefinition()
                {
                    Id        = new SerializableDefinitionId(typeof(MyObjectBuilder_PrefabDefinition), grid.CustomName),
                    CubeGrids = allGrids.ToArray()
                };

                var fileName = grid.CustomName + ".sbc";
                this.Info("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);
                feedback?.Invoke("Saving {1} grids as {0}", fileName, defOut.CubeGrids.Length);

                var mishMash = new MyObjectBuilder_Definitions()
                {
                    Prefabs = new MyObjectBuilder_PrefabDefinition[] { defOut }
                };
                var writer = MyAPIGateway.Utilities.WriteBinaryFileInLocalStorage(fileName, typeof(DesignTools));
                var obCode = MyAPIGateway.Utilities.SerializeToXML(mishMash);
                obCode = obCode.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\"");
                writer.Write(Encoding.UTF8.GetBytes(obCode));
                writer.Close();
            }
            catch (Exception e)
            {
                this.Error("Failed to parse.  Error:\n{0}", e.ToString());
            }
        }