Exemplo n.º 1
0
        public MyObjectBuilder_CubeGrid BuildTestEntity()
        {
            var entity = new MyObjectBuilder_CubeGrid
            {
                EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ENTITY),
                PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                Skeleton        = new System.Collections.Generic.List <BoneInfo>(),
                LinearVelocity  = new VRageMath.Vector3(0, 0, 0),
                AngularVelocity = new VRageMath.Vector3(0, 0, 0),
                GridSizeEnum    = MyCubeSize.Large
            };

            var blockPrefix       = entity.GridSizeEnum.ToString();
            var cornerBlockPrefix = entity.GridSizeEnum.ToString();

            entity.IsStatic    = false;
            blockPrefix       += "BlockArmor"; // HeavyBlockArmor|BlockArmor;
            cornerBlockPrefix += "BlockArmor"; // HeavyBlockArmor|BlockArmor|RoundArmor_;

            // Figure out where the Character is facing, and plant the new constrcut right in front, by "10" units, facing the Character.
            var vector = new BindableVector3DModel(_dataModel.CharacterPosition.Forward).Vector3D;

            vector.Normalize();
            vector   = Vector3D.Multiply(vector, 6);
            Position = new BindablePoint3DModel(Point3D.Add(new BindablePoint3DModel(_dataModel.CharacterPosition.Position).Point3D, vector));
            Forward  = new BindableVector3DModel(_dataModel.CharacterPosition.Forward);
            Up       = new BindableVector3DModel(_dataModel.CharacterPosition.Up);

            entity.PositionAndOrientation = new MyPositionAndOrientation
            {
                Position = Position.ToVector3D(),
                Forward  = Forward.ToVector3(),
                Up       = Up.ToVector3()
            };

            // Large|BlockArmor|Corner
            // Large|RoundArmor_|Corner
            // Large|HeavyBlockArmor|Block,
            // Small|BlockArmor|Slope,
            // Small|HeavyBlockArmor|Corner,

            var blockType              = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "Block");
            var slopeBlockType         = (SubtypeId)Enum.Parse(typeof(SubtypeId), cornerBlockPrefix + "Slope");
            var cornerBlockType        = (SubtypeId)Enum.Parse(typeof(SubtypeId), cornerBlockPrefix + "Corner");
            var inverseCornerBlockType = (SubtypeId)Enum.Parse(typeof(SubtypeId), cornerBlockPrefix + "CornerInv");

            entity.CubeBlocks = new System.Collections.Generic.List <MyObjectBuilder_CubeBlock>();

            //var smoothObject = true;

            // Read in voxel and set main cube space.
            //var ccubic = TestCreateSplayedDiagonalPlane();
            //var ccubic = TestCreateSlopedDiagonalPlane();
            //var ccubic = TestCreateStaggeredStar();
            var ccubic = Modelling.TestCreateTrayShape();
            //var ccubic = ReadModelVolmetic(@"..\..\..\..\..\..\building 3D\models\Rhino_corrected.obj", 10, null, ModelTraceVoxel.ThickSmoothedDown);

            var fillObject = false;

            //if (smoothObject)
            //{
            //    CalculateAddedInverseCorners(ccubic);
            //    CalculateAddedSlopes(ccubic);
            //    CalculateAddedCorners(ccubic);
            //}

            Modelling.BuildStructureFromCubic(entity, ccubic, fillObject, blockType, slopeBlockType, cornerBlockType, inverseCornerBlockType);

            return(entity);
        }
