Example #1
0
 public void DiagonalDistanceToIfYDistanceIsSmalerThenXDistanceTest()
 {
     BuildingBlock pointOne = new BuildingBlock(1, 2);
     BuildingBlock pointTwo = new BuildingBlock(1, 1);
     var distance = pointOne.DiagonalDistanceTo(pointTwo);
     Assert.AreEqual(1, distance);
 }
Example #2
0
 public void DiagonalDistanceToIfXDistanceIsSmalerThenYDistanceTest()
 {
     BuildingBlock pointOne = new BuildingBlock(0, 0);
     BuildingBlock pointTwo = new BuildingBlock(2, 1);
     var distance = pointOne.DiagonalDistanceTo(pointTwo);
     Assert.AreEqual(1 + Math.Sqrt(2), distance);
 }
Example #3
0
 public void DiagonalDistanceHalfOfIntMax()
 {
     BuildingBlock pointOne = new BuildingBlock(Int32.MaxValue / 2, Int32.MaxValue / 2);
     BuildingBlock pointTwo = new BuildingBlock(0, 0);
     var distance = pointOne.DiagonalDistanceTo(pointTwo);
     Assert.AreEqual((Int32.MaxValue / 2) * Math.Sqrt(2), distance);
 }
Example #4
0
 public void DiagonalDistanceToIfYDistanceIsEqualToXDistanceTest()
 {
     BuildingBlock pointOne = new BuildingBlock(10, 10);
     BuildingBlock pointTwo = new BuildingBlock(0, 0);
     var distance = pointOne.DiagonalDistanceTo(pointTwo);
     Assert.AreEqual(10 * Math.Sqrt(2), distance);
 }
Example #5
0
 public Area(string name, IAreaConnector input)
     : base(new List<BuildingBlock>())
 {
     _name = name;
     _boundBuildingBlock = null;
     _inputs = new List<IAreaConnector>() {input};
 }
Example #6
0
        public PuzzleOutput areaGeneratePuzzle(BuildingBlock buildingBlockToBind)
        {
            if (_verbose) Debug.Log("spawning Area: " + _name);
            if (_boundBuildingBlock != null) {
                if (_verbose) Debug.Log("Area already bound to another building block!");
                return new PuzzleOutput();
            }
            else {
                BuildingBlock.shuffle(_inputs);
                foreach (IAreaConnector input in _inputs) {

                    PuzzleOutput possibleInput = input.areaGeneratePuzzle(this);
                    if (possibleInput == null)
                        continue;
                    _input = input;
                    _boundBuildingBlock = buildingBlockToBind;
                    PuzzleOutput 	result = new PuzzleOutput();
                    result.Items.AddRange(possibleInput.Items);
                    result.Relationships.AddRange(possibleInput.Relationships);

                    // Add an area connection relationship here
                    AreaConnectionRelationship connectionRelationship = input.makeConnection(this);
                    result.Relationships.Add(connectionRelationship);

                    return result;
                }
                return null;

            }
        }
Example #7
0
 public Area(string name, List<IAreaConnector> inputs)
     : base(new List<BuildingBlock>())
 {
     _name = name;
     _boundBuildingBlock = null;
     _inputs = inputs;
 }
Example #8
0
File: Person.cs Project: pprintz/p2
        internal Person(int id, double movementSpeed, BuildingBlock position)
        {
            if (id <= 0)
            { /* Negative or zero-valued id means this is a totally new person */
                int newID;
                do
                {
                    newID = _idCounter++;
                } while (IdsInUse.Contains(newID));
                ID = newID;
            }
            else
            {
                /* non-zeroed, positive value means this is an existing person */
                if (IdsInUse.Contains(id))
                    throw new PersonException($"A user with ID {id} already exists!");
                ID = id;
            }

            PersonInteractionStats = new DataSimulationStatistics();
            // 3 - 8 kmt
            MovementSpeed = movementSpeed < 3 ? 3 + Rand.NextDouble() * 5 : movementSpeed; // Less than 5 means that it was not created.
            MovementSpeed = 3 + Rand.NextDouble() * 5;
            MovementSpeedInMetersPerSecond = (MovementSpeed * 1000) / 60 / 60;
            Position = position;
            //If their position is int16.maxvalue, if the priority is not assigned == That there is no path,
            //They will not be touched in the simulation, but will be added to the counter in CP_SimulationStats
            if (position.Priority == Int16.MaxValue)
            {
                NoPathAvailable = true;
            }
            OriginalPosition = position;
        }
 public BuildingPartDestroyedEvent(BuildingBlock buildingBlock, HitInfo info)
 {
     BuildingPart = new BuildingPart(buildingBlock);
     Info = info;
     string bonename = StringPool.Get(info.HitBone);
     HitBone = bonename == "" ? "unknown" : bonename;
 }
Example #10
0
File: Tile.cs Project: pprintz/p2
 public double DiagonalDistanceTo(BuildingBlock point)
 {
     double xDistance = Math.Abs(X - point.X);
     double yDistance = Math.Abs(Y - point.Y);
     if (xDistance > yDistance)
         return Math.Sqrt(2) * yDistance + 1 * (xDistance - yDistance);
     return Math.Sqrt(2) * xDistance + 1 * (yDistance - xDistance);
 }
