/// <summary> /// Gets positions of all floor tiles in the map and adds them to a list of floor tiles. /// </summary> public void LocateFloorTilesPos(CubeGrid cubeGrid, float cubeSize) { List <Vector3> _floorTilesPos = new List <Vector3>(); _floorTilesPos.Clear(); for (int x = 0; x < cubeGrid.cubes.GetLength(0); x++) { for (int y = 0; y < cubeGrid.cubes.GetLength(1); y++) { for (int z = 0; z < cubeGrid.cubes.GetLength(2); z++) { if (cubeGrid.cubes[x, y, z].caseValue == 51) { Vector3 _floorTilePos = new Vector3((x * cubeSize) + (cubeSize / 2), y * cubeSize, (z * cubeSize) + (cubeSize / 2)); _floorTilesPos.Add(_floorTilePos); } } } } SetFloorTilesPos(_floorTilesPos); }
private void CreateChunk(int x, int y, int z) { CubeGrid chunk = Instantiate(cubeGridPrefab) as CubeGrid; chunk.Initialize(resolution, chunkSize, isoLevel, interpolation, x, y, z, heightMap, noiseWeight); chunk.transform.parent = transform; chunk.transform.localPosition = new Vector3(x * chunkSize, y * chunkSize, z * chunkSize); if (x > 0) { chunks[x - 1, y, z].xNeighbor = chunk; } if (y > 0) { chunks[x, y - 1, z].yNeighbor = chunk; } if (z > 0) { chunks[x, y, z - 1].zNeighbor = chunk; } if (x > 0 && z > 0) { chunks[x - 1, y, z - 1].xzNeighbor = chunk; } if (x > 0 && y > 0) { chunks[x - 1, y - 1, z].xyNeighbor = chunk; } if (z > 0 && y > 0) { chunks[x, y - 1, z - 1].zyNeighbor = chunk; } if (x > 0 && y > 0 && z > 0) { chunks[x - 1, y - 1, z - 1].xyzNeighbor = chunk; } chunks[x, y, z] = chunk; }
private static Block InitMapAndFindStartBlock(CubeGrid grid, Vector3D start, Dictionary <Vector3I, GridLocation> map) { Block startBlock = null; var minDistance = double.MaxValue; foreach (var block in grid.Blocks) { map[block.GridPosition.ToVector3I()] = new GridLocation(block); var distanceSquared = (block.Position.ToVector3D() - start).LengthSquared(); if (distanceSquared < minDistance) { minDistance = distanceSquared; startBlock = block; } } if (startBlock is null) { throw new InvalidOperationException("Couldn't find a starting block for nav graph."); } return(startBlock); }
/// <summary> /// Adds block to compound (should be used for clients). /// </summary> /// <returns>true if the block has been addded, otherwise false</returns> public bool Add(ushort id, MySlimBlock block) { if (!CanAddBlock(block)) { return(false); } // block.AddNeighbours(); Debug.Assert(block.BlockDefinition.Size == Vector3I.One, "Only blocks with size=1 are supported!"); if (m_blocks.ContainsKey(id)) { Debug.Fail("Cannot add block with existing id to compound block!"); return(false); } m_blocks.Add(id, block); MatrixD parentWorldMatrix = this.Parent.WorldMatrix; MatrixD blockLocalMatrix = MatrixD.Identity; GetBlockLocalMatrixFromGridPositionAndOrientation(block, ref blockLocalMatrix); MatrixD worldMatrix = blockLocalMatrix * parentWorldMatrix; block.FatBlock.PositionComp.SetWorldMatrix(worldMatrix, this, true); block.FatBlock.OnAddedToScene(this); block.FatBlock.Hierarchy.Parent = Hierarchy; CubeGrid.UpdateBlockNeighbours(SlimBlock); RefreshTemplates(); return(true); }
internal FatNavGraph CreateGraph(CubeGrid grid, Vector3D start, Vector3I up) { var map = new Dictionary <Vector3I, GridLocation>(capacity: 256); var startBlock = InitMapAndFindStartBlock(grid, start, map); var navGraph = new FatNavGraph(); var steps = new StepVectors(up); var cubeQueue = new Queue <Block>(); var nodeBuilder = new FatNodeBuilder(); cubeQueue.Enqueue(startBlock); while (cubeQueue.Count > 0) { var currentCube = cubeQueue.Dequeue(); var currentPosition = currentCube.GridPosition.ToVector3I(); map[currentPosition].Visited = true; // check for obstacles (2 blocks above the site) if (map.ContainsKey(currentPosition + up) || map.ContainsKey(currentPosition + 2 * up)) { continue; } var fatNode = nodeBuilder.Create(currentCube.Position); // TODO(P): Add some position offset. map[currentPosition].Node = fatNode; navGraph.Nodes.Add(fatNode); ExploreSides(map, cubeQueue, steps, currentPosition, fatNode); } return(navGraph); }
public BuildCheckResult CanBuild(MySlimBlock projectedBlock, bool checkHavokIntersections) { MyBlockOrientation blockOrientation = projectedBlock.Orientation; //GR: For rotation take into account: //the projected block orientation Quaternion blockOrientationQuat; blockOrientation.GetQuaternion(out blockOrientationQuat); //GR: The projector block orientation (which is relative to the Cubegrid orientation) Quaternion projQuat = Quaternion.Identity; Orientation.GetQuaternion(out projQuat); blockOrientationQuat = Quaternion.Multiply(projQuat, blockOrientationQuat); //GR: The orienation settings of the projector //Take into account order of multiplication to review! blockOrientationQuat = Quaternion.Multiply(ProjectionRotationQuaternion, blockOrientationQuat); Vector3I projectedMin = CubeGrid.WorldToGridInteger(projectedBlock.CubeGrid.GridIntegerToWorld(projectedBlock.Min)); Vector3I projectedMax = CubeGrid.WorldToGridInteger(projectedBlock.CubeGrid.GridIntegerToWorld(projectedBlock.Max)); Vector3I blockPos = CubeGrid.WorldToGridInteger(projectedBlock.CubeGrid.GridIntegerToWorld(projectedBlock.Position)); Vector3I min = new Vector3I(Math.Min(projectedMin.X, projectedMax.X), Math.Min(projectedMin.Y, projectedMax.Y), Math.Min(projectedMin.Z, projectedMax.Z)); Vector3I max = new Vector3I(Math.Max(projectedMin.X, projectedMax.X), Math.Max(projectedMin.Y, projectedMax.Y), Math.Max(projectedMin.Z, projectedMax.Z)); projectedMin = min; projectedMax = max; if (!CubeGrid.CanAddCubes(projectedMin, projectedMax)) { return(BuildCheckResult.IntersectedWithGrid); } MyGridPlacementSettings settings = new MyGridPlacementSettings(); settings.SnapMode = SnapMode.OneFreeAxis; var mountPoints = projectedBlock.BlockDefinition.GetBuildProgressModelMountPoints(1.0f); bool isConnected = MyCubeGrid.CheckConnectivity(this.CubeGrid, projectedBlock.BlockDefinition, mountPoints, ref blockOrientationQuat, ref blockPos); if (isConnected) { if (CubeGrid.GetCubeBlock(blockPos) == null) { if (checkHavokIntersections) { if (MyCubeGrid.TestPlacementAreaCube(CubeGrid, ref settings, projectedMin, projectedMax, blockOrientation, projectedBlock.BlockDefinition, CubeGrid)) { return(BuildCheckResult.OK); } else { return(BuildCheckResult.IntersectedWithSomethingElse); } } else { return(BuildCheckResult.OK); } } else { return(BuildCheckResult.AlreadyBuilt); } } else { return(BuildCheckResult.NotConnected); } }
private void ComponentStack_IsFunctionalChanged() { UpdateIsWorking(); CubeGrid.UpdateOwnership(OwnerId, IsFunctional); }
public override void OnBuildSuccess(long builtBy) { ResourceSink.Update(); UpdateHavokCollisionSystemID(CubeGrid.GetPhysicsBody().HavokCollisionSystemID); base.OnBuildSuccess(builtBy); }
protected override bool Attach(MyAttachableTopBlockBase rotor, bool updateGroup = true) { Debug.Assert(rotor != null, "Rotor cannot be null!"); Debug.Assert(m_constraint == null, "Already attached, call detach first!"); if (rotor is MyMotorRotor) { if (CubeGrid.Physics != null && CubeGrid.Physics.Enabled) { m_topBlock = rotor; m_topGrid = m_topBlock.CubeGrid; var rotorBody = m_topGrid.Physics.RigidBody; rotorBody.MaxAngularVelocity = float.MaxValue; rotorBody.Restitution = 0.5f; CubeGrid.GetPhysicsBody().HavokWorld.BreakOffPartsUtil.UnmarkEntityBreakable(rotorBody); if (MyFakes.WHEEL_SOFTNESS) { HkUtils.SetSoftContact(rotorBody, null, MyPhysicsConfig.WheelSoftnessRatio, MyPhysicsConfig.WheelSoftnessVelocity); } var info = HkGroupFilter.CalcFilterInfo(rotorBody.Layer, CubeGrid.GetPhysicsBody().HavokCollisionSystemID, 1, 1); rotorBody.SetCollisionFilterInfo(info); HkWheelConstraintData data = new HkWheelConstraintData(); var suspensionAx = PositionComp.LocalMatrix.Forward; var posA = DummyPosition + (suspensionAx * m_height); var posB = (rotor as MyMotorRotor).DummyPosLoc; var axisA = PositionComp.LocalMatrix.Up; var axisAPerp = PositionComp.LocalMatrix.Forward; var axisB = rotor.PositionComp.LocalMatrix.Up; //empirical values because who knows what havoc sees behind this //docs say one value should mean same effect for 2 ton or 200 ton vehicle //but we have virtual mass blocks so real mass doesnt corespond to actual "weight" in game and varying gravity data.SetSuspensionDamping(m_damping); data.SetSuspensionStrength(m_strenth); //Min/MaxHeight also define the limits of the suspension and SuspensionTravel lowers this limit data.SetSuspensionMinLimit((BlockDefinition.MinHeight - m_height) * SuspensionTravel); data.SetSuspensionMaxLimit((BlockDefinition.MaxHeight - m_height) * SuspensionTravel); data.SetInBodySpace(posB, posA, axisB, axisA, suspensionAx, suspensionAx, RotorGrid.Physics, CubeGrid.Physics); m_constraint = new HkConstraint(rotorBody, CubeGrid.Physics.RigidBody, data); m_constraint.WantRuntime = true; CubeGrid.Physics.AddConstraint(m_constraint); if (!m_constraint.InWorld) { Debug.Fail("Constraint not added!"); CubeGrid.Physics.RemoveConstraint(m_constraint); m_constraint = null; return(false); } m_constraint.Enabled = true; m_topBlock.Attach(this); m_isAttached = true; PropagateFriction(m_friction); UpdateIsWorking(); if (m_updateBrakeNeeded) { UpdateBrake(); } if (m_updateFrictionNeeded) { FrictionChanged(); } if (updateGroup) { OnConstraintAdded(GridLinkTypeEnum.Physical, m_topGrid); OnConstraintAdded(GridLinkTypeEnum.Logical, m_topGrid); } return(true); } } return(false); }
public void Start() { this.grid = new CubeGrid(this, this.computeShader); meshFilter = !meshFilter?this.GetComponent <MeshFilter>() : meshFilter; }
private bool processGUIMenus(SceneView _view) { Rect _rect = new Rect(10, 10, 100, 400); GUILayout.BeginArea(_rect); int selectedGridIndex = 0; switch (m_editMode) { case EditMode.addBlock: { selectedGridIndex = 0; break; } case EditMode.delBlock: { selectedGridIndex = 1; break; } } string[] _buttons = new string[] { "Add", "Delete", "Clear", "Destroy hiden", "Save", "Load", "Exit" }; int oldButtonSelected = selectedGridIndex; selectedGridIndex = GUILayout.SelectionGrid(selectedGridIndex, _buttons, 1); GUILayout.EndArea(); processSelectionGridMenu(_view); if (oldButtonSelected != selectedGridIndex) { switch (selectedGridIndex) { case 0: { m_editMode = EditMode.addBlock; break; } case 1: { m_editMode = EditMode.delBlock; break; } case 2: { m_Instance.ClearDictionary(); break; } case 3: { DeleteHidenObjects(); break; } case 4: { string path = EditorUtility.SaveFilePanelInProject("Select level path", "Level", "xml", "Select a file"); if (path.Length != 0) { m_Instance.SerializeMe(path); } break; } case 5: { string path = EditorUtility.OpenFilePanel("Select level path", Application.dataPath, "xml"); if (path.Length != 0) { m_Instance.ClearDictionary(); ScriptableObject.DestroyImmediate(m_Instance); m_Instance = CubeGridXML.ToGrid(path); CubeGridSingletonObject sing = GameObject.FindObjectOfType <CubeGridSingletonObject>(); if (sing != null) { sing.Grid = m_Instance; } } break; } case 6: { DeselectThisGrid(); break; } } return(true); } ; return(false); }
void OnSceneGUI(SceneView _view) { // нет выделенного объекта - нет инспектора. if (!target) { return; } // Получаем указатель на выделенныйобъект. m_Instance = ((CubeGrid)target); if (!m_Instance) { return; } if (m_Instance.m_CubeLibrary == null) { return; } ; m_Library = m_Instance.m_CubeLibrary; if (!m_Instance.currentPrefab) { //Попытаемся получить первый куб из библиотеки, если он не выбран. m_Instance.currentPrefab = m_Library.GetGameObjectByIndex(0); if (!m_Instance.currentPrefab) { // Получить не удалось, в библиотеке нет элементов. return; } } ; if (processGUIMenus(_view)) { return; } float blockSize = m_Instance.gridSize; //float halfBlockSize = blockSize / 2.0f; Quaternion noRotation = Quaternion.Euler(0, 0, 0); if (Event.current.type == EventType.layout) { if (!m_marker) { // Создаем маркер GameObject blockInst = AssetDatabase.LoadAssetAtPath <GameObject>("Assets/Tiles/pre_Cursor.prefab"); blockInst.transform.localScale = new Vector3(blockSize, blockSize, blockSize); m_marker = Instantiate(blockInst, intersectionPoint, noRotation) as GameObject; m_marker.name = "MARKER"; m_marker.hideFlags = HideFlags.HideAndDontSave | HideFlags.NotEditable | HideFlags.HideInInspector | HideFlags.HideInHierarchy; DestroyImmediate(m_marker.GetComponent <BoxCollider>()); meshRenderer = m_marker.GetComponent <MeshRenderer>(); m_markerMaterial = new Material(meshRenderer.sharedMaterial); m_markerMaterial.color = Color.Lerp(Color.green, meshRenderer.sharedMaterial.color, 0.85f); meshRenderer.sharedMaterial = m_markerMaterial; } // Запрещаем выделение других объектов. HandleUtility.AddDefaultControl(GUIUtility.GetControlID(GetHashCode(), FocusType.Passive)); } // Обрабатываем события редактора. switch (Event.current.type) { #region MouseMove case EventType.mouseMove: { m_currentObject = null; switch (m_editMode) { case EditMode.addBlock: case EditMode.delBlock: { RaycastHit hitInfo = new RaycastHit(); Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (Physics.Raycast(ray, out hitInfo)) { if (m_editMode == EditMode.addBlock) { Vector3 pointOnCollider = hitInfo.transform.position + hitInfo.normal * blockSize; intersectionPoint = pointOnCollider; } else { m_currentObject = hitInfo.transform.gameObject; intersectionPoint = hitInfo.transform.position; } intersectionPoint.x = intersectionPoint.x - intersectionPoint.x % blockSize; intersectionPoint.y = intersectionPoint.y - intersectionPoint.y % blockSize; intersectionPoint.z = intersectionPoint.z - intersectionPoint.z % blockSize; } else { Plane hPlane = new Plane(Vector3.up, Vector3.zero); float distance = 0; if (hPlane.Raycast(ray, out distance)) { // make this local pointOnXY = ray.GetPoint(distance); intersectionPoint = new Vector3(pointOnXY.x, pointOnXY.y, pointOnXY.z); intersectionPoint.x = intersectionPoint.x - intersectionPoint.x % blockSize; intersectionPoint.y = intersectionPoint.y - intersectionPoint.y % blockSize; intersectionPoint.z = intersectionPoint.z - intersectionPoint.z % blockSize; if (Physics.Raycast(pointOnXY, intersectionPoint, out hitInfo, Vector3.Distance(pointOnXY, intersectionPoint))) { intersectionPoint = hitInfo.point; intersectionPoint.x = intersectionPoint.x - intersectionPoint.x % blockSize; intersectionPoint.y = intersectionPoint.y - intersectionPoint.y % blockSize; intersectionPoint.z = intersectionPoint.z - intersectionPoint.z % blockSize; } } } Event.current.Use(); break; } } break; } #endregion #region MouseUp case EventType.mouseUp: { if (Event.current.button == 0) { if (!(m_editMode == EditMode.addBlock || m_editMode == EditMode.delBlock)) { break; } switch (m_editMode) { case EditMode.addBlock: { GameObject CreatedCube; m_Instance.CreateCubeAt(intersectionPoint, out CreatedCube); Event.current.Use(); break; } case EditMode.delBlock: { if (m_currentObject) { m_Instance.DeleteCubeAt(m_currentObject.transform.position); } Event.current.Use(); break; } } } break; } #endregion #region KeyUp case EventType.keyUp: { switch (Event.current.keyCode) { case KeyCode.Escape: { DeselectThisGrid(); Event.current.Use(); break; } case KeyCode.Space: { SwitchState(); Event.current.Use(); break; } default: break; } break; } default: break; } #endregion DrawBlockMarker(blockSize, noRotation); }
public static void Refresh() { _Grid = null; }
private void Awake() { instance = this; }
public void Start() { this.grid = new CubeGrid(this, this.computeShader); mesh = GetComponent <MeshFilter>().mesh; }
/// <summary> /// Returns true if this block can connect to another block (of the given type) in the given position. /// This is called only if CheckConnectionAllowed == true. /// If this method would return true for any position, set CheckConnectionAllowed to false to avoid /// unnecessary overhead. It is the block's responsibility to call CubeGrid.UpdateBlockNeighbors every time the /// conditions that are checked by this method change. /// </summary> public virtual bool ConnectionAllowed(ref Vector3I otherBlockPos, ref Vector3I faceNormal, MyCubeBlockDefinition def) { if (MyFakes.ENABLE_FRACTURE_COMPONENT && Components.Has <MyFractureComponentBase>()) { MyFractureComponentCubeBlock fractureComponent = GetFractureComponent(); if (fractureComponent == null || fractureComponent.MountPoints == null) { return(true); } var other = CubeGrid.GetCubeBlock(otherBlockPos); if (other == null) { return(true); } MyBlockOrientation or = other.Orientation; var position = Position; Debug.Assert(m_tmpMountPoints.Count == 0); m_tmpMountPoints.Clear(); if (other.FatBlock != null && other.FatBlock.Components.Has <MyFractureComponentBase>()) { MyFractureComponentCubeBlock otherFractureComponent = other.GetFractureComponent(); if (otherFractureComponent != null) { m_tmpMountPoints.AddRange(otherFractureComponent.MountPoints); } } else if (other.FatBlock is MyCompoundCubeBlock) { var lst = new List <MyCubeBlockDefinition.MountPoint>(); foreach (var b in (other.FatBlock as MyCompoundCubeBlock).GetBlocks()) { MyFractureComponentCubeBlock blockInCompoundFractureComponent = b.GetFractureComponent(); if (blockInCompoundFractureComponent != null) { m_tmpMountPoints.AddRange(blockInCompoundFractureComponent.MountPoints); } else { var mountPoints = b.BlockDefinition.GetBuildProgressModelMountPoints(b.BuildLevelRatio); lst.Clear(); MyCubeGrid.TransformMountPoints(lst, b.BlockDefinition, mountPoints, ref b.Orientation); m_tmpMountPoints.AddRange(lst); } } } else { var mountPoints = def.GetBuildProgressModelMountPoints(other.BuildLevelRatio); MyCubeGrid.TransformMountPoints(m_tmpMountPoints, def, mountPoints, ref or); } bool result = MyCubeGrid.CheckMountPointsForSide(fractureComponent.MountPoints, ref SlimBlock.Orientation, ref position, BlockDefinition.Id, ref faceNormal, m_tmpMountPoints, ref or, ref otherBlockPos, def.Id); m_tmpMountPoints.Clear(); return(result); } return(true); }
public void Start() { this.grid = new CubeGrid(this, this.computeShader); }
public BuildCheckResult CanBuild(MySlimBlock projectedBlock, bool checkHavokIntersections) { MyBlockOrientation blockOrientation = projectedBlock.Orientation; Matrix local; blockOrientation.GetMatrix(out local); var gridOrientation = (m_clipboard as MyGridClipboard).GetFirstGridOrientationMatrix(); if (gridOrientation != Matrix.Identity) { var afterRotation = Matrix.Multiply(local, gridOrientation); blockOrientation = new MyBlockOrientation(ref afterRotation); } Quaternion blockOrientationQuat; blockOrientation.GetQuaternion(out blockOrientationQuat); Quaternion projQuat = Quaternion.Identity; Orientation.GetQuaternion(out projQuat); blockOrientationQuat = Quaternion.Multiply(projQuat, blockOrientationQuat); Vector3I projectedMin = CubeGrid.WorldToGridInteger(projectedBlock.CubeGrid.GridIntegerToWorld(projectedBlock.Min)); Vector3I projectedMax = CubeGrid.WorldToGridInteger(projectedBlock.CubeGrid.GridIntegerToWorld(projectedBlock.Max)); Vector3I blockPos = CubeGrid.WorldToGridInteger(projectedBlock.CubeGrid.GridIntegerToWorld(projectedBlock.Position)); Vector3I min = new Vector3I(Math.Min(projectedMin.X, projectedMax.X), Math.Min(projectedMin.Y, projectedMax.Y), Math.Min(projectedMin.Z, projectedMax.Z)); Vector3I max = new Vector3I(Math.Max(projectedMin.X, projectedMax.X), Math.Max(projectedMin.Y, projectedMax.Y), Math.Max(projectedMin.Z, projectedMax.Z)); projectedMin = min; projectedMax = max; if (!CubeGrid.CanAddCubes(projectedMin, projectedMax)) { return(BuildCheckResult.IntersectedWithGrid); } MyGridPlacementSettings settings = new MyGridPlacementSettings(); settings.Mode = MyGridPlacementSettings.SnapMode.OneFreeAxis; var mountPoints = projectedBlock.BlockDefinition.GetBuildProgressModelMountPoints(1.0f); bool isConnected = MyCubeGrid.CheckConnectivity(this.CubeGrid, projectedBlock.BlockDefinition, mountPoints, ref blockOrientationQuat, ref blockPos); if (isConnected) { if (CubeGrid.GetCubeBlock(blockPos) == null) { if (checkHavokIntersections) { if (MyCubeGrid.TestPlacementAreaCube(CubeGrid, ref settings, projectedMin, projectedMax, blockOrientation, projectedBlock.BlockDefinition, CubeGrid)) { return(BuildCheckResult.OK); } else { return(BuildCheckResult.IntersectedWithSomethingElse); } } else { return(BuildCheckResult.OK); } } else { return(BuildCheckResult.AlreadyBuilt); } } else { return(BuildCheckResult.NotConnected); } }
public void SetGrid(CubeGrid a_cubeGrid) { m_cubeGrid = a_cubeGrid; }
private void UpdateProjection() { if (m_instantBuildingEnabled) { if (ProjectedGrid != null) { foreach (var projectedBlock in ProjectedGrid.CubeBlocks) { ShowCube(projectedBlock, true); } m_clipboard.HasPreviewBBox = true; } } else { m_hiddenBlock = null; if (m_clipboard.PreviewGrids.Count == 0) { return; } m_remainingBlocks = ProjectedGrid.CubeBlocks.Count; ProjectedGrid.Render.Transparency = 0f; m_buildableBlocksCount = 0; m_visibleBlocks.Clear(); m_buildableBlocks.Clear(); m_hiddenBlocks.Clear(); ProfilerShort.Begin("Update cube visibility"); foreach (var projectedBlock in ProjectedGrid.CubeBlocks) { Vector3 worldPosition = ProjectedGrid.GridIntegerToWorld(projectedBlock.Position); Vector3I realPosition = CubeGrid.WorldToGridInteger(worldPosition); var realBlock = CubeGrid.GetCubeBlock(realPosition); if (realBlock != null && projectedBlock.BlockDefinition.Id == realBlock.BlockDefinition.Id) { m_hiddenBlocks.Add(projectedBlock); m_remainingBlocks--; } else { bool canBuild = CanBuild(projectedBlock); if (canBuild) { m_buildableBlocks.Add(projectedBlock); m_buildableBlocksCount++; } else { if (m_showOnlyBuildable) { m_hiddenBlocks.Add(projectedBlock); } else { m_visibleBlocks.Add(projectedBlock); } } } } foreach (var block in m_visibleBlocks) { ShowCube(block, false); } foreach (var block in m_buildableBlocks) { ShowCube(block, true); } foreach (var block in m_hiddenBlocks) { HideCube(block); } ProfilerShort.End(); if (m_remainingBlocks == 0 && !m_keepProjection) { RemoveProjection(m_keepProjection); } else { UpdateEmissivity(); } m_statsDirty = true; if (m_shouldUpdateTexts) { UpdateText(); m_shouldUpdateTexts = false; } m_clipboard.HasPreviewBBox = false; } }
protected virtual void RemovePilotFromSeat(MyCharacter pilot) { CubeGrid.SetInventoryMassDirty(); }
void Start() { motherGrid = CubeGrid.instance; }
void Awake() { _grid = GlobalOptions.Grid; motor = GetComponent <BoxMotor>(); }
void Start() { _grid = GlobalOptions.Grid; _library = _grid.m_CubeLibrary; _gridSize = _grid.gridSize; }
void Inventory_ContentsChanged(MyInventoryBase obj) { CubeGrid.SetInventoryMassDirty(); }
public void Initialize(Vector3[] a_endPoint, Vector2Int a_destinationCoord, string a_colorKey, float a_sphereSpeed, CubeGrid a_cubeGrid, Turret a_turret) { m_positions = a_endPoint; m_endPoint = m_positions[0]; m_colorKey = a_colorKey; m_destinationCoord = a_destinationCoord; m_sphereSpeed = a_sphereSpeed; m_cubeGrid = a_cubeGrid; m_turret = a_turret; m_startPoint = transform.position; GetComponent <Renderer>().material.color = m_cubeGrid.GetSphereColorByKey(a_colorKey); m_posIndex = 0; }
private void InitSubparts() { if (!CubeGrid.CreatePhysics) { return; } m_subparts.Clear(); m_subpartIDs.Clear(); m_currentOpening.Clear(); m_currentSpeed.Clear(); m_emitter.Clear(); m_hingePosition.Clear(); m_openingSequence.Clear(); for (int i = 0; i < ((MyAdvancedDoorDefinition)BlockDefinition).Subparts.Length; i++) { MyEntitySubpart foundPart = LoadSubpartFromName(((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].Name); if (foundPart != null) { m_subparts.Add(foundPart); // save the Subparts hinge (pivot) // if not defined... if (((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].PivotPosition == null) { // ...try to get pivot from Model... VRage.Import.MyModelBone bone = foundPart.Model.Bones.First(b => !b.Name.Contains("Root")); if (bone != null) { m_hingePosition.Add(bone.Transform.Translation); } } else // ...otherwise get from definition { m_hingePosition.Add((Vector3)((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].PivotPosition); } } } // get the sequence count from definition int openSequenzCount = ((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence.Length; for (int i = 0; i < openSequenzCount; i++) { if (!String.IsNullOrEmpty(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].IDs)) { // if one sequence should be applied for multiple subparts (i.e. <IDs>1-3,4,6,8,9</IDs> // add copies to m_openingSequence List // split by comma string[] tmp1 = ((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].IDs.Split(','); for (int j = 0; j < tmp1.Length; j++) { // split by minus string[] tmp2 = tmp1[j].Split('-'); if (tmp2.Length == 2) { for (int k = Convert.ToInt32(tmp2[0]); k <= Convert.ToInt32(tmp2[1]); k++) { m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]); m_subpartIDs.Add(k); } } else { m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]); m_subpartIDs.Add(Convert.ToInt32(tmp1[j])); } } } else { m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]); m_subpartIDs.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].ID); } } for (int i = 0; i < m_openingSequence.Count; i++) { m_currentOpening.Add(0f); m_currentSpeed.Add(0f); m_emitter.Add(new MyEntity3DSoundEmitter(this, true)); // make sure maxOpen is always positive and invert accordingly if (m_openingSequence[i].MaxOpen < 0f) { m_openingSequence[i].MaxOpen *= -1; m_openingSequence[i].InvertRotation = !m_openingSequence[i].InvertRotation; } } m_sequenceCount = m_openingSequence.Count; m_subpartCount = m_subparts.Count; Array.Resize(ref transMat, m_subpartCount); Array.Resize(ref rotMat, m_subpartCount); UpdateDoorPosition(); if (CubeGrid.Projector != null) { //This is a projected grid, don't add collisions for subparts return; } foreach (MyEntitySubpart subpart in m_subparts) { subpart.Physics = null; if (subpart != null && subpart.Physics == null) { if ((subpart.ModelCollision.HavokCollisionShapes != null) && (subpart.ModelCollision.HavokCollisionShapes.Length > 0)) { List <HkShape> shapes = subpart.ModelCollision.HavokCollisionShapes.ToList(); var listShape = new HkListShape(shapes.GetInternalArray(), shapes.Count, HkReferencePolicy.None); subpart.Physics = new Engine.Physics.MyPhysicsBody(subpart, RigidBodyFlag.RBF_DOUBLED_KINEMATIC | RigidBodyFlag.RBF_KINEMATIC); subpart.Physics.IsPhantom = false; (subpart.Physics as MyPhysicsBody).CreateFromCollisionObject((HkShape)listShape, Vector3.Zero, WorldMatrix, null, MyPhysics.CollisionLayers.KinematicDoubledCollisionLayer); subpart.Physics.Enabled = true; listShape.Base.RemoveReference(); } } } CubeGrid.OnHavokSystemIDChanged -= CubeGrid_HavokSystemIDChanged; CubeGrid.OnHavokSystemIDChanged += CubeGrid_HavokSystemIDChanged; CubeGrid.OnPhysicsChanged -= CubeGrid_OnPhysicsChanged; CubeGrid.OnPhysicsChanged += CubeGrid_OnPhysicsChanged; if (CubeGrid.Physics != null) { UpdateHavokCollisionSystemID(CubeGrid.GetPhysicsBody().HavokCollisionSystemID); } }
/// <summary> /// A*寻路 /// </summary> private void AStarCount() { //将寻路起点放置到OpenList openList.Add(allCubes[(int)startPos.x, (int)startPos.y]); //循环运算 while (true) { //排序 openList.Sort(); //找到此次排序中,F值最小的格子 CubeGrid currentGrid = openList[0]; //如果当前格子是终点 if (currentGrid.GetGridType() == GridType.End) { //生成路径 PushCubePath(currentGrid); break; } //遍历周边的8个格子 for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { //除去当前中心格子 if (i == 0 && j == 0) { continue; } //计算新格子的坐标 int x = currentGrid.x + i; int z = currentGrid.z + j; //排除特殊情况 if (x < 0 || z < 0 || x >= allCubes.GetLength(0) || z >= allCubes.GetLength(1)) { continue; } //排除障碍 if (allCubes[x, z].GetGridType() == GridType.Obsticle) { continue; } //排除已经成为过发现者 if (closeList.Contains(allCubes[x, z])) { continue; } //声明一个G int g = 0; if (i == 0 || j == 0) { g = currentGrid.G + 10; } else { g = currentGrid.G + 14; } //如果该格子的G值从未计算过,则设置 //如果当前次的运算得到的结果G,比原本的G值要小,则更新 if (allCubes[x, z].G == 0 || g < allCubes[x, z].G) { allCubes[x, z].G = g; //更新发现者 allCubes[x, z].finder = currentGrid; } //计算横向的x步数 int hx = (int)endPos.x - x; //计算纵向的z步数 int hy = (int)endPos.y - z; //计算H值 allCubes[x, z].H = hx > 0 ? hx : -hx + hy > 0 ? hy : -hy; //计算F值 allCubes[x, z].F = allCubes[x, z].G + allCubes[x, z].H; //如果OpenList中不包含当前格子 if (!openList.Contains(allCubes[x, z])) { //放进去 openList.Add(allCubes[x, z]); } } } //将当前中心格子放置到CloseList closeList.Add(currentGrid); //从OpenList中移除 openList.Remove(currentGrid); if (openList.Count == 0) { Debug.Log("Can Not Find Path!!!"); break; } } }
public override void UpdateBeforeSimulation10() { base.UpdateBeforeSimulation10(); if (!CheckUnobstructed()) { if (SafeConstraint != null) { RemoveConstraintInBoth(); } return; } if (SafeConstraint != null) { bool staticOk = this.CubeGrid.IsStatic || !m_other.CubeGrid.IsStatic; if (!staticOk || !IsWorking || !m_other.IsWorking) { return; } Debug.Assert(!m_other.CubeGrid.MarkedForClose && !CubeGrid.MarkedForClose); var mergeBlockDefinition = this.BlockDefinition as MyMergeBlockDefinition; float maxStrength = mergeBlockDefinition != null ? mergeBlockDefinition.Strength : 0.1f; float dist = (float)(WorldMatrix.Translation - m_other.WorldMatrix.Translation).Length() - CubeGrid.GridSize; if (dist > CubeGrid.GridSize * 3) { RemoveConstraintInBoth(); return; } MergeData data = new MergeData(); CalculateMergeData(ref data); (m_constraint.ConstraintData as HkMalleableConstraintData).Strength = data.ConstraintStrength; if (data.PositionOk && data.AxisOk && data.RotationOk) { if (m_frameCounter++ >= 3) { Vector3I gridOffset = CalculateOtherGridOffset(); Vector3I otherGridOffset = m_other.CalculateOtherGridOffset(); bool canMerge = this.CubeGrid.CanMergeCubes(m_other.CubeGrid, gridOffset); if (!canMerge) { if (this.CubeGrid.GridSystems.ControlSystem.IsLocallyControlled || m_other.CubeGrid.GridSystems.ControlSystem.IsLocallyControlled) { MyHud.Notifications.Add(MyNotificationSingletons.ObstructingBlockDuringMerge); } return; } var handle = BeforeMerge; if (handle != null) { BeforeMerge(); } if (Sync.IsServer) { foreach (var block in CubeGrid.GetBlocks()) { var mergeBlock = block.FatBlock as MyShipMergeBlock; if (mergeBlock != null && mergeBlock != this && mergeBlock.InConstraint) { (block.FatBlock as MyShipMergeBlock).RemoveConstraintInBoth(); } } MyCubeGrid mergedGrid = this.CubeGrid.MergeGrid_MergeBlock(m_other.CubeGrid, gridOffset); if (mergedGrid == null) { mergedGrid = m_other.CubeGrid.MergeGrid_MergeBlock(this.CubeGrid, otherGridOffset); } Debug.Assert(mergedGrid != null); RemoveConstraintInBoth(); } } } else { m_frameCounter = 0; } return; } foreach (var other in m_gridList) { if (other.MarkedForClose) { continue; } Vector3I pos = Vector3I.Zero; double dist = double.MaxValue; LineD l = new LineD(Physics.ClusterToWorld(Physics.RigidBody.Position), Physics.ClusterToWorld(Physics.RigidBody.Position) + GetMergeNormalWorld()); if (other.GetLineIntersectionExactGrid(ref l, ref pos, ref dist)) { var block = other.GetCubeBlock(pos).FatBlock as MyShipMergeBlock; if (block == null) { continue; } if (block.InConstraint || !block.IsWorking || !block.CheckUnobstructed() || block.GetMergeNormalWorld().Dot(GetMergeNormalWorld()) > 0.0f) { return; } if (!block.FriendlyWithBlock(this)) { return; } CreateConstraint(other, block); NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; m_updateBeforeFlags |= UpdateBeforeFlags.EnableConstraint; break; } } }
void Awake() { Grid = GlobalOptions.Grid; animator = GetComponent <Animator>(); animatorPose = GameObject.Find("PlayerModel_imporded").GetComponent <Animator>(); }