Exemplo n.º 2
0
        private MyObjectBuilder_CubeGrid BuildShipEntity()
        {
            var entity = new MyObjectBuilder_CubeGrid
            {
                EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ENTITY),
                PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                Skeleton        = new System.Collections.Generic.List <BoneInfo>(),
                LinearVelocity  = new VRageMath.Vector3(0, 0, 0),
                AngularVelocity = new VRageMath.Vector3(0, 0, 0)
            };

            var blockPrefix = "";

            switch (ClassType)
            {
            case ImportModelClassType.SmallShip:
                entity.GridSizeEnum = MyCubeSize.Small;
                blockPrefix        += "Small";
                entity.IsStatic     = false;
                break;

            case ImportModelClassType.LargeShip:
                entity.GridSizeEnum = MyCubeSize.Large;
                blockPrefix        += "Large";
                entity.IsStatic     = false;
                break;

            case ImportModelClassType.Station:
                entity.GridSizeEnum = MyCubeSize.Large;
                blockPrefix        += "Large";
                entity.IsStatic     = true;
                Position            = Position.RoundOff(MyCubeSize.Large.ToLength());
                Forward             = Forward.RoundToAxis();
                Up = Up.RoundToAxis();
                break;
            }

            switch (ArmorType)
            {
            case ImportArmorType.Heavy: blockPrefix += "HeavyBlockArmor"; break;

            case ImportArmorType.Light: blockPrefix += "BlockArmor"; break;

                // TODO: Rounded Armor.
                // Currently in development, and only specified as 'Light' on the 'Large' structures.
                //case ImportArmorType.Round: blockPrefix += "RoundArmor_"; break;
            }

            // Large|BlockArmor|Corner
            // Large|RoundArmor_|Corner
            // Large|HeavyBlockArmor|Block,
            // Small|BlockArmor|Slope,
            // Small|HeavyBlockArmor|Corner,

            var blockType              = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "Block");
            var slopeBlockType         = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "Slope");
            var cornerBlockType        = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "Corner");
            var inverseCornerBlockType = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "CornerInv");

            entity.CubeBlocks = new System.Collections.Generic.List <MyObjectBuilder_CubeBlock>();

            double multiplier;

            if (IsMultipleScale)
            {
                multiplier = MultipleScale;
            }
            else
            {
                multiplier = MaxLengthScale / Math.Max(Math.Max(OriginalModelSize.Height, OriginalModelSize.Width), OriginalModelSize.Depth);
            }

            var ccubic = Modelling.ReadModelVolmetic(Filename, multiplier, null, TraceType, MainViewModel.ResetProgress, MainViewModel.IncrementProgress);

            Modelling.BuildStructureFromCubic(entity, ccubic, FillObject, blockType, slopeBlockType, cornerBlockType, inverseCornerBlockType);

            MainViewModel.ClearProgress();

            entity.PositionAndOrientation = new MyPositionAndOrientation
            {
                // TODO: reposition based scale.
                Position = Position.ToVector3D(),
                Forward  = Forward.ToVector3(),
                Up       = Up.ToVector3()
            };

            IsValidModel = entity.CubeBlocks.Count > 0;

            return(entity);
        }