Example #11
0
 public BuildingEvent(Construction construction, Construction.Target target, BuildingBlock bb, bool bNeedsValidPlacement)
 {
     Builder = Server.GetPlayer(target.player);
     BuildingPart = new BuildingPart(bb);
     Construction = construction;
     Target = target;
     NeedsValidPlacement = bNeedsValidPlacement;
 }
        public BuildingPartGradeChangeEvent(BuildingBlock bb, BuildingGrade.Enum bgrade, BasePlayer player)
        {
            BuildingPart = new BuildingPart(bb);
            Builder = Server.GetPlayer(player);
            grade = bgrade;

            HasPrivilege = (bool)bb.CallMethod("CanChangeToGrade", bgrade, player);
        }
Example #13
0
 public void DiagonalDistanceHalfOfIntMin()
 {
     int min = (Int32.MinValue + 1) / 2;
     BuildingBlock pointOne = new BuildingBlock(min, min);
     BuildingBlock pointTwo = new BuildingBlock(0, 0);
     var distance = pointOne.DiagonalDistanceTo(pointTwo);
     Assert.AreEqual((Math.Abs(min) * Math.Sqrt(2)), distance);
 }
Example #14
0
        public PropertyChangePuzzle(BuildingBlock changerInput, BuildingBlock changeeInput, 
									string desiredPropertyName, object desiredPropertyVal)
            : base(new List<BuildingBlock>() { changerInput, changeeInput })
        {
            _changerInput = changerInput;
            _changeeInput = changeeInput;
            _desiredPropertyName = desiredPropertyName;
            _desiredPropertyVal = desiredPropertyVal;
        }
Example #15
0
 private void addBlockToList(BuildingBlock buildingBlock, DateTime dateTime)
 {
     KeyValuePair<BuildingBlock, DateTime> newKVP = new KeyValuePair<BuildingBlock, DateTime>(buildingBlock, dateTime);
     if (!this.upgradedBuildingBlocks.Exists(x => x.Key.Equals(newKVP.Key)))
     {
         this.upgradedBuildingBlocks.Add(newKVP);
         updateConfig();
     }
 }
Example #16
0
 public void areaDespawnItems(BuildingBlock possibleBind)
 {
     if (_verbose) Debug.Log(string.Format("Attempting to despawn items for area {0}", _name));
     if (possibleBind == _boundBuildingBlock) {
         if (_verbose) Debug.Log(string.Format("Successfully despawning items for area {0}", _name));
         _input.areaDespawnItems(this);
         _boundBuildingBlock = null;
     }
 }
Example #17
0
 private void DestroyConditionalModels(BuildingBlock parent)
 {
     if (conditionals != null)
     {
         for (int i = 0; i < conditionals.Count; i++)
         {
             parent.gameManager.Retire(conditionals[i]);
         }
         conditionals.Clear();
     }
 }
Example #18
0
        object OnStructureUpgrade(BuildingBlock block, BasePlayer player, BuildingGrade.Enum gradeEnum)
        {
            var grade = gradeEnum.ToString();

            if ((bool)Config[grade] || IsAllowed(player.UserIDString, $"{Title}.{grade}"))
            {
                return(null);
            }
            PrintToChat(player, Lang("NotAllowed", player.UserIDString, grade));
            return(true);
        }
Example #19
0
 public void PersonStart()
 {
     BuildingBlock block = new BuildingBlock(0,0);
     Person person = new Person(block);
     Assert.AreEqual(1,person.ID);
     Assert.AreEqual(false,person.Evacuated);
     Assert.AreEqual(new List<BuildingBlock>(), person.PathList);
     Tile tile = person.Position;
     Assert.AreEqual(0, tile.X);
     Assert.AreEqual(0, tile.Y);
 }
 void OnEntityBuilt(Planner planner, GameObject gameObject)
 {
     cachedBlock = gameObject.GetComponent<BuildingBlock>();
     if (cachedBlock == null) return;
     if (cachedBlock.blockDefinition == null) return;
     if (cachedBlock.blockDefinition.fullName != "build/block.halfheight") return;
     cachedBlock.GetComponentInChildren<MeshCollider>().gameObject.AddComponent<TriggerBase>();
     cachedBlock.GetComponentInChildren<TriggerBase>().gameObject.layer = triggerLayer;
     cachedBlock.GetComponentInChildren<TriggerBase>().interestLayers = playerMask;
     timer.Once(0.1f, () => ResetBlock(cachedBlock) );
 }
 void OnEntityEnter(TriggerBase triggerbase, BaseEntity entity)
 {
     if (!hasStarted) return;
     cachedBlock = triggerbase.GetComponentInParent<BuildingBlock>();
     if (cachedBlock == null) return;
     if (cachedBlock.blockDefinition.fullName != "build/block.halfheight") return;
     cachedPlayer = entity.GetComponent<BasePlayer>();
     if (cachedPlayer == null) return;
     cachedBlock.Kill(BaseNetworkable.DestroyMode.Gib);
     cachedPlayer.SendConsoleCommand("chat.add", new object[] { "0", string.Format("<color=orange>{0}:</color> {1}", "Warning", "You are not allowed to build blocks over you"), 1.0 });
 }
 /// <summary>
 /// Displays a layout definition.
 /// </summary>
 /// <param name="layout">The layout to be displayed.</param>
 private void DisplayDefinition(LayoutInformation layout)
 {
     this.logger.Log(TraceEventType.Information, "Exporting layout {0}", layout.Name);
     foreach (BuildingBlockName bbn in layout.BuildingBlockNames)
     {
         BuildingBlock bb = this.template.GetLayoutBuildingBlock(layout, bbn);
         this.logger.Log(TraceEventType.Information, "Exporting layout building block {0} hash {1} ID {2}", bb.Name, bb.GetHashCode(), bb.ID);
         this.document.InsertParagraph(bb.Name, Constants.WorkItemDefinitionStyleName);
         this.document.InsertBuildingBlock(bb, string.Format(CultureInfo.InvariantCulture, "_Temp_{0}", this.bookmarkSequence++));
     }
 }
