public static ulong GetBattlePoints(MyObjectBuilder_CubeGrid[] grids) { ulong pts = 0; foreach (var grid in grids) pts += GetBattlePoints(grid); return pts; }
public void ProcessCubeGrid(MyObjectBuilder_CubeGrid gridBuilder) { gridBuilder.IsStatic = false; // To prevent exploits gridBuilder.DestructibleBlocks = false; foreach (var block in gridBuilder.CubeBlocks) { var functionalBlock = block as MyObjectBuilder_FunctionalBlock; if (functionalBlock != null) { functionalBlock.Enabled = false; } } }
public CubeGridEntity( MyObjectBuilder_CubeGrid definition ) : base(definition) { _cubeBlockManager = new CubeBlockManager( this ); List<CubeBlockEntity> cubeBlockList = new List<CubeBlockEntity>( ); foreach ( MyObjectBuilder_CubeBlock cubeBlock in definition.CubeBlocks ) { cubeBlock.EntityId = 0; cubeBlockList.Add( new CubeBlockEntity( this, cubeBlock ) ); } _cubeBlockManager.Load( cubeBlockList ); _lastNameRefresh = DateTime.Now; _name = "Cube Grid"; }
public static ulong GetBattlePoints(MyObjectBuilder_CubeGrid grid) { ulong pts = 0; foreach (var block in grid.CubeBlocks) { MyObjectBuilder_CompoundCubeBlock compoundBlock = block as MyObjectBuilder_CompoundCubeBlock; if (compoundBlock != null) { foreach (var blockInCompound in compoundBlock.Blocks) pts += GetBattlePoints(blockInCompound); } else { pts += GetBattlePoints(block); } } return pts; }
public virtual void Init(MyObjectBuilder_CubeGrid builder) { var thrustComp = CubeGrid.Components.Get<MyEntityThrustComponent>(); if(thrustComp != null) thrustComp.DampenersEnabled = builder.DampenersEnabled; if (WheelSystem != null) m_cubeGrid.SetHandbrakeRequest(builder.Handbrake); if (MySession.Static.Settings.EnableOxygen) { GasSystem.Init(builder.OxygenAmount); } if (MyPerGameSettings.EnableJumpDrive) { JumpSystem.Init(builder.JumpDriveDirection, builder.JumpRemainingTime); } var thrustComponent = CubeGrid.Components.Get<MyEntityThrustComponent>(); if (thrustComponent != null) thrustComponent.MergeAllGroupsDirty(); }
public override void UpdateOnceBeforeFrame() { base.UpdateOnceBeforeFrame(); //Only create projections from real projectors if (CubeGrid.Physics != null && m_savedProjection != null) { var clone = (MyObjectBuilder_CubeGrid)m_savedProjection.Clone(); MyEntities.RemapObjectBuilder(clone); m_clipboard.ProcessCubeGrid(clone); m_clipboard.SetGridFromBuilder(clone, Vector3.Zero, 0f); m_originalGridBuilder = m_savedProjection; m_savedProjection = null; InitializeClipboard(); //This will just issue the request //It will only remove it only if conditions are not met a few frames later RequestRemoveProjection(); } UpdateEmissivity(); }
void OnBlueprintScreen_Closed(MyGuiScreenBase source) { ResourceSink.Update(); UpdateIsWorking(); if (m_clipboard.CopiedGrids.Count == 0 || !IsWorking) { RemoveProjection(false); return; } if (m_clipboard.GridSize != CubeGrid.GridSize) { RemoveProjection(false); ShowNotification(MySpaceTexts.NotificationProjectorGridSize); return; } if (m_clipboard.CopiedGrids.Count > 1) { ShowNotification(MySpaceTexts.NotificationProjectorMultipleGrids); } int largestGridIndex = -1; int largestGridBlockCount = -1; for (int i = 0; i < m_clipboard.CopiedGrids.Count; i++) { int currentGridBlockCount = m_clipboard.CopiedGrids[i].CubeBlocks.Count; if (currentGridBlockCount > largestGridBlockCount) { largestGridBlockCount = currentGridBlockCount; largestGridIndex = i; } } ParallelTasks.Parallel.Start(delegate() { m_originalGridBuilder = (MyObjectBuilder_CubeGrid)m_clipboard.CopiedGrids[largestGridIndex].Clone(); m_clipboard.ProcessCubeGrid(m_clipboard.CopiedGrids[largestGridIndex]); MyEntities.RemapObjectBuilder(m_originalGridBuilder); }, delegate() { SendNewBlueprint(m_originalGridBuilder); }); }
public static BoundingSphere CalculateBoundingSphere(this MyObjectBuilder_CubeGrid grid) { return(BoundingSphere.CreateFromBoundingBox(grid.CalculateBoundingBox())); }
private void SetGridFromBuilderInternal(MyObjectBuilder_CubeGrid grid, Vector3 offset) { BeforeCreateGrid(grid); m_copiedGrids.Add(grid); m_copiedGridOffsets.Add(offset); RemovePilots(grid); }
public void SetGridFromBuilder(MyObjectBuilder_CubeGrid grid, Vector3 dragPointDelta, float dragVectorLength) { m_copiedGrids.Clear(); m_copiedGridOffsets.Clear(); m_dragPointToPositionLocal = dragPointDelta; m_dragDistance = dragVectorLength; var transform = grid.PositionAndOrientation ?? MyPositionAndOrientation.Default; m_pasteDirUp = transform.Up; m_pasteDirForward = transform.Forward; SetGridFromBuilderInternal(grid, Vector3.Zero); }
private void RemovePilots(MyObjectBuilder_CubeGrid grid) { foreach (var block in grid.CubeBlocks) { MyObjectBuilder_Cockpit cockpit = block as MyObjectBuilder_Cockpit; if (cockpit != null) { cockpit.ClearPilotAndAutopilot(); } else { MyObjectBuilder_LandingGear landingGear = block as MyObjectBuilder_LandingGear; if (landingGear != null) { landingGear.IsLocked = false; landingGear.MasterToSlave = null; landingGear.AttachedEntityId = null; landingGear.LockMode = LandingGearMode.Unlocked; } } } }
public override void GetGridSpawnMaterials(MyObjectBuilder_CubeGrid grid) { ClearRequiredMaterials(); foreach (var block in grid.CubeBlocks) { MyComponentStack.GetMountedComponents(m_materialList, block); if (block.ConstructionStockpile != null) { foreach (var item in block.ConstructionStockpile.Items) { if (item.PhysicalContent != null) { var itemId = item.PhysicalContent.GetId(); m_materialList.AddMaterial(itemId, item.Amount, item.Amount, addToDisplayList: false); } } } } }
public static void BiggestGrid(this IEnumerable <MyObjectBuilder_CubeGrid> Grids, out MyObjectBuilder_CubeGrid BiggestGrid) { BiggestGrid = Grids.Aggregate((i1, i2) => i1.CubeBlocks.Count > i2.CubeBlocks.Count ? i1 : i2); }
public void Update() { if (Entity == null || Entity.Closed || Entity.MarkedForClose) { return; } if (CoreMagRails.instance == null) { return; } if (!valid) { return; } if (initDirty) { initBlockSettings(); } if (CoreMagRails.instance.debug != DebugLevel.Verbose) { if (updateHook) { CoreMagRails.UpdateHook -= Update; updateHook = false; } return; } if (ents.Count == 0) { int n = 30; while (n-- > 0) { var prefab = MyDefinitionManager.Static.GetPrefabDefinition("HoloProjectionPrefab"); MyObjectBuilder_CubeGrid p_grid = prefab.CubeGrids[0]; MyAPIGateway.Entities.RemapObjectBuilder(p_grid); p_grid.CreatePhysics = false; IMyEntity grid = MyAPIGateway.Entities.CreateFromObjectBuilder(p_grid); grid.Flags &= ~EntityFlags.Save; //do not save grid.Flags &= ~EntityFlags.Sync; //do not sync MyAPIGateway.Entities.AddEntity(grid); ents.Add(grid); } } Vector3D home = WorldtoGrid(Entity.WorldMatrix.Translation, Entity.WorldMatrixNormalizedInv); home.X -= def.X; home.Y -= def.Y; home.Z -= def.Z; if (def.type == RailType.curve) { Vector3D baseangle = new Vector3D(0, 0, 1); foreach (var ent in ents) { int index = ents.IndexOf(ent); //MyAPIGateway.Utilities.ShowMessage("Test", Entity.WorldMatrix.Translation.ToString()); //MyAPIGateway.Utilities.ShowMessage("TestD", (Entity.WorldMatrix.Translation + Vector3D.Multiply(Entity.WorldMatrix.Down, 3)).ToString()); //going to use X and Z double d_angle = ((double)index / 30) / 2; d_angle += 0.5d; if (def.X > 0) { d_angle += 0.5d; } d_angle *= Math.PI; double s = Math.Sin(d_angle); double c = Math.Cos(d_angle); var angle = new Vector3D(-baseangle.Z * s, 0, baseangle.Z * c); //note that for the rail part this will be easier... var radianvector = angle * def.radius; radianvector += home; ent.SetPosition(GridToWorld(radianvector, Entity.WorldMatrix)); } } else if (def.type == RailType.straight) { home.Z -= def.size.Z * 0.5d * def.sizeenum; foreach (var ent in ents) { double index = ents.IndexOf(ent); var lerp = Vector3.Lerp(home, new Vector3(home.X, home.Y, def.size.Z * 0.5d * def.sizeenum), (float)(index / 30.0d)); //var newpos = home + new Vector3D(0, 0, (index - 15d) / 5); ent.SetPosition(GridToWorld(lerp, Entity.WorldMatrix)); } } else if (def.type == RailType.slant) { home.Z -= def.size.Z * 0.5d * def.sizeenum; //Log.DebugWrite( DebugLevel.Info, "Drawing line"); //Log.DebugWrite(DebugLevel.Info, home); foreach (var ent in ents) { double index = ents.IndexOf(ent); var lerp = Vector3.Lerp(home, new Vector3(home.X, -def.min.Y, def.size.Z * 0.5d * def.sizeenum), (float)(index / 30.0d)); //var newpos = new Vector3D(home.X, ( home.Y + (def.min.Y - home.Y) * (((index - 15d) / 5) / def.size.Z)), home.Z + ((index - 15d) / 5)); //Log.DebugWrite(DebugLevel.Info, lerp); ent.SetPosition(GridToWorld(lerp, Entity.WorldMatrix)); } } else if (def.type == RailType.cross) { var ftb = new Vector3D(home); ftb.Z -= def.size.Z * 0.5d * def.sizeenum; var ltr = new Vector3D(home); ltr.X -= def.size.X * 0.5d * def.sizeenum; foreach (var ent in ents) { double index = ents.IndexOf(ent); Vector3D lerp; if (index % 2 == 0) { lerp = Vector3D.Lerp(ftb, new Vector3D(ftb.X, ftb.Y, def.size.Z * 0.5d * def.sizeenum), (float)(index / 30.0d)); } else { lerp = Vector3D.Lerp(ltr, new Vector3D(def.size.X * 0.5d * def.sizeenum, ltr.Y, ltr.Z), (float)(index / 30.0d)); } ent.SetPosition(GridToWorld(lerp, Entity.WorldMatrix)); } } //DOSTUFF }
public override bool HandleCommand(ulong userId, string[] words) { bool force = false; if (words.FirstOrDefault(x => x.ToLower() == "force") != null) { force = true; } HashSet <IMyEntity> entities = new HashSet <IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities); }); List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>(); int count = 0; Wrapper.GameAction(() => { foreach (IMyEntity entity in entities) { if (entity.InScene) { continue; } if (!(entity is IMyCubeGrid)) { continue; } MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (builder == null) { continue; } count++; if (!force) { continue; } IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (grid.BigOwners.Count > 0) { ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } grid.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); grid.InScene = true; grid.CastShadows = true; builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows); MyAPIGateway.Entities.RemapObjectBuilder(builder); Logging.WriteLineAndConsole("Conceal", string.Format("Force Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, builder.EntityId)); /* * entity.InScene = true; * entity.CastShadows = true; * entity.Visible = true; */ //CubeGridEntity newEntity = new CubeGridEntity(builder); //SectorObjectManager.Instance.AddEntity(newEntity); BaseEntityNetworkManager.BroadcastRemoveEntity(entity); MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(builder); addList.Add(builder); MyAPIGateway.Multiplayer.SendEntitiesCreated(addList); addList.Clear(); } }); if (!force) { Logging.WriteLineAndConsole(string.Format("Command would Reveal {0} grids. Type /admin reveal force to reveal them.", count)); } else { Logging.WriteLineAndConsole(string.Format("Command Revealed {0} grids", count)); } return(true); }
public virtual void BeforeBlockDeserialization(MyObjectBuilder_CubeGrid builder) { ConveyorSystem.BeforeBlockDeserialization(builder.ConveyorLines); }
private void MergeData(MyObjectBuilder_CubeGrid cubeGridObject, ref Dictionary <Int64, Int64> idReplacementTable) { if (cubeGridObject == null) { return; } cubeGridObject.EntityId = MergeId(cubeGridObject.EntityId, ref idReplacementTable); foreach (var cubeGrid in cubeGridObject.CubeBlocks) { cubeGrid.EntityId = MergeId(cubeGrid.EntityId, ref idReplacementTable); //cubeGrid.MultiBlockId // ??? var cockpit = cubeGrid as MyObjectBuilder_Cockpit; if (cockpit != null) { cockpit.RemoveHierarchyCharacter(cockpit.Pilot); cockpit.Pilot = null; // remove any pilots. } var motorBase = cubeGrid as MyObjectBuilder_MotorBase; if (motorBase != null && motorBase.RotorEntityId.HasValue) { // reattach motor/rotor to correct entity. motorBase.RotorEntityId = MergeId(motorBase.RotorEntityId.Value, ref idReplacementTable); } var pistonBase = cubeGrid as MyObjectBuilder_PistonBase; if (pistonBase != null && pistonBase.TopBlockId.HasValue) { // reattach PistonBase (and ExtendedPistonBase) to correct entity. pistonBase.TopBlockId = MergeId(pistonBase.TopBlockId.Value, ref idReplacementTable); } var shipConnector = cubeGrid as MyObjectBuilder_ShipConnector; if (shipConnector != null) { // reattach ShipConnector to correct entity. shipConnector.ConnectedEntityId = MergeId(shipConnector.ConnectedEntityId, ref idReplacementTable); } var buttonPanel = cubeGrid as MyObjectBuilder_ButtonPanel; if (buttonPanel != null) { // reattach Button Panels to correct entity. RenumberToolbar(buttonPanel.Toolbar, ref idReplacementTable); } var timerBlock = cubeGrid as MyObjectBuilder_TimerBlock; if (timerBlock != null) { // reattach Timer actions to correct entity. RenumberToolbar(timerBlock.Toolbar, ref idReplacementTable); } var sensorBlock = cubeGrid as MyObjectBuilder_SensorBlock; if (sensorBlock != null) { // reattach Sensor actions to correct entity. RenumberToolbar(sensorBlock.Toolbar, ref idReplacementTable); } var shipController = cubeGrid as MyObjectBuilder_ShipController; if (shipController != null) { // reattach Ship Controller actions to correct entity. RenumberToolbar(shipController.Toolbar, ref idReplacementTable); } } AddEntity(cubeGridObject); }
static void OnThrowMessageSuccess(MyObjectBuilder_CubeGrid grid, Vector3D position, Vector3D linearVelocity, float mass, MyCueId throwSound) { MySessionComponentThrower.Static.Throw(grid, position, linearVelocity, mass, throwSound); }
public void SpawnCargoShipGroup(Vector3 startPosition, Vector3 stopPosition, ulong remoteUserId = 0) { try { //Calculate lowest and highest frequencies float lowestFrequency = 999999; float highestFrequency = 0; foreach (MySpawnGroupDefinition entry in MyDefinitionManager.Static.GetSpawnGroupDefinitions()) { if (entry.Frequency < lowestFrequency) { lowestFrequency = entry.Frequency; } if (entry.Frequency > highestFrequency) { highestFrequency = entry.Frequency; } } if (lowestFrequency <= 0) { lowestFrequency = 1; } //Get a list of which groups *could* spawn Random random = new Random((int)DateTime.Now.ToBinary()); double randomChance = random.NextDouble(); randomChance = randomChance * (highestFrequency / lowestFrequency); List <MySpawnGroupDefinition> possibleGroups = new List <MySpawnGroupDefinition>(); foreach (MySpawnGroupDefinition entry in MyDefinitionManager.Static.GetSpawnGroupDefinitions()) { if (entry.Frequency >= randomChance) { possibleGroups.Add(entry); } } //Determine which group *will* spawn randomChance = random.NextDouble(); int randomShipIndex = Math.Max(0, Math.Min((int)Math.Round(randomChance * possibleGroups.Count, 0), possibleGroups.Count - 1)); MySpawnGroupDefinition randomSpawnGroup = possibleGroups[randomShipIndex]; ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Spawning cargo group '" + randomSpawnGroup.DisplayNameText.ToString() + "' ..."); //Spawn the ships in the group Matrix orientation = Matrix.CreateLookAt(startPosition, stopPosition, new Vector3(0, 1, 0)); foreach (MySpawnGroupDefinition.SpawnGroupPrefab entry in randomSpawnGroup.Prefabs) { MyPrefabDefinition matchedPrefab = null; foreach (var prefabEntry in MyDefinitionManager.Static.GetPrefabDefinitions()) { MyPrefabDefinition prefabDefinition = prefabEntry.Value; if (prefabDefinition.Id.SubtypeId.ToString() == entry.SubtypeId) { matchedPrefab = prefabDefinition; break; } } if (matchedPrefab == null) { continue; } //TODO - Build this to iterate through all cube grids in the prefab MyObjectBuilder_CubeGrid objectBuilder = matchedPrefab.CubeGrids[0]; //Create the ship CubeGridEntity cubeGrid = new CubeGridEntity(objectBuilder); //Set the ship position and orientation Vector3 shipPosition = Vector3.Transform(entry.Position, orientation) + startPosition; orientation.Translation = shipPosition; MyPositionAndOrientation newPositionOrientation = new MyPositionAndOrientation(orientation); cubeGrid.PositionAndOrientation = newPositionOrientation; //Set the ship velocity //Speed is clamped between 1.0f and the max cube grid speed Vector3 travelVector = stopPosition - startPosition; travelVector.Normalize(); Vector3 shipVelocity = travelVector * (float)Math.Min(cubeGrid.MaxLinearVelocity, Math.Max(1.0f, entry.Speed)); cubeGrid.LinearVelocity = shipVelocity; cubeGrid.IsDampenersEnabled = false; foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.BaseCubeBlocks) { //Set the beacon names if (cubeBlock.TypeId == typeof(MyObjectBuilder_Beacon)) { MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock; beacon.CustomName = entry.BeaconText; } //Set the owner of every block //TODO - Find out if setting to an arbitrary non-zero works for this // TODO Fix the rest of the player manager methods //cubeBlock.Owner = PlayerMap.Instance.GetServerVirtualPlayerId(); cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction; } //And add the ship to the world SectorObjectManager.Instance.AddEntity(cubeGrid); } ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Cargo group '" + randomSpawnGroup.DisplayNameText.ToString() + "' spawned with " + randomSpawnGroup.Prefabs.Count.ToString() + " ships at " + startPosition.ToString()); } catch (Exception ex) { LogManager.ErrorLog.WriteLine(ex); } }
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); }
public static void CalculateItemRequirements(MyObjectBuilder_CubeGrid[] blocksToBuild, MyComponentList buildComponents) { buildComponents.Clear(); foreach (var grid in blocksToBuild) { foreach (var block in grid.CubeBlocks) { var compound = block as MyObjectBuilder_CompoundCubeBlock; if (compound != null) { foreach (var subblock in compound.Blocks) { AddSingleBlockRequirements(subblock, buildComponents); } } else { AddSingleBlockRequirements(block, buildComponents); } } } }
public static void PlacePrefabToWorld(MyObjectBuilder_CubeGrid[] currentPrefab, Vector3D position, List<MyCubeGrid> createdGrids = null) { Vector3D newPosition = Vector3D.Zero; Vector3D positionOffset = Vector3D.Zero; bool firstIteration = true; MyEntities.RemapObjectBuilderCollection(currentPrefab); foreach (var gridBuilder in currentPrefab) { if (gridBuilder.PositionAndOrientation.HasValue) { if (firstIteration) { positionOffset = position - gridBuilder.PositionAndOrientation.Value.Position; firstIteration = false; newPosition = position; } else { newPosition = gridBuilder.PositionAndOrientation.Value.Position + positionOffset; } } MyPositionAndOrientation originalPos = gridBuilder.PositionAndOrientation.Value; originalPos.Position = newPosition; gridBuilder.PositionAndOrientation = originalPos; MyCubeGrid currentGrid = MyEntities.CreateFromObjectBuilder(gridBuilder) as MyCubeGrid; if (currentGrid != null) { currentGrid.ClearSymmetries(); currentGrid.Physics.LinearVelocity = Vector3D.Zero; currentGrid.Physics.AngularVelocity = Vector3D.Zero; if (createdGrids != null) { createdGrids.Add(currentGrid); } MyEntities.Add(currentGrid, true); } } }
public MyCubeBlockDefinition GetFirstBlockDefinition(MyObjectBuilder_CubeGrid grid = null) { if (grid == null) if (m_copiedGrids.Count > 0) grid = m_copiedGrids[0]; else return null; if (grid.CubeBlocks.Count > 0) { MyDefinitionId firstBlock = grid.CubeBlocks[0].GetId(); return MyDefinitionManager.Static.GetCubeBlockDefinition(firstBlock); } return null; }
internal void SetNewBlueprint(MyObjectBuilder_CubeGrid gridBuilder) { m_originalGridBuilder = gridBuilder; var clone = m_originalGridBuilder;//(MyObjectBuilder_CubeGrid)gridBuilder.Clone(); //MyEntities.RemapObjectBuilder(clone); //m_clipboard.ProcessCubeGrid(clone); m_clipboard.SetGridFromBuilder(clone, Vector3.Zero, 0f); if (m_instantBuildingEnabled) { ResetRotation(); var boundingBox = clone.CalculateBoundingBox(); // Add 1 to get the center out of the bounds and another 1 for a gap m_projectionOffset.Y = Math.Abs((int)(boundingBox.Min.Y / MyDefinitionManager.Static.GetCubeSize(clone.GridSizeEnum))) + 2; } InitializeClipboard(); }
public void SetGridFromBuilders(MyObjectBuilder_CubeGrid[] grids, Vector3 dragPointDelta, float dragVectorLength) { ShowModdedBlocksWarning = true; if (IsActive) { Deactivate(); } m_copiedGrids.Clear(); m_copiedGridOffsets.Clear(); if (grids.Length == 0) return; MatrixD pasteMatrix = GetPasteMatrix(); m_dragPointToPositionLocal = dragPointDelta; m_dragDistance = dragVectorLength; var transform = grids[0].PositionAndOrientation ?? MyPositionAndOrientation.Default; m_pasteDirUp = transform.Up; m_pasteDirForward = transform.Forward; SetGridFromBuilderInternal(grids[0], Vector3.Zero); MatrixD invMatrix = grids[0].PositionAndOrientation.HasValue ? grids[0].PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity; invMatrix = MatrixD.Invert(invMatrix); for (int i = 1; i < grids.Length; ++i) { Vector3D offset = grids[i].PositionAndOrientation.HasValue ? (Vector3D)grids[i].PositionAndOrientation.Value.Position : Vector3D.Zero; offset = Vector3D.Transform(offset, invMatrix); SetGridFromBuilderInternal(grids[i], offset); } //Activate(); }
private void OnNewBlueprintSuccess(MyObjectBuilder_CubeGrid projectedGrid) { if (MyEventContext.Current.IsLocallyInvoked == false) { SetNewBlueprint(projectedGrid); } }
protected void BeforeCreateGrid(MyObjectBuilder_CubeGrid grid) { Debug.Assert(grid.CubeBlocks.Count > 0, "The grid does not contain any blocks"); foreach (var block in grid.CubeBlocks) { var defId = block.GetId(); MyCubeBlockDefinition blockDef = null; MyDefinitionManager.Static.TryGetCubeBlockDefinition(defId, out blockDef); if (blockDef == null) continue; MyCubeBuilder.BuildComponent.BeforeCreateBlock(blockDef, GetClipboardBuilder(), block, buildAsAdmin: MySession.Static.IsAdminModeEnabled(Sync.MyId)); } }
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); }
private static BoundingSphere GetBoundingSphereForGrids(MyObjectBuilder_CubeGrid[] currentPrefab) { BoundingSphere boundingSphere = new BoundingSphere(Vector3.Zero, float.MinValue); foreach (var gridBuilder in currentPrefab) { BoundingSphere localSphere = gridBuilder.CalculateBoundingSphere(); MatrixD gridTransform = gridBuilder.PositionAndOrientation.HasValue ? gridBuilder.PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity; boundingSphere.Include(localSphere.Transform(gridTransform)); } return boundingSphere; }
// might not work? -- updated, needs testing public static List<long> GetBigOwners( MyObjectBuilder_CubeGrid grid ) { Dictionary<long, int> ownerList = new Dictionary<long, int>( ); foreach ( MyObjectBuilder_CubeBlock block in grid.CubeBlocks ) { if ( block.Owner == 0 ) continue; if ( ownerList.ContainsKey( block.Owner ) ) ownerList[ block.Owner ] = ownerList[ block.Owner ] + 1; else ownerList.Add( block.Owner, 1 ); } int count = ownerList.OrderBy( x => x.Value ).Select( x => x.Value ).FirstOrDefault( ); return ownerList.OrderBy( x => x.Value ).Where( x => x.Value == count ).Select( x => x.Key ).ToList( ); }
private void SendNewBlueprint(MyObjectBuilder_CubeGrid projectedGrid) { SetNewBlueprint(projectedGrid); MyMultiplayer.RaiseEvent(this, x => x.OnNewBlueprintSuccess, projectedGrid); }
public static List<long> GetAllOwners( MyObjectBuilder_CubeGrid grid ) { Dictionary<long, int> ownerList = new Dictionary<long, int>( ); foreach ( MyObjectBuilder_CubeBlock block in grid.CubeBlocks ) { if ( block.Owner == 0 ) continue; if ( ownerList.ContainsKey( block.Owner ) ) ownerList[ block.Owner ] = ownerList[ block.Owner ] + 1; else ownerList.Add( block.Owner, 1 ); } return ownerList.Select( x => x.Key ).ToList( ); }
private void RemoveProjection(bool keepProjection) { m_hiddenBlock = null; m_clipboard.Deactivate(); if (!keepProjection) { m_clipboard.Clear(); m_originalGridBuilder = null; } UpdateEmissivity(); m_statsDirty = true; UpdateText(); //We call this to disable the controls RaisePropertiesChanged(); }
public static bool HasCustomName( MyObjectBuilder_CubeGrid grid, string name, bool exact ) { foreach ( MyObjectBuilder_CubeBlock block in grid.CubeBlocks ) { MyObjectBuilder_TerminalBlock termBlock = block as MyObjectBuilder_TerminalBlock; if ( termBlock != null ) { if ( exact ) { if ( termBlock.CustomName != null && termBlock.CustomName == name ) { return true; } } else { if ( termBlock.CustomName != null && termBlock.CustomName.Contains( name ) ) { return true; } } } } return false; }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( BlockDefinition.ResourceSinkGroup, BlockDefinition.RequiredPowerInput, CalculateRequiredPowerInput); ResourceSink = sinkComp; base.Init(objectBuilder, cubeGrid); if (!MyFakes.ENABLE_PROJECTOR_BLOCK) { return; } var projectorBuilder = (MyObjectBuilder_ProjectorBase)objectBuilder; if (projectorBuilder.ProjectedGrid != null) { m_projectionOffset = projectorBuilder.ProjectionOffset; m_projectionRotation = projectorBuilder.ProjectionRotation; m_savedProjection = projectorBuilder.ProjectedGrid; KeepProjection = projectorBuilder.KeepProjection; } m_showOnlyBuildable = projectorBuilder.ShowOnlyBuildable; InstantBuildingEnabled = projectorBuilder.InstantBuildingEnabled; MaxNumberOfProjections = projectorBuilder.MaxNumberOfProjections; MaxNumberOfBlocksPerProjection = projectorBuilder.MaxNumberOfBlocks; GetOwnershipFromProjector = projectorBuilder.GetOwnershipFromProjector; m_projectionsRemaining = MathHelper.Clamp(projectorBuilder.ProjectionsRemaining, 0, m_maxNumberOfProjections); IsWorkingChanged += MyProjector_IsWorkingChanged; sinkComp.IsPoweredChanged += PowerReceiver_IsPoweredChanged; ResourceSink.Update(); m_statsDirty = true; UpdateText(); NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME; SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; CubeGrid.OnBlockAdded += previewGrid_OnBlockAdded; CubeGrid.OnBlockRemoved += previewGrid_OnBlockRemoved; CubeGrid.OnGridSplit += CubeGrid_OnGridSplit; }
public static bool HasOwner( MyObjectBuilder_CubeGrid grid ) { foreach ( MyObjectBuilder_CubeBlock block in grid.CubeBlocks ) { if ( !( block is MyObjectBuilder_TerminalBlock ) ) continue; MyObjectBuilder_TerminalBlock functional = (MyObjectBuilder_TerminalBlock)block; if ( functional.Owner != 0 ) return true; } return false; }
public abstract void GetGridSpawnMaterials(MyObjectBuilder_CubeGrid grid);
public static bool DoesGridHavePowerSupply( MyObjectBuilder_CubeGrid grid ) { return grid.CubeBlocks.Any( DoesBlockSupplyPower ); }
public virtual void GetObjectBuilder(MyObjectBuilder_CubeGrid ob) { var thrustComp = CubeGrid.Components.Get<MyEntityThrustComponent>(); ob.DampenersEnabled = thrustComp == null || thrustComp.DampenersEnabled; ConveyorSystem.SerializeLines(ob.ConveyorLines); if (ob.ConveyorLines.Count == 0) ob.ConveyorLines = null; if (WheelSystem != null) ob.Handbrake = WheelSystem.HandBrake; if (MySession.Static.Settings.EnableOxygen) { ob.OxygenAmount = GasSystem.GetOxygenAmount(); } if (MyPerGameSettings.EnableJumpDrive) { ob.JumpDriveDirection = JumpSystem.GetJumpDriveDirection(); ob.JumpRemainingTime = JumpSystem.GetRemainingJumpTime(); } }
public override void Remap(MyObjectBuilder_CubeGrid grid) { var transformCopy = LocalTransform; var minToMin = new Dictionary <Vector3I, Vector3I>(grid.CubeBlocks.Count * 3 / 2); foreach (var x in grid.CubeBlocks) { var orig = (Vector3I)x.Min; var cMin = orig; Vector3I cMax; BlockTransformations.ComputeBlockMax(x, out cMax); x.BlockOrientation.Forward = LocalTransform.GetDirection(x.BlockOrientation.Forward); x.BlockOrientation.Up = LocalTransform.GetDirection(x.BlockOrientation.Up); Vector3I.Transform(ref cMin, ref transformCopy, out cMin); Vector3I.Transform(ref cMax, ref transformCopy, out cMax); minToMin[orig] = x.Min = Vector3I.Min(cMin, cMax); var proj = x as MyObjectBuilder_ProjectorBase; // Don't have to update the rotation; it is bound to the world matrix of the projector. if (proj != null) { Vector3I.TransformNormal(ref proj.ProjectionOffset, ref transformCopy, out proj.ProjectionOffset); } } if (grid.BlockGroups != null) { foreach (var g in grid.BlockGroups) { for (var i = 0; i < g.Blocks.Count; i++) { Vector3I tmpOut; if (minToMin.TryGetValue(g.Blocks[i], out tmpOut)) { g.Blocks[i] = tmpOut; } else { g.Blocks[i] = Vector3I.MaxValue; // sorta discards it? } } } } if (grid.ConveyorLines != null) { foreach (var l in grid.ConveyorLines) { l.StartDirection = LocalTransform.GetDirection(l.StartDirection); l.StartPosition = Vector3I.Transform(l.StartPosition, ref transformCopy); l.EndDirection = LocalTransform.GetDirection(l.EndDirection); l.EndPosition = Vector3I.Transform(l.EndPosition, ref transformCopy); if (l.Sections == null) { continue; } for (var s = 0; s < l.Sections.Count; s++) { l.Sections[s] = new SerializableLineSectionInformation() { Direction = LocalTransform.GetDirection(l.Sections[s].Direction), Length = l.Sections[s].Length } } ; } } }