Exemplo n.º 3
0
        public void RotateComponent()
        {
            var d1 = SpaceEngineersApi.GetCubeDefinition(new MyObjectBuilderType(typeof(MyObjectBuilder_Thrust)), MyCubeSize.Large, "LargeBlockLargeThrust");

            Assert.AreEqual("DisplayName_Block_LargeThrust", d1.DisplayName, "Must match");
            Assert.AreEqual(MyCubeSize.Large, d1.CubeSize, "Must match");

            Assert.AreEqual(3, d1.Size.X, "Must match");
            Assert.AreEqual(2, d1.Size.Y, "Must match");
            Assert.AreEqual(4, d1.Size.Z, "Must match");

            //======//

            var orient = new SerializableBlockOrientation(Base6Directions.Direction.Forward, Base6Directions.Direction.Up);

            var f = Base6Directions.GetVector(orient.Forward);
            var u = Base6Directions.GetVector(orient.Up);

            var m = Matrix.CreateFromDir(f, u);
            var q = Quaternion.CreateFromRotationMatrix(m);

            var nf = Base6Directions.GetForward(q);
            var nu = Base6Directions.GetUp(q);

            // Test that Space Engineers orientation methods are working as expected. Forward is still Forward, Up is still Up.
            Assert.AreEqual(nf, orient.Forward, "Initial Orientation Forward must match.");
            Assert.AreEqual(nu, orient.Up, "Initial Orientation Forward must match.");

            //======//

            var v   = d1.Size.ToVector3();
            var fV1 = Vector3.Transform(v, m);

            // Orientation of Forward/Up should provide the exact same dimentions as the original Component above.
            Assert.AreEqual(3, fV1.X, "Must match");
            Assert.AreEqual(2, fV1.Y, "Must match");
            Assert.AreEqual(4, fV1.Z, "Must match");

            //======//

            var newOrient = new SerializableBlockOrientation(Base6Directions.Direction.Down, Base6Directions.Direction.Right);

            var newM = Matrix.CreateFromDir(Base6Directions.GetVector(newOrient.Forward), Base6Directions.GetVector(newOrient.Up));

            var fV2 = Vector3.Transform(v, newM);

            // The reoriented Component size should now have changed.
            Assert.AreEqual(2, fV2.X, "Must match");
            Assert.AreEqual(4, fV2.Y, "Must match");
            Assert.AreEqual(3, fV2.Z, "Must match");

            //======//

            // Reducing complexity of code with Extension.
            var direction = new SerializableBlockOrientation(Base6Directions.Direction.Down, Base6Directions.Direction.Right);
            var fV3       = d1.Size.Transform(direction);

            // The reoriented Component size should now have changed.
            Assert.AreEqual(2, fV3.X, "Must match");
            Assert.AreEqual(4, fV3.Y, "Must match");
            Assert.AreEqual(3, fV3.Z, "Must match");
        }
        public void Load()
        {
            CubeAssets      = new ObservableCollection <ComponentItemModel>();
            ComponentAssets = new ObservableCollection <ComponentItemModel>();
            ItemAssets      = new ObservableCollection <ComponentItemModel>();
            MaterialAssets  = new ObservableCollection <ComponentItemModel>();

            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            foreach (var cubeDefinition in SpaceEngineersCore.Resources.CubeBlockDefinitions)
            {
                var props  = new Dictionary <string, string>();
                var fields = cubeDefinition.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);

                foreach (var field in fields)
                {
                    props.Add(field.Name, GetValue(field, cubeDefinition));
                }

                CubeAssets.Add(new ComponentItemModel
                {
                    Name             = cubeDefinition.DisplayNameText,
                    TypeId           = cubeDefinition.Id.TypeId,
                    TypeIdString     = cubeDefinition.Id.TypeId.ToString(),
                    SubtypeId        = cubeDefinition.Id.SubtypeName,
                    TextureFile      = (cubeDefinition.Icons == null || cubeDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(cubeDefinition.Icons.First(), Path.Combine(contentPath, cubeDefinition.Icons.First())),
                    Time             = TimeSpan.FromSeconds(cubeDefinition.MaxIntegrity / cubeDefinition.IntegrityPointsPerSec),
                    Accessible       = cubeDefinition.Public,
                    Mass             = SpaceEngineersApi.FetchCubeBlockMass(cubeDefinition.Id.TypeId, cubeDefinition.CubeSize, cubeDefinition.Id.SubtypeName),
                    CubeSize         = cubeDefinition.CubeSize,
                    Size             = new BindableSize3DIModel(cubeDefinition.Size),
                    CustomProperties = props,
                    IsMod            = !cubeDefinition.Context.IsBaseGame,
                });
            }

            foreach (var componentDefinition in SpaceEngineersCore.Resources.ComponentDefinitions)
            {
                var   bp     = SpaceEngineersApi.GetBlueprint(componentDefinition.Id.TypeId, componentDefinition.Id.SubtypeName);
                float amount = 0;
                if (bp != null && bp.Results.Length > 0)
                {
                    amount = (float)bp.Results[0].Amount;
                }

                ComponentAssets.Add(new ComponentItemModel
                {
                    Name         = componentDefinition.DisplayNameText,
                    TypeId       = componentDefinition.Id.TypeId,
                    TypeIdString = componentDefinition.Id.TypeId.ToString(),
                    SubtypeId    = componentDefinition.Id.SubtypeName,
                    Mass         = componentDefinition.Mass,
                    TextureFile  = (componentDefinition.Icons == null || componentDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(componentDefinition.Icons.First(), Path.Combine(contentPath, componentDefinition.Icons.First())),
                    Volume       = componentDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    Accessible   = componentDefinition.Public,
                    Time         = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds / amount) : (TimeSpan?)null,
                    IsMod        = !componentDefinition.Context.IsBaseGame,
                });
            }

            foreach (var physicalItemDefinition in SpaceEngineersCore.Resources.PhysicalItemDefinitions)
            {
                var   bp     = SpaceEngineersApi.GetBlueprint(physicalItemDefinition.Id.TypeId, physicalItemDefinition.Id.SubtypeName);
                float amount = 0;
                if (bp != null)
                {
                    if (bp.Results != null && bp.Results.Length > 0)
                    {
                        amount = (float)bp.Results[0].Amount;
                    }
                }

                float timeMassMultiplyer = 1f;
                if (physicalItemDefinition.Id.TypeId == typeof(MyObjectBuilder_Ore) ||
                    physicalItemDefinition.Id.TypeId == typeof(MyObjectBuilder_Ingot))
                {
                    timeMassMultiplyer = physicalItemDefinition.Mass;
                }

                ItemAssets.Add(new ComponentItemModel
                {
                    Name         = physicalItemDefinition.DisplayNameText,
                    TypeId       = physicalItemDefinition.Id.TypeId,
                    TypeIdString = physicalItemDefinition.Id.TypeId.ToString(),
                    SubtypeId    = physicalItemDefinition.Id.SubtypeName,
                    Mass         = physicalItemDefinition.Mass,
                    Volume       = physicalItemDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    TextureFile  = physicalItemDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(physicalItemDefinition.Icons.First(), Path.Combine(contentPath, physicalItemDefinition.Icons.First())),
                    Accessible   = physicalItemDefinition.Public,
                    Time         = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds / amount / timeMassMultiplyer) : (TimeSpan?)null,
                    IsMod        = !physicalItemDefinition.Context.IsBaseGame,
                });
            }

            foreach (MyVoxelMaterialDefinition voxelMaterialDefinition in SpaceEngineersCore.Resources.VoxelMaterialDefinitions)
            {
                string texture = voxelMaterialDefinition.GetVoxelDisplayTexture();

                MaterialAssets.Add(new ComponentItemModel
                {
                    Name         = voxelMaterialDefinition.Id.SubtypeName,
                    TextureFile  = texture == null ? null : SpaceEngineersCore.GetDataPathOrDefault(texture, Path.Combine(contentPath, texture)),
                    IsRare       = voxelMaterialDefinition.IsRare,
                    OreName      = voxelMaterialDefinition.MinedOre,
                    MineOreRatio = voxelMaterialDefinition.MinedOreRatio,
                    IsMod        = !voxelMaterialDefinition.Context.IsBaseGame,
                });
            }
        }