Example #23
0
        public async Task <IActionResult> OnGetAsync(int id)
        {
            var block = await _context.BuildingBlocks.FindAsync(id);

            if (block == null)
            {
                return(BadRequest());
            }
            BuildingBlock = block;
            return(Page());
        }
Example #24
0
        /// <summary>
        /// Adds and places the currently selected building block, deactivating the hologram copy.
        /// </summary>
        public void AddCopy(BuildingBlock buildingBlock)
        {
            CancelPreviewCopy(); // The block still hasn't been placed yet, which means that we're technically still in preview mode.

            BuildingBlockCopy copy = buildingBlock.AddCopy();

            selectedBuildingBlockCopy = copy;
            placedBuildingBlockCopies.Add(copy);

            PlaceCopy();
        }
Example #25
0
 public ElevatorInfo(BuildingBlock block, string name, string waypoints)
 {
     rx                 = block.transform.rotation.x.ToString();
     ry                 = block.transform.rotation.y.ToString();
     rz                 = block.transform.rotation.z.ToString();
     rw                 = block.transform.rotation.w.ToString();
     Grade              = GradeToNum(block.grade).ToString();
     this.Name          = name;
     this.WaypointsName = waypoints;
     this.PrefabName    = block.blockDefinition.fullName;
 }
Example #26
0
        public void BuildingBlockForSpecificWorkItemTypeIsNotUsedForWorkItemsNotOfThatType()
        {
            WorkItemTreeNode  item = CreateWorkItemNode("SomeOtherWorkItemType", 0);
            LayoutInformation li   = this.SetupTestLayout(BuildingBlockName.Default, new BuildingBlockName(Wit));
            WorkItemLayout    sut  = this.CreateWorkItemLayout(li);

            // Act
            BuildingBlock ans = sut.ChooseBuildingBlock(item);

            // Assert
            Assert.AreEqual <BuildingBlockName>(BuildingBlockName.Default, new BuildingBlockName(ans), "The default building block was not used.");
        }
        void RefundMaterials(BuildingBlock block, BasePlayer player)
        {
            if (block.OwnerID != player.userID || player.inventory.containerMain.IsFull())
            {
                return;
            }

            foreach (var item in block.blockDefinition.grades[(int)block.grade].costToBuild)
            {
                player.GiveItem(ItemManager.CreateByItemID(item.itemid, (int)item.amount));
            }
        }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BuildingBlockName"/> class parsing the name of an existing <see cref="BuildingBlock"/>.
        /// </summary>
        /// <param name="buildingBlock">The building block to parse the name from.</param>
        public BuildingBlockName(BuildingBlock buildingBlock)
        {
            if (buildingBlock == null)
            {
                throw new ArgumentNullException("buildingBlock");
            }

            BuildingBlockName temp = BuildingBlockName.Parse(buildingBlock.Name);

            this.workItemType = temp.workItemType;
            this.level        = temp.level;
        }
Example #29
0
        public void BuildingBlockForSpecificWorkItemTypeAndLevelNotUsedForWorkItemsNotOnThatLevel()
        {
            WorkItemTreeNode  item = CreateWorkItemNode(Wit, 0);
            LayoutInformation li   = this.SetupTestLayout(BuildingBlockName.Default, new BuildingBlockName(Wit), new BuildingBlockName(Wit, 1));
            WorkItemLayout    sut  = this.CreateWorkItemLayout(li);

            // Act
            BuildingBlock ans = sut.ChooseBuildingBlock(item);

            // Assert
            Assert.AreEqual <BuildingBlockName>(new BuildingBlockName(Wit), new BuildingBlockName(ans));
        }
Example #30
0
 private void OnStructureUpgrade(BuildingBlock block, BasePlayer player, BuildingGrade.Enum grade)
 {
     if (block == null || player == null)
     {
         return;
     }
     if (!HasPerms(player.UserIDString, "hammertime.allowed"))
     {
         return;
     }
     NextTick(() => DoInvokes(block, false, block?.blockDefinition?.canRotate ?? true));
 }
Example #31
0
        [Test] //ExSkip
        public void CreateAndInsert()
        {
            // A document's glossary document stores building blocks.
            Document         doc         = new Document();
            GlossaryDocument glossaryDoc = new GlossaryDocument();

            doc.GlossaryDocument = glossaryDoc;

            // Create a building block, name it, and then add it to the glossary document.
            BuildingBlock block = new BuildingBlock(glossaryDoc)
            {
                Name = "Custom Block"
            };

            glossaryDoc.AppendChild(block);

            // All new building block GUIDs have the same zero value by default, and we can give them a new unique value.
            Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

            block.Guid = Guid.NewGuid();

            // The following attributes categorize building blocks
            // in the menu found via Insert -> Quick Parts -> Building Blocks Organizer in Microsoft Word.
            Assert.AreEqual("(Empty Category)", block.Category);
            Assert.AreEqual(BuildingBlockType.None, block.Type);
            Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
            Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

            // Before we can add this building block to our document, we will need to give it some contents.
            // We will do that and set a category, gallery, and behavior with a document visitor.
            BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);

            block.Accept(visitor);

            // We can access the block that we just made from the glossary document.
            BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
                                                                     "My custom building blocks", "Custom Block");

            // The block itself is a section that contains the text.
            Assert.AreEqual($"Text inside {customBlock.Name}\f", customBlock.FirstSection.Body.FirstParagraph.GetText());
            Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);
            Assert.DoesNotThrow(() => Guid.Parse(customBlock.Guid.ToString()));     //ExSkip
            Assert.AreEqual("My custom building blocks", customBlock.Category);     //ExSkip
            Assert.AreEqual(BuildingBlockType.None, customBlock.Type);              //ExSkip
            Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);  //ExSkip
            Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior); //ExSkip

            // Now, we can insert it into the document as a new section.
            doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

            // We can also find it in Microsoft Word's Building Blocks Organizer and place it manually.
            doc.Save(ArtifactsDir + "BuildingBlocks.CreateAndInsert.dotx");
        }
Example #32
0
        public void ChooseBuildingBlockLocatesWorkItemLevelSpecificBuildingBlockInPreferenceToLevelSpecificDefault()
        {
            WorkItemTreeNode  item = CreateWorkItemNode(Wit, 0);
            LayoutInformation li   = this.SetupTestLayout(BuildingBlockName.Default, new BuildingBlockName(0), new BuildingBlockName(Wit, 0));
            WorkItemLayout    sut  = this.CreateWorkItemLayout(li);

            // Act
            BuildingBlock ans = sut.ChooseBuildingBlock(item);

            // Assert
            Assert.AreEqual <BuildingBlockName>(new BuildingBlockName(Wit, 0), new BuildingBlockName(ans), "The work item level-specific building block was not used.");
        }
Example #33
0
        public void ChooseBuildingBlockLocatesDefaultBuildingBlockWithLevelIfOneExistsForThatLevel()
        {
            WorkItemTreeNode  item = CreateWorkItemNode(Wit, 0);
            LayoutInformation li   = this.SetupTestLayout(BuildingBlockName.Default, new BuildingBlockName(0));
            WorkItemLayout    sut  = this.CreateWorkItemLayout(li);

            // Act
            BuildingBlock ans = sut.ChooseBuildingBlock(item);

            // Assert
            Assert.AreEqual <BuildingBlockName>(new BuildingBlockName(0), new BuildingBlockName(ans), "The level-specific default building block was not used.");
        }
Example #34
0
        // Enqueues a stability update for the next tick
        private void EnqueueUpdate(BuildingBlock block)
        {
            ++currentStats.blocksEnqueued;
            if (!stabilityQueueDelayed.Contains(block))
            {
                ++currentStats.blocksEnqueuedUnique;
#if DEBUG
                Log("Enqueued " + BuildingBlockHelpers.Name(block));
#endif
                stabilityQueueDelayed.Add(block);
            }
        }
Example #35
0
        public void ChooseBuildingBlockLocatesDefaultBuildingBlockEvenIfNotTheFirstInALayout()
        {
            WorkItemTreeNode  item = CreateWorkItemNode(Wit, 0);
            LayoutInformation li   = this.SetupTestLayout(new BuildingBlockName("dummy"), BuildingBlockName.Default);
            WorkItemLayout    sut  = this.CreateWorkItemLayout(li);

            // Act
            BuildingBlock ans = sut.ChooseBuildingBlock(item);

            // Assert
            Assert.AreEqual <BuildingBlockName>(BuildingBlockName.Default, new BuildingBlockName(ans), "The default building block was not used.");
        }
Example #36
0
        public void BuildingBlockForSpecificWorkItemTypeAndLevelOverridesDefaultIfWorkItemTypeSpecificNotDefined()
        {
            WorkItemTreeNode  item = CreateWorkItemNode(Wit, 1);
            LayoutInformation li   = this.SetupTestLayout(BuildingBlockName.Default, new BuildingBlockName(Wit, 1));
            WorkItemLayout    sut  = this.CreateWorkItemLayout(li);

            // Act
            BuildingBlock ans = sut.ChooseBuildingBlock(item);

            // Assert
            Assert.AreEqual <BuildingBlockName>(new BuildingBlockName(Wit, 1), new BuildingBlockName(ans));
        }