Exemplo n.º 5
0
 internal void OnSerializingMethod(StreamingContext context)
 {
     SerializedEntity = SpaceEngineersApi.Serialize <MyObjectBuilder_EntityBase>(EntityBase);
 }
Exemplo n.º 6
0
 internal void OnDeserializedMethod(StreamingContext context)
 {
     EntityBase = SpaceEngineersApi.Deserialize <MyObjectBuilder_EntityBase>(SerializedEntity);
 }
        private bool BuildEntity()
        {
            var filenamepart = Path.GetFileNameWithoutExtension(Filename);
            var filename     = MainViewModel.CreateUniqueVoxelStorageName(filenamepart + MyVoxelMap.V2FileExtension);

            double multiplier;

            if (IsMultipleScale)
            {
                multiplier = MultipleScale;
            }
            else
            {
                multiplier = MaxLengthScale / Math.Max(Math.Max(OriginalModelSize.Height, OriginalModelSize.Width), OriginalModelSize.Depth);
            }

            var scale           = new ScaleTransform3D(multiplier, multiplier, multiplier);
            var rotateTransform = MeshHelper.TransformVector(new System.Windows.Media.Media3D.Vector3D(0, 0, 0), -RotateRoll, RotateYaw - 90, RotatePitch + 90);

            SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);

            var model = MeshHelper.Load(Filename, ignoreErrors: true);

            var meshes      = new List <MyVoxelRayTracer.MyMeshModel>();
            var geometeries = new List <MeshGeometry3D>();

            foreach (var model3D in model.Children)
            {
                var gm       = (GeometryModel3D)model3D;
                var geometry = gm.Geometry as MeshGeometry3D;

                if (geometry != null)
                {
                    geometeries.Add(geometry);
                }
            }
            meshes.Add(new MyVoxelRayTracer.MyMeshModel(geometeries.ToArray(), InsideStockMaterial.Value, InsideStockMaterial.Value));

            #region handle dialogs and process the conversion

            var doCancel = false;

            var progressModel = new ProgressCancelModel {
                Title = "Processing...", SubTitle = "Processing...", DialogText = "Time remaining: Calculating..."
            };
            var progressVm = new ProgressCancelViewModel(this, progressModel);
            progressVm.CloseRequested += delegate(object sender, EventArgs e)
            {
                doCancel = true;
            };

            var cancelFunc = (Func <bool>) delegate
            {
                return(doCancel);
            };

            var completedAction = (Action) delegate
            {
                progressVm.Close();
            };

            MyVoxelMap voxelMap = null;

            var action = (Action) delegate
            {
                voxelMap = MyVoxelRayTracer.ReadModelAsteroidVolmetic(model, meshes, scale, rotateTransform, TraceType, TraceCount, TraceDirection,
                                                                      progressModel.ResetProgress, progressModel.IncrementProgress, cancelFunc, completedAction);
            };

            if (RunInLowPrioity)
            {
                System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Idle;
            }

            _dialogService.ShowDialog <WindowProgressCancel>(this, progressVm, action);

            if (RunInLowPrioity)
            {
                System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Normal;
            }

            #endregion

            if (doCancel || voxelMap == null)
            {
                IsValidEntity = false;
                NewEntity     = null;
            }
            else
            {
                voxelMap.ForceShellMaterial(OutsideStockMaterial.Value, (byte)OutsideMaterialDepth);
                voxelMap.Save(SourceFile);

                var position = VRageMath.Vector3D.Zero;
                var forward  = Vector3.Forward;
                var up       = Vector3.Up;

                if (IsAbsolutePosition)
                {
                    position = Position.ToVector3();
                }
                else if (IsInfrontofPlayer)
                {
                    // Figure out where the Character is facing, and plant the new construct centered in front of the Character, but "BuildDistance" units out in front.
                    var lookVector = (VRageMath.Vector3D)_dataModel.CharacterPosition.Forward.ToVector3();
                    lookVector.Normalize();
                    VRageMath.Vector3D?boundingIntersectPoint = voxelMap.BoundingContent.IntersectsRayAt(voxelMap.BoundingContent.Center, -lookVector * 5000d);

                    if (!boundingIntersectPoint.HasValue)
                    {
                        boundingIntersectPoint = voxelMap.BoundingContent.Center;
                    }

                    var distance = VRageMath.Vector3D.Distance(boundingIntersectPoint.Value, voxelMap.BoundingContent.Center) + (float)BuildDistance;
                    VRageMath.Vector3D vector = lookVector * distance;
                    position = VRageMath.Vector3D.Add(_dataModel.CharacterPosition.Position, vector) - voxelMap.BoundingContent.Center;
                }

                var entity = new MyObjectBuilder_VoxelMap(position, filename)
                {
                    EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ASTEROID),
                    PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                    StorageName     = Path.GetFileNameWithoutExtension(filename)
                };

                entity.PositionAndOrientation = new MyPositionAndOrientation
                {
                    Position = position,
                    Forward  = forward,
                    Up       = up
                };

                IsValidEntity = voxelMap.BoundingContent.Size.Volume > 0f;

                NewEntity = entity;

                if (BeepWhenFinished)
                {
                    System.Media.SystemSounds.Asterisk.Play();
                }
            }

            return(!doCancel);
        }