Example #37
0
 public void PayForUpgrade(BuildingBlock buildingBlock, ConstructionGrade constructionGrade, BasePlayer player)
 {
     if (Interface.CallHook("OnPayForUpgrade", player, buildingBlock, constructionGrade) != null)
     {
         return;
     }
     foreach (var item in constructionGrade.costToBuild)
     {
         player.inventory.Take(collect, item.itemid, (int)item.amount);
         //player.Command("note.inv " + item.itemid + " " + item.amount * -1f);
     }
 }
        [Test] //ExSkip
        public void BuildingBlockFields()
        {
            Document doc = new Document();

            // BuildingBlocks are stored inside the glossary document
            // If you're making a document from scratch, the glossary document must also be manually created
            GlossaryDocument glossaryDoc = new GlossaryDocument();

            doc.GlossaryDocument = glossaryDoc;

            // Create a building block and name it
            BuildingBlock block = new BuildingBlock(glossaryDoc);

            block.Name = "Custom Block";

            // Put in in the document's glossary document
            glossaryDoc.AppendChild(block);
            Assert.AreEqual(1, glossaryDoc.Count);

            // All GUIDs are this value by default
            Assert.AreEqual("00000000-0000-0000-0000-000000000000", block.Guid.ToString());

            // In Microsoft Word, we can use these attributes to find blocks in Insert > Quick Parts > Building Blocks Organizer
            Assert.AreEqual("(Empty Category)", block.Category);
            Assert.AreEqual(BuildingBlockType.None, block.Type);
            Assert.AreEqual(BuildingBlockGallery.All, block.Gallery);
            Assert.AreEqual(BuildingBlockBehavior.Content, block.Behavior);

            // If we want to use our building block as an AutoText quick part, we need to give it some text and change some properties
            // All the necessary preparation will be done in a custom document visitor that we will accept
            BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);

            block.Accept(visitor);

            // We can find the block we made in the glossary document like this
            BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
                                                                     "My custom building blocks", "Custom Block");

            // Our block contains one section which now contains our text
            Assert.AreEqual($"Text inside {customBlock.Name}\f", customBlock.FirstSection.Body.FirstParagraph.GetText());
            Assert.AreEqual(customBlock.FirstSection, customBlock.LastSection);
            Assert.DoesNotThrow(() => Guid.Parse(customBlock.Guid.ToString()));     //ExSkip
            Assert.AreEqual("My custom building blocks", customBlock.Category);     //ExSkip
            Assert.AreEqual(BuildingBlockType.None, customBlock.Type);              //ExSkip
            Assert.AreEqual(BuildingBlockGallery.QuickParts, customBlock.Gallery);  //ExSkip
            Assert.AreEqual(BuildingBlockBehavior.Paragraph, customBlock.Behavior); //ExSkip

            // Then we can insert it into the document as a new section
            doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

            // Or we can find it in Microsoft Word's Building Blocks Organizer and place it manually
            doc.Save(ArtifactsDir + "BuildingBlocks.BuildingBlockFields.dotx");
        }
 private void RefundResources(BasePlayer player, BuildingBlock buildingBlock)
 {
     foreach (var item in buildingBlock.blockDefinition.grades[(int)buildingBlock.grade].costToBuild)
     {
         var newItem = ItemManager.CreateByItemID(item.itemid, (int)item.amount);
         if (newItem != null)
         {
             player.inventory.GiveItem(newItem);
             player.Command("note.inv", item.itemid, item.amount);
         }
     }
 }
 private void DestroyConditionalModels(BuildingBlock parent)
 {
     if (this.conditionals == null)
     {
         return;
     }
     for (int i = 0; i < this.conditionals.Count; i++)
     {
         parent.gameManager.Retire(this.conditionals[i]);
     }
     this.conditionals.Clear();
 }
Example #41
0
            // Gets adjacent supports and supported blocks
            public static void GetAdjacentBlocks(BuildingBlock self, out List <BuildingBlock> supports, out List <BuildingBlock> supported)
            {
                supports  = new List <BuildingBlock>();
                supported = new List <BuildingBlock>();
                if (!IsValidBlock(self))
                {
                    return;
                }
                List <StabilityPinPoint> pinPoints = GetPrefabPinPoints(self);

                // Find all blocks supporting this block
                foreach (var pinPoint in pinPoints)
                {
                    var        worldPosition = LocalToWorld(self, pinPoint.worldPosition);
                    Collider[] colliders     = Physics.OverlapSphere(worldPosition, 0.1f, constructionLayerMask);
                    foreach (var collider in colliders)
                    {
                        BuildingBlock other = collider.gameObject.ToBaseEntity() as BuildingBlock;
                        if (!IsValidBlock(other) || other.isDestroyed || other == self) // Bogus, already destroyed or self
                        {
                            continue;
                        }
                        if (IsSupportedBy(self, other))
                        {
                            supports.Add(other);
                        }
                    }
                }
                // Find all blocks supported by this block
                if (!IsSupportForAnything(self))
                {
                    return;
                }
                List <Socket_Base> sockets = GetPrefabSockets(self);

                foreach (var socket in sockets)
                {
                    var        worldPosition = LocalToWorld(self, socket.worldPosition);
                    Collider[] colliders     = Physics.OverlapSphere(worldPosition, 0.2f, constructionLayerMask);
                    foreach (var collider in colliders)
                    {
                        BuildingBlock other = collider.gameObject.ToBaseEntity() as BuildingBlock;
                        if (!IsValidBlock(other) || other.isDestroyed || other == self) // Bogus, already destroyed or self
                        {
                            continue;
                        }
                        if (IsSupportedBy(other, self))
                        {
                            supported.Add(other);
                        }
                    }
                }
            }