Exemplo n.º 8
0
 private void OnSerializingMethod(StreamingContext context)
 {
     SerializedEntity = SpaceEngineersApi.Serialize <MyObjectBuilder_Meteor>(Meteor);
 }
Exemplo n.º 9
0
        public MyObjectBuilder_CubeGrid BuildEntity()
        {
            var entity = new MyObjectBuilder_CubeGrid
            {
                EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ENTITY),
                PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                Skeleton        = new System.Collections.Generic.List <BoneInfo>(),
                LinearVelocity  = new VRageMath.Vector3(0, 0, 0),
                AngularVelocity = new VRageMath.Vector3(0, 0, 0)
            };

            var blockPrefix = "";

            switch (ClassType)
            {
            case ImportImageClassType.SmallShip:
                entity.GridSizeEnum = MyCubeSize.Small;
                blockPrefix        += "Small";
                entity.IsStatic     = false;
                break;

            case ImportImageClassType.LargeShip:
                entity.GridSizeEnum = MyCubeSize.Large;
                blockPrefix        += "Large";
                entity.IsStatic     = false;
                break;

            case ImportImageClassType.Station:
                entity.GridSizeEnum = MyCubeSize.Large;
                blockPrefix        += "Large";
                entity.IsStatic     = true;
                Position            = Position.RoundOff(MyCubeSize.Large.ToLength());
                Forward             = Forward.RoundToAxis();
                Up = Up.RoundToAxis();
                break;
            }

            switch (ArmorType)
            {
            case ImportArmorType.Heavy: blockPrefix += "HeavyBlockArmor"; break;

            case ImportArmorType.Light: blockPrefix += "BlockArmor"; break;
            }

            entity.PositionAndOrientation = new MyPositionAndOrientation
            {
                // TODO: reposition based scale.
                Position = Position.ToVector3D(),
                Forward  = Forward.ToVector3(),
                Up       = Up.ToVector3()
            };

            // Large|BlockArmor|Corner
            // Large|RoundArmor_|Corner
            // Large|HeavyBlockArmor|Block,
            // Small|BlockArmor|Slope,
            // Small|HeavyBlockArmor|Corner,

            entity.CubeBlocks = new System.Collections.Generic.List <MyObjectBuilder_CubeBlock>();
            var image = ImageHelper.ResizeImage(_sourceImage, NewImageSize.Size);

            using (var palatteImage = new Bitmap(image))
            {
                // Optimal order load. from grid coordinate (0,0,0) and up.
                for (var x = palatteImage.Width - 1; x >= 0; x--)
                {
                    for (var y = palatteImage.Height - 1; y >= 0; y--)
                    {
                        const int z     = 0;
                        var       color = palatteImage.GetPixel(x, y);

                        // Specifically ignore anything with less than half "Transparent" Alpha.
                        if (IsAlphaLevel && color.A < AlphaLevel)
                        {
                            continue;
                        }

                        if (IsKeyColor && color.R == KeyColor.R && color.G == KeyColor.G && color.B == KeyColor.B)
                        {
                            continue;
                        }

                        // Parse the string through the Enumeration to check that the 'subtypeid' is still valid in the game engine.
                        var armor = (SubtypeId)Enum.Parse(typeof(SubtypeId), blockPrefix + "Block");

                        MyObjectBuilder_CubeBlock newCube;
                        entity.CubeBlocks.Add(newCube = new MyObjectBuilder_CubeBlock());
                        newCube.SubtypeName           = armor.ToString();
                        newCube.EntityId         = 0;
                        newCube.BlockOrientation = Modelling.GetCubeOrientation(CubeType.Cube);
                        newCube.Min          = new VRageMath.Vector3I(palatteImage.Width - x - 1, palatteImage.Height - y - 1, z);
                        newCube.ColorMaskHSV = color.ToSandboxHsvColor();
                    }
                }
            }

            return(entity);
        }