Example #42
0
    private void RPC_OpenDoor(BaseEntity.RPCMessage rpc)
    {
        if (!rpc.player.CanInteract())
        {
            return;
        }
        if (!this.canHandOpen)
        {
            return;
        }
        if (base.IsOpen())
        {
            return;
        }
        if (base.IsBusy())
        {
            return;
        }
        if (base.IsLocked())
        {
            return;
        }
        BaseLock slot = base.GetSlot(BaseEntity.Slot.Lock) as BaseLock;

        if (slot != null)
        {
            if (!slot.OnTryToOpen(rpc.player))
            {
                return;
            }
            if (slot.IsLocked() && UnityEngine.Time.realtimeSinceStartup - this.decayResetTimeLast > 60f)
            {
                BuildingBlock buildingBlock = base.FindLinkedEntity <BuildingBlock>();
                if (!buildingBlock)
                {
                    Decay.RadialDecayTouch(base.transform.position, 40f, 2097408);
                }
                else
                {
                    Decay.BuildingDecayTouch(buildingBlock);
                }
                this.decayResetTimeLast = UnityEngine.Time.realtimeSinceStartup;
            }
        }
        base.SetFlag(BaseEntity.Flags.Open, true, false, true);
        base.SendNetworkUpdateImmediate(false);
        if (this.isSecurityDoor && this.NavMeshLink != null)
        {
            this.SetNavMeshLinkEnabled(true);
        }
        Interface.CallHook("OnDoorOpened", this, rpc.player);
    }
Example #43
0
        public void Initialize(BuildingBlock buildingBlock, bool isPreview)
        {
            this.currentBuildingBlock = buildingBlock;
            this.isPreview            = isPreview;

            FollowConstructionBlock();

            btnRemoveCopy.gameObject.SetActive(!isPreview);

            btnRotateX.enabled = buildingBlock.RoundBuildingBlockTemplate.CanRotate;
            btnRotateY.enabled = buildingBlock.RoundBuildingBlockTemplate.CanRotate;
            btnRotateZ.enabled = buildingBlock.RoundBuildingBlockTemplate.CanRotate;
        }
Example #44
0
        private void GetBuildingblockOwner(BasePlayer player, BuildingBlock block)
        {
            object findownerblock = FindOwnerBlock(block);

            if (findownerblock is bool)
            {
                SendReply(player, noBlockOwnerfound);
                return;
            }
            ulong ownerid = (UInt64)findownerblock;

            SendBasePlayerFind(player, ownerid);
        }
Example #45
0
        private bool HasAccess(BasePlayer player, BuildingBlock buildingBlock)
        {
            bool flag;

            if (tempFriends.TryGetValue(buildingBlock.OwnerID, out flag))
            {
                return(flag);
            }
            var areFriends = AreFriends(buildingBlock.OwnerID, player.userID);

            tempFriends.Add(buildingBlock.OwnerID, areFriends);
            return(areFriends);
        }
Example #46
0
 void Start()
 {
     gameManager     = FindObjectOfType <GameManager>();
     WinningPosition = gameManager.topLeft.GetComponent <BuildingBlock>();
     for (int i = 0; i < WinningX; i++)
     {
         WinningPosition = WinningPosition.Borders[(int)Direction.East].GetComponent <BuildingBlock>();
     }
     for (int i = 0; i < WinningY; i++)
     {
         WinningPosition = WinningPosition.Borders[(int)Direction.South].GetComponent <BuildingBlock>();
     }
 }
Example #47
0
 // Tests if the block is a generally supported by the specified
 public static bool IsSupportedBy(BuildingBlock self, BuildingBlock by)
 {
     if (!IsValidBlock(self) || !IsValidBlock(by) || self.isDestroyed || by.isDestroyed)
     {
         return(false);
     }
     string[] supportFor;
     if (!supportMap.TryGetValue(self.blockDefinition.hierachyName, out supportFor))
     {
         return(false);
     }
     return(supportFor.Contains(by.blockDefinition.hierachyName));
 }
Example #48
0
 public void BuildingBlockStart()
 {
     BuildingBlock buildingBlock = new BuildingBlock(0, 0);
     Assert.AreEqual(0, buildingBlock.X);
     Assert.AreEqual(0, buildingBlock.Y);
     Assert.AreEqual(0, buildingBlock.HeatmapCounter);
     Assert.AreEqual(false, buildingBlock.IsChecked);
     Assert.AreEqual(double.MaxValue, buildingBlock.LengthFromSource);
     Assert.AreEqual(0, buildingBlock.LengthToDestination);
     Assert.AreEqual(null, buildingBlock.Parent);
     Assert.AreEqual(new HashSet<Tile>(), buildingBlock.Neighbours);
     Assert.AreEqual(Tile.Types.Free, buildingBlock.Type);
 }
        public void GetLayoutBuildingBlockReturnsTheBuildingBlockBelongingToTheLayoutIgnoringCase()
        {
            // Arrange
            BuildingBlock[] layout1Blocks = this.SetupWordTemplateWithCategoryAndBuildingBlocks(CategoryPrefix + "Layout1", BuildingBlockName.Default, new BuildingBlockName("lower"));
            this.sut.Load();
            LayoutInformation layout1 = this.sut.Layouts.First();

            // Act
            BuildingBlock ans1 = this.sut.GetLayoutBuildingBlock(layout1, new BuildingBlockName("LOWER"));

            // Assert
            Assert.AreSame(layout1Blocks[1], ans1, "Should get building block with differently cased name");
        }
        public void GetLayoutBuildingBlockReturnsNullIfBuildingBlockDoesNotExist()
        {
            // Arrange
            BuildingBlock[] layout1Blocks = this.SetupWordTemplateWithCategoryAndBuildingBlocks(CategoryPrefix + "Layout1", BuildingBlockName.Default);
            this.sut.Load();
            LayoutInformation layout = this.sut.Layouts.First();

            // Act
            BuildingBlock ans = this.sut.GetLayoutBuildingBlock(layout, new BuildingBlockName("Invalid"));

            // Assert
            Assert.IsNull(ans);
        }
Example #51
0
        int NextBlockGrade(BuildingBlock building_block, int offset = 1)
        {
            var current_grade = (int)building_block.grade;

            var grades = building_block.blockDefinition.grades;
            if (grades == null) return current_grade;

            var target_grade = current_grade + offset;
            while (target_grade >= 0 && target_grade < grades.Length)
            {
                if (grades[target_grade] != null) return target_grade;
                target_grade += offset;
            }

            return current_grade;
        }
 public CombineContainerPuzzle(BuildingBlock containerInput, BuildingBlock carryableInput, BuildingBlock nonCarryableInput)
     : base(new List<BuildingBlock>() { })
 {
     // Filter to generate a carryable container
     Dictionary<string, object> containerFilterProps = new Dictionary<string, object>();
     containerFilterProps["carryable"] = true;
     FilterBlock containerFilter = new FilterBlock(containerInput, containerFilterProps);
     // Filter to make sure the item in the container is not carryable
     Dictionary<string, object> carryableFilterProps = new Dictionary<string, object>();
     carryableFilterProps["carryable"] = false;
     FilterBlock carryableFilter = new FilterBlock(carryableInput, carryableFilterProps);
     // Filter to make sure the item not in the container is not carryable
     Dictionary<string, object> nonCarryableFilterProps = new Dictionary<string, object>();
     nonCarryableFilterProps["carryable"] = false;
     FilterBlock nonCarryableFilter = new FilterBlock(nonCarryableInput, nonCarryableFilterProps);
     InsertionPuzzle insertStep = new InsertionPuzzle(containerFilter, carryableFilter);
     _outputPuzzleMap = new CombinePuzzle(nonCarryableFilter, new UnboxingPuzzle(insertStep));
 }
Example #53
0
 public override PuzzleOutput generatePuzzle(string outputName, System.Collections.Generic.Dictionary<string, object> desiredOutputProperties)
 {
     if (_verbose) Debug.Log(string.Format("Generating OR Block"));
     if (Random.value >= 0.5f) {
      	// Try option 1 first
         if (_verbose) Debug.Log("TRYING OPTION 1");
         PuzzleOutput maybeOutput = _option1.generatePuzzle(outputName, desiredOutputProperties);
         if (maybeOutput != null) {
             _spawnedOption = _option1;
             return maybeOutput;
         }
         // Next try option 2
         if (_verbose) Debug.Log("TRYING OPTION 2");
         maybeOutput = _option2.generatePuzzle(outputName, desiredOutputProperties);
         if (maybeOutput != null) {
             _spawnedOption = _option2;
             return maybeOutput;
         }
         return null;
     }
     else {
         // Try option 2 first
         if (_verbose) Debug.Log("TRYING OPTION 2");
         PuzzleOutput maybeOutput = _option2.generatePuzzle(outputName, desiredOutputProperties);
         if (maybeOutput != null) {
             _spawnedOption = _option2;
             return maybeOutput;
         }
         // Next try option 1
         if (_verbose) Debug.Log("TRYING OPTION 1");
         maybeOutput = _option1.generatePuzzle(outputName, desiredOutputProperties);
         if (maybeOutput != null) {
             _spawnedOption = _option1;
             return maybeOutput;
         }
         return null;
     }
 }
Example #54
0
 static void DoRotation(BuildingBlock block, Quaternion defaultRotation)
 {
     if (block.blockDefinition == null) return;
     var transform = block.transform;
     if (defaultRotation == defaultQuaternion)
         transform.localRotation *= Quaternion.Euler(block.blockDefinition.rotationAmount);
     else
         transform.localRotation *= defaultRotation;
     block.ClientRPC(null, "UpdateConditionalModels", new object[0]);
     block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
 }
Example #55
0
 /////////////////////////////////////////////////////
 ///  SetHealth(BuildingBlock block)
 ///  Set max health for a block
 /////////////////////////////////////////////////////
 private static void SetHealth(BuildingBlock block)
 {
     block.health = block.MaxHealth();
     block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
 }