Exemplo n.º 10
0
        public void Load(MyPositionAndOrientation characterPosition, float maxFloatingObjects)
        {
            MaxFloatingObjects = maxFloatingObjects;
            CharacterPosition  = characterPosition;
            StockItemList.Clear();
            var list        = new List <ComponentItemModel>();
            var contentPath = ToolboxUpdater.GetApplicationContentPath();

            foreach (var componentDefinition in SpaceEngineersCore.Resources.ComponentDefinitions)
            {
                var bp = SpaceEngineersApi.GetBlueprint(componentDefinition.Id.TypeId, componentDefinition.Id.SubtypeName);
                list.Add(new ComponentItemModel
                {
                    Name        = componentDefinition.DisplayNameText,
                    TypeId      = componentDefinition.Id.TypeId,
                    SubtypeId   = componentDefinition.Id.SubtypeName,
                    Mass        = componentDefinition.Mass,
                    TextureFile = componentDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(componentDefinition.Icons.First(), Path.Combine(contentPath, componentDefinition.Icons.First())),
                    Volume      = componentDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    Accessible  = componentDefinition.Public,
                    Time        = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds) : (TimeSpan?)null,
                });
            }

            foreach (var physicalItemDefinition in SpaceEngineersCore.Resources.PhysicalItemDefinitions)
            {
                if (physicalItemDefinition.Id.SubtypeName == "CubePlacerItem" || physicalItemDefinition.Id.SubtypeName == "WallPlacerItem")
                {
                    continue;
                }

                var bp = SpaceEngineersApi.GetBlueprint(physicalItemDefinition.Id.TypeId, physicalItemDefinition.Id.SubtypeName);
                list.Add(new ComponentItemModel
                {
                    Name        = physicalItemDefinition.DisplayNameText,
                    TypeId      = physicalItemDefinition.Id.TypeId,
                    SubtypeId   = physicalItemDefinition.Id.SubtypeName,
                    Mass        = physicalItemDefinition.Mass,
                    Volume      = physicalItemDefinition.Volume * SpaceEngineersConsts.VolumeMultiplyer,
                    TextureFile = physicalItemDefinition.Icons == null ? null : SpaceEngineersCore.GetDataPathOrDefault(physicalItemDefinition.Icons.First(), Path.Combine(contentPath, physicalItemDefinition.Icons.First())),
                    Accessible  = physicalItemDefinition.Public,
                    Time        = bp != null ? TimeSpan.FromSeconds(bp.BaseProductionTimeInSeconds) : (TimeSpan?)null,
                });
            }

            foreach (var item in list.OrderBy(i => i.FriendlyName))
            {
                StockItemList.Add(item);
            }

            //list.Clear();

            //foreach (var cubeDefinition in SpaceEngineersAPI.CubeBlockDefinitions)
            //{
            //    list.Add(new ComponentItemModel
            //    {
            //        Name = cubeDefinition.DisplayName,
            //        TypeId = cubeDefinition.Id.TypeId,
            //        SubtypeId = cubeDefinition.Id.SubtypeName,
            //        CubeSize = cubeDefinition.CubeSize,
            //        TextureFile = cubeDefinition.Icon == null ? null : Path.Combine(contentPath, cubeDefinition.Icon),
            //        Accessible = !string.IsNullOrEmpty(cubeDefinition.Model),
            //    });
            //}

            //foreach (var item in list.OrderBy(i => i.FriendlyName))
            //{
            //    StockItemList.Add(item);
            //}
        }
Exemplo n.º 11
0
 private void OnDeserializedMethod(StreamingContext context)
 {
     EntityBase = SpaceEngineersApi.Deserialize <MyObjectBuilder_Character>(SerializedEntity);
 }
Exemplo n.º 12
0
        public bool ExtractStationIntersect(IMainView mainViewModel, bool tightIntersection)
        {
            // Make a shortlist of station Entities in the bounding box of the asteroid.
            var asteroidWorldAABB = new BoundingBoxD((Vector3D)ContentBounds.Min + PositionAndOrientation.Value.Position, (Vector3D)ContentBounds.Max + PositionAndOrientation.Value.Position);
            var stations          = mainViewModel.GetIntersectingEntities(asteroidWorldAABB).Where(e => e.ClassType == ClassType.LargeStation).Cast <StructureCubeGridModel>().ToList();

            if (stations.Count == 0)
            {
                return(false);
            }

            var modified   = false;
            var sourceFile = SourceVoxelFilepath ?? VoxelFilepath;
            var asteroid   = new MyVoxelMap();

            asteroid.Load(sourceFile);

            var total = stations.Sum(s => s.CubeGrid.CubeBlocks.Count);

            mainViewModel.ResetProgress(0, total);

            // Search through station entities cubes for intersection with this voxel.
            foreach (var station in stations)
            {
                var quaternion = station.PositionAndOrientation.Value.ToQuaternion();

                foreach (var cube in station.CubeGrid.CubeBlocks)
                {
                    mainViewModel.IncrementProgress();

                    var definition = SpaceEngineersApi.GetCubeDefinition(cube.TypeId, station.CubeGrid.GridSizeEnum, cube.SubtypeName);

                    var orientSize    = definition.Size.Transform(cube.BlockOrientation).Abs();
                    var min           = cube.Min.ToVector3() * station.CubeGrid.GridSizeEnum.ToLength();
                    var max           = (cube.Min + orientSize) * station.CubeGrid.GridSizeEnum.ToLength();
                    var p1            = Vector3D.Transform(min, quaternion) + station.PositionAndOrientation.Value.Position - (station.CubeGrid.GridSizeEnum.ToLength() / 2);
                    var p2            = Vector3D.Transform(max, quaternion) + station.PositionAndOrientation.Value.Position - (station.CubeGrid.GridSizeEnum.ToLength() / 2);
                    var cubeWorldAABB = new BoundingBoxD(Vector3.Min(p1, p2), Vector3.Max(p1, p2));

                    // find worldAABB of block.
                    if (asteroidWorldAABB.Intersects(cubeWorldAABB))
                    {
                        Vector3I block;
                        var      cacheSize = new Vector3I(64);
                        Vector3D position  = PositionAndOrientation.Value.Position;

                        // read the asteroid in chunks of 64 to avoid the Arithmetic overflow issue.
                        for (block.Z = 0; block.Z < asteroid.Storage.Size.Z; block.Z += 64)
                        {
                            for (block.Y = 0; block.Y < asteroid.Storage.Size.Y; block.Y += 64)
                            {
                                for (block.X = 0; block.X < asteroid.Storage.Size.X; block.X += 64)
                                {
                                    var cache = new MyStorageData();
                                    cache.Resize(cacheSize);
                                    // LOD1 is not detailed enough for content information on asteroids.
                                    Vector3I maxRange = block + cacheSize - 1;
                                    asteroid.Storage.ReadRange(cache, MyStorageDataTypeFlags.Content, 0, block, maxRange);

                                    bool     changed = false;
                                    Vector3I p;
                                    for (p.Z = 0; p.Z < cacheSize.Z; ++p.Z)
                                    {
                                        for (p.Y = 0; p.Y < cacheSize.Y; ++p.Y)
                                        {
                                            for (p.X = 0; p.X < cacheSize.X; ++p.X)
                                            {
                                                BoundingBoxD    voxelCellBox = new BoundingBoxD(position + p + block, position + p + block + 1);
                                                ContainmentType contains     = cubeWorldAABB.Contains(voxelCellBox);

                                                // TODO: finish tightIntersection. Will require high interpretation of voxel content volumes.

                                                if (contains == ContainmentType.Contains || contains == ContainmentType.Intersects)
                                                {
                                                    cache.Content(ref p, 0);
                                                    changed = true;
                                                }
                                            }
                                        }
                                    }

                                    if (changed)
                                    {
                                        asteroid.Storage.WriteRange(cache, MyStorageDataTypeFlags.Content, block, maxRange);
                                        modified = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            mainViewModel.ClearProgress();

            if (modified)
            {
                var tempfilename = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                asteroid.Save(tempfilename);
                // replaces the existing asteroid file, as it is still the same size and dimentions.
                UpdateNewSource(asteroid, tempfilename);
                MaterialAssets = null;
                InitializeAsync();
            }
            return(modified);
        }
Exemplo n.º 13
0
 private void OnSerializingMethod(StreamingContext context)
 {
     SerializedEntity = SpaceEngineersApi.Serialize <MyObjectBuilder_VoxelMap>(VoxelMap);
 }
Exemplo n.º 14
0
        public List <string> LoadEntities(string[] filenames)
        {
            IsBusy = true;
            var idReplacementTable = new Dictionary <long, long>();
            var badfiles           = new List <string>();

            foreach (var filename in filenames)
            {
                bool isCompressed;
                MyObjectBuilder_CubeGrid       cubeEntity;
                MyObjectBuilder_FloatingObject floatingEntity;
                MyObjectBuilder_Meteor         meteorEntity;
                MyObjectBuilder_Character      characterEntity;
                MyObjectBuilder_Definitions    prefabDefinitions;

                if (SpaceEngineersApi.TryReadSpaceEngineersFile(filename, out cubeEntity, out isCompressed))
                {
                    MergeData(cubeEntity, ref idReplacementTable);
                }
                else if (SpaceEngineersApi.TryReadSpaceEngineersFile(filename, out prefabDefinitions, out isCompressed))
                {
                    if (prefabDefinitions.Prefabs != null)
                    {
                        foreach (var prefab in prefabDefinitions.Prefabs)
                        {
                            if (prefab.CubeGrid != null)
                            {
                                MergeData(prefab.CubeGrid, ref idReplacementTable);
                            }
                            if (prefab.CubeGrids != null)
                            {
                                foreach (var cubeGrid in prefab.CubeGrids)
                                {
                                    MergeData(cubeGrid, ref idReplacementTable);
                                }
                            }
                        }
                    }
                }
                else if (SpaceEngineersApi.TryReadSpaceEngineersFile(filename, out floatingEntity, out isCompressed))
                {
                    var newEntity = AddEntity(floatingEntity);
                    newEntity.EntityId = MergeId(floatingEntity.EntityId, ref idReplacementTable);
                }
                else if (SpaceEngineersApi.TryReadSpaceEngineersFile(filename, out meteorEntity, out isCompressed))
                {
                    var newEntity = AddEntity(meteorEntity);
                    newEntity.EntityId = MergeId(meteorEntity.EntityId, ref idReplacementTable);
                }
                else if (SpaceEngineersApi.TryReadSpaceEngineersFile(filename, out characterEntity, out isCompressed))
                {
                    var newEntity = AddEntity(characterEntity);
                    newEntity.EntityId = MergeId(characterEntity.EntityId, ref idReplacementTable);
                }
                else
                {
                    badfiles.Add(filename);
                }
            }

            IsBusy = false;
            return(badfiles);
        }
Exemplo n.º 15
0
 private void OnSerializingMethod(StreamingContext context)
 {
     SerializedEntity = SpaceEngineersApi.Serialize <MyObjectBuilder_InventoryBagEntity>(EntityBase);
 }