Example #56
0
 /////////////////////////////////////////////////////
 ///  SetGrade(BuildingBlock block, BuildingGrade.Enum level)
 ///  Change grade level of a block
 /////////////////////////////////////////////////////
 private static void SetGrade(BuildingBlock block, BuildingGrade.Enum level)
 {
     block.SetGrade(level);
     block.health = block.MaxHealth();
     block.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
 }
Example #57
0
 public ElevatorInfo(BuildingBlock block, string name, string waypoints)
 {
     rx = block.transform.rotation.x.ToString();
     ry = block.transform.rotation.y.ToString();
     rz = block.transform.rotation.z.ToString();
     rw = block.transform.rotation.w.ToString();
     Grade = GradeToNum(block.grade).ToString();
     this.Name = name;
     this.WaypointsName = waypoints;
     this.PrefabName = block.blockDefinition.fullName;
 }
Example #58
0
 public void SetInfo(ElevatorInfo info)
 {
     this.info = info;
     var cwaypoints = Interface.CallHook("GetWaypointsList", this.info.WaypointsName);
     if (cwaypoints == null)
     {
         Debug.Log(string.Format("{0} was destroyed, informations are invalid. Did you set waypoints? or a PrefabName?", info.Name));
         GameObject.Destroy(this);
         return;
     }
     this.waypoints = new List<WaypointInfo>();
     foreach (var cwaypoint in (List<object>)cwaypoints)
     {
         foreach (KeyValuePair<Vector3, float> pair in (Dictionary<Vector3,float>)cwaypoint)
         {
             this.waypoints.Add(new WaypointInfo(pair.Key, pair.Value));
         }
     }
     if (this.waypoints.Count < 2)
     {
         Debug.Log(string.Format("{0} waypoints were detected for {1}. Needs at least 2 waypoints. Destroying.", this.waypoints.Count.ToString(), info.Name));
         GameObject.Destroy(this);
         return;
     }
     this.rotation = new UnityEngine.Quaternion(Convert.ToSingle(info.rx), Convert.ToSingle(info.ry), Convert.ToSingle(info.rz), Convert.ToSingle(info.rw));
     this.block = CreateBuildingBlock(this.info.PrefabName, this.waypoints[0].GetPosition(), this.rotation, Convert.ToInt32(this.info.Grade));
     if(this.block == null)
     {
         Debug.Log(string.Format("Something went wrong, couldn't create the BuildingBlock for {0}", info.Name));
         GameObject.Destroy(this);
         return;
     }
     protectedBlock.Add(this.block.GetComponent<BaseCombatEntity>());
     trigger = block.GetComponentInChildren<MeshCollider>().gameObject.AddComponent<TriggerBase>();
     trigger.gameObject.name = "Elevator";
     var newlayermask = new UnityEngine.LayerMask();
     newlayermask.value = 133120;
     trigger.interestLayers = newlayermask;
     trigger.gameObject.layer = UnityEngine.LayerMask.NameToLayer("Trigger");
     spawnedElevators.Add(this);
 }
Example #59
0
        bool GetStructureClean(BuildingBlock initialBlock, float playerRot, BuildingBlock currentBlock, out Dictionary<string, object> data)
        {
            data = new Dictionary<string, object>();
            posCleanData = new Dictionary<string, object>();
            rotCleanData = new Dictionary<string, object>();

            normedPos = GenerateGoodPos(initialBlock.transform.position, currentBlock.transform.position, playerRot);
            normedYRot = currentBlock.transform.rotation.ToEulerAngles().y - playerRot;

            data.Add("prefabname", currentBlock.blockDefinition.fullName);
            data.Add("grade", currentBlock.grade);

            posCleanData.Add("x", normedPos.x);
            posCleanData.Add("y", normedPos.y);
            posCleanData.Add("z", normedPos.z);
            data.Add("pos", posCleanData);

            rotCleanData.Add("x", currentBlock.transform.rotation.ToEulerAngles().x);
            rotCleanData.Add("y", normedYRot);
            rotCleanData.Add("z", currentBlock.transform.rotation.ToEulerAngles().z);
            data.Add("rot", rotCleanData);
            return true;
        }
Example #60
0
        bool GetSpawnableClean(BuildingBlock initialBlock, float playerRot, Spawnable currentSpawn, out Dictionary<string, object> data)
        {
            data = new Dictionary<string, object>();
            posCleanData = new Dictionary<string, object>();
            rotCleanData = new Dictionary<string, object>();

            normedPos = GenerateGoodPos(initialBlock.transform.position, currentSpawn.transform.position, playerRot);
            normedYRot = currentSpawn.transform.rotation.ToEulerAngles().y - playerRot;
            data.Add("prefabname", currentSpawn.GetComponent<BaseNetworkable>().LookupPrefabName().ToString());

            posCleanData.Add("x", normedPos.x);
            posCleanData.Add("y", normedPos.y);
            posCleanData.Add("z", normedPos.z);
            data.Add("pos", posCleanData);

            rotCleanData.Add("x", currentSpawn.transform.rotation.ToEulerAngles().x);
            rotCleanData.Add("y", normedYRot);
            rotCleanData.Add("z", currentSpawn.transform.rotation.ToEulerAngles().z);
            data.Add("rot", rotCleanData);
            return true;
        }