Inheritance: MonoBehaviour
コード例 #1
0
 public static void ChangeToDoor(Wall a, Wall b)
 {
     //right and left mode to modify
     if (a.X == b.X)
     {
         if (a.Y < b.Y)
         {
             a.sides.Right = MultiWallScript.Mode.Half;
             b.sides.Left = MultiWallScript.Mode.Half;
         }
         else
         {
             a.sides.Left = MultiWallScript.Mode.Half;
             b.sides.Right = MultiWallScript.Mode.Half;
         }
     }
     //top and bottom mode to modify
     else if (a.Y == b.Y)
     {
         if (a.X < b.X)
         {
             a.sides.Bottom = MultiWallScript.Mode.Half;
             b.sides.Top = MultiWallScript.Mode.Half;
         }
         else
         {
             a.sides.Top = MultiWallScript.Mode.Half;
             b.sides.Bottom = MultiWallScript.Mode.Half;
         }
     }
     else
         throw new System.ArgumentException("Inproper coordinates of the walls");
 }
コード例 #2
0
ファイル: Wall.cs プロジェクト: LuciusSixPercent/Finsternis
    public void FadeOut(Wall notifier = null)
    {
        targetAlpha = fadeAlpha;
        waitFrames = 1;

        if (notifier)
            shouldFadeCompletely = canFadeCompletely && notifier.transform.position.z == transform.position.z;
        else if (canFadeCompletely)
            shouldFadeCompletely = true;

        if (shouldFadeCompletely)
        {
            foreach (Wall neighbour in neighbours)
            {
                if (notifier != neighbour)
                    neighbour.FadeOut(this);
            }
        }
        else if (notifier && (!lastNotifier || notifier.transform.position.x == transform.position.x))
        {
            m.SetVector("_FadePoint", notifier.transform.position + (transform.position - notifier.transform.position) / 2);
            Vector3 axis = (notifier.transform.position - transform.position);
            axis.x = Mathf.Abs(axis.x);
            axis.y = Mathf.Abs(axis.y);
            axis.z = Mathf.Abs(axis.z);
            m.SetVector("_FadeAxis", axis);
            lastNotifier = notifier;
        }
    }
コード例 #3
0
 public Labirynth(uint x, uint y, GenerationAlghorithm _algorithm)
 {
     chambersCountHorizontal = x;
     chambersCountVertical = y;
     walls = new Wall[chambersCountHorizontal, chambersCountVertical];
     algorithm = _algorithm;
 }
コード例 #4
0
 public MazyPrototypeFactory(Maze maze, Wall wall, Room room, Door door)
 {
     _maze = maze;
     _wall = wall;
     _room = room;
     _door = door;
 }
コード例 #5
0
ファイル: Door.cs プロジェクト: darkstrauss/Bonkers
    void Awake()
    {
        justTraveled = 0;
        gameObject.isStatic = true;
        gameObject.transform.localPosition = Vector3.zero;

        GetComponent<BoxCollider>().isTrigger = true;

        wall = transform.parent.GetComponent<Wall>();
        floor = transform.parent.transform.parent.gameObject;
        CBS = Camera.main.GetComponent<PlayerMovement>().CBS;
        playerInteraction = Camera.main.GetComponent<PlayerMovement>();
        
        if (tag == "down" || tag == "back")
        {
            wallSize = wall.xSize;
        }
        else
        {
            wallSize = wall.zSize;
        }

        xSize = 1;
        ySize = 3;
        gridX = wall.xSize;

        Generate();
    }
コード例 #6
0
ファイル: Tester.cs プロジェクト: sillsdev/libcom
    public static void Main(string[] args)
    {
        System.Console.WriteLine("Starting Tester.");

        System.Console.WriteLine("Writing Hello on wall.");
        Wall wall = new Wall();
        wall.writeBSTROnWall("Hello");
        System.Console.WriteLine("Writing Brrrrr! on wall.");
        wall.writeBSTROnWall("Brrrrr!");
        System.Console.WriteLine("Reading wall:");
        string wallContents = "overwrite me";
        wallContents = wall.readWallBSTR();
        System.Console.WriteLine("Wall says: " + wallContents);
        System.Console.WriteLine("Again, Wall says: '" + wall.readWallBSTR() + "'.");

        System.Console.WriteLine("\n\nDoing Bag-Ball test");
        //TODO What if I create it something like: IBag bag = (IBall) Factory.BagClass();  Eberhard might have said I was supposed to be doing this sort of thing that way.
        Bag bag = new Bag();
        Ball ball = (Ball) bag.ProvideBall(); // TODO what if I cast it as an IBall rather than Ball

        long distance_rolled;
        distance_rolled = ball.roll(2);
        System.Console.WriteLine("Rolling ball by 2. Accumulated distance: {0} (should say 2)", distance_rolled);
        if (distance_rolled != 2) {
            System.Console.WriteLine("Tester.exe: Error, distance wasn't correct. Exiting.");
            Environment.Exit(-1);
        }
        bag.InspectBall(ball);
        distance_rolled = ball.roll(9);
        System.Console.WriteLine("Rolling ball by 9. Accumulated distance: {0} (should say 14)", distance_rolled);
        if (distance_rolled != 14) {
            System.Console.WriteLine("Tester.exe: Error, distance wasn't correct. Exiting.");
            Environment.Exit(-1);
        }
    }
コード例 #7
0
ファイル: FindSouthFacingWalls.cs プロジェクト: AMEE/revit
        /// <summary>
        /// Obtains the outward direction of the exterior wall.
        /// </summary>
        /// <param name="wall">The wall.</param>
        /// <returns>A normalized XYZ direction vector.</returns>
        protected XYZ GetExteriorWallDirection(Wall wall)
        {
            LocationCurve locationCurve = wall.Location as LocationCurve;
            XYZ exteriorDirection = XYZ.BasisZ;

            if (locationCurve != null)
            {
                Curve curve = locationCurve.Curve;

                //Write("Wall line endpoints: ", curve);

                XYZ direction = XYZ.BasisX;
                if (curve is Line)
                {
                    // Obtains the tangent vector of the wall.
                    direction = curve.ComputeDerivatives(0, true).BasisX.Normalize();
                }
                else
                {
                    // An assumption, for non-linear walls, that the "tangent vector" is the direction
                    // from the start of the wall to the end.
                    direction = (curve.get_EndPoint(1) - curve.get_EndPoint(0)).Normalize();
                }
                // Calculate the normal vector via cross product.
                exteriorDirection = XYZ.BasisZ.CrossProduct(direction);

                // Flipped walls need to reverse the calculated direction
                if (wall.Flipped) exteriorDirection = -exteriorDirection;
            }

            return exteriorDirection;
        }
コード例 #8
0
ファイル: WallTests.cs プロジェクト: ajlopez/TddRocks
 public void AttackInitialWallTwice()
 {
     Wall wall = new Wall();
     wall.NewDay();
     Assert.IsTrue(wall.Attack(10, 12, 6));
     Assert.IsTrue(wall.Attack(10, 12, 6));
 }
コード例 #9
0
        public void read_from_file(string name, int count_walls)
        {
            StreamReader myStream = null;
            try
            {
                myStream = new StreamReader(name);
                using (myStream)
                {
                    Walls = null;
                    Walls = new List<Wall>();

                    Wall arg;
                    int i = 0;
                    while (i < count_walls)
                    {
                        myStream.BaseStream.ReadByte();
                        arg = new Wall(new Point(myStream.BaseStream.ReadByte(), myStream.BaseStream.ReadByte()), new Point(myStream.BaseStream.ReadByte(), myStream.BaseStream.ReadByte()));
                        if ((arg.Dot_1.X != 0 && arg.Dot_1.Y != 0) || (arg.Dot_2.X != 0 && arg.Dot_2.Y != 0))
                        {
                            Walls.Add(arg);
                            ++i;
                        }
                    }
                }
                myStream.Close();
            }
            catch (Exception)
            {
            }
        }
コード例 #10
0
ファイル: WallCatalogResource.cs プロジェクト: dd-dk/s3pi
 public WallCatalogResource(int APIversion,
     uint version,
     uint unknown2,
     Common common,
     Wall wallType,
     Partition partitionType,
     PartitionFlagsType partitionFlags,
     VerticalSpan verticalSpanType,
     PartitionsBlockedFlagsType partitionsBlockedFlags,
     PartitionsBlockedFlagsType adjacentPartitionsBlockedFlags,
     PartitionTool partitionToolMode,
     ToolUsageFlagsType toolUsageFlags,
     uint defaultPatternIndex,
     WallThickness wallThicknessType,
     TGIBlockList ltgib)
     : base(APIversion, version, common, ltgib)
 {
     this.unknown2 = unknown2;
     this.wallType = wallType;
     this.partitionType = partitionType;
     this.partitionFlags = partitionFlags;
     this.verticalSpanType = verticalSpanType;
     this.partitionsBlockedFlags = partitionsBlockedFlags;
     this.adjacentPartitionsBlockedFlags = adjacentPartitionsBlockedFlags;
     this.partitionToolMode = partitionToolMode;
     this.toolUsageFlags = toolUsageFlags;
     this.defaultPatternIndex = defaultPatternIndex;
     this.wallThicknessType = wallThicknessType;
 }
コード例 #11
0
 public MazePrototypeFactory(Maze maze, Room room, Door door, Wall wall)
 {
     this.prototypeMaze = maze;
     this.prototypeRoom = room;
     this.prototypeDoor = door;
     this.prototypeWall = wall;
 }
コード例 #12
0
ファイル: WallTests.cs プロジェクト: ajlopez/TddRocks
 public void AttackInitialWallTwoDaysDifferentPlaces()
 {
     Wall wall = new Wall();
     wall.NewDay();
     Assert.IsTrue(wall.Attack(10, 12, 6));
     wall.NewDay();
     Assert.IsTrue(wall.Attack(11, 13, 6));
 }
コード例 #13
0
ファイル: ProfileWall.cs プロジェクト: AMEE/revit
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="wall">wall to create reinforcement on</param>
 /// <param name="commandData">object which contains reference to Revit Application</param>
 public ProfileWall(Wall wall, ExternalCommandData commandData)
     : base(commandData)
 {
     m_data = wall;
     List<List<Edge>> faces = GetFaces(m_data);
     m_points = GetNeedPoints(faces);
     m_to2DMatrix = GetTo2DMatrix();
 }
コード例 #14
0
 public bool IsNextTo(Wall otherWall)
 {
     int diffX = this.X - otherWall.X;
     int diffY = this.Y - otherWall.Y;
     if (diffX == 0 || diffY == 0)
         return (System.Math.Abs(diffX + diffY) == 1);
     return false;
 }
コード例 #15
0
ファイル: Form1.cs プロジェクト: yuxiang2025/CI
 //丟入牆壁起末點
 public void Add_New_Wall(PointF p1, PointF p2)
 {
     Wall new_wall = new Wall();
     new_wall.start.X = p1.X;
     new_wall.start.Y = p1.Y;
     new_wall.end.X = p2.X;
     new_wall.end.Y = p2.Y;
     Mywall.Add(new_wall);
 }
コード例 #16
0
ファイル: SceneTest.cs プロジェクト: Dahrkael/TopDown-Racer
 protected override void Initialize()
 {
     Map = new Map();
     Camera = new Camera2D(Vector2.Zero, Map.Width - 800, Map.Height - 600);
     Car = new Car(new Vector2(XNAGame.I.Width / 2 + 50, XNAGame.I.Height / 2 + 50));
     Wall = new Wall(new Vector2(XNAGame.I.Width / 2 + 50, XNAGame.I.Height / 2 + 500), 100, 16);
     info = new Text("", "Speed: 0 - Angle: 0", new Vector2(0, 20));
     Music = new Music("track");
     Music.Play(true);
 }
コード例 #17
0
ファイル: WallTests.cs プロジェクト: ajlopez/TddRocks
        public void AttackInitialThousandDays()
        {
            Wall wall = new Wall();

            for (int k = 0; k < 1000; k++)
            {
                wall.NewDay();
                Assert.IsTrue(wall.Attack(k, k + 100, 6));
            }
        }
コード例 #18
0
ファイル: Wall.cs プロジェクト: PeteJBB/SupremeViolence
 public static bool IsThereAWallAt(int x, int y, Wall[] walls = null)
 {
     if (walls == null)
     {
         // this is dangerous...
         walls = GameObject.FindObjectsOfType<Wall>();
     }
     var match = walls.FirstOrDefault(w => Mathf.RoundToInt(w.transform.position.x) == x && Mathf.RoundToInt(w.transform.position.y) == y);
     return match != null;
 }
コード例 #19
0
ファイル: Blueprint.cs プロジェクト: Railec/SE1cKBS2
        /**
         * This method returns a copy of the blueprint.
         * This is a Deep Copy, meaning that all the Rooms, Corners in those rooms and Walls connected to those corners will be copied.
         * The purpose of this is to make a new copy to work in when editing a blueprint, while preserving the original.
         */
        public Blueprint Clone()
        {
            Blueprint newBp = new Blueprint(this.Name);

            List<Wall> newWalls = new List<Wall>();
            List<Corner> newCorners = new List<Corner>();

            foreach(Room room in this.Rooms) {
                Room newRoom = new Room(room.Name, room.GetID(), room.GetFloorID(), room.FunctionID);
                newBp.Rooms.Add(newRoom);

                foreach(Corner corner in room.GetCorners()) {
                    Corner newCorner = newCorners.Find( (c) => (c.GetID() == corner.GetID()) );
                    if(newCorner != null) {
                        newRoom.AddCorner(newCorner);
                        continue;
                    }

                    newCorner = new Corner(corner.GetID(), corner.GetPoint());
                    newRoom.AddCorner(newCorner);
                    newCorners.Add(newCorner);

                    foreach(Wall wall in corner.GetWalls()) {
                        Wall newWall = newWalls.Find( (w) => (w.GetID() == wall.GetID()) );
                        if(newWall != null) {
                            if(newWall.Left.GetID() == corner.GetID()) {
                                newWall.Left = newCorner;
                            } else if(newWall.Right.GetID() == corner.GetID()) {
                                newWall.Right = newCorner;
                            }
                            if(newWall.GetType() == typeof(Door)) {
                                ((Door)newWall).Hinge = (((Door)newWall).Hinge.Equals(newWall.Left) ? newWall.Left : newWall.Right);
                            }
                            newCorner.AddWall(newWall);
                            continue;
                        }

                        Corner left = (wall.Left.Equals(newCorner) ? newCorner : wall.Left);
                        Corner right = (wall.Right.Equals(newCorner) ? newCorner : wall.Right);

                        if(wall.GetType() == typeof(Door)) {
                            newWall = new Door(wall.GetID(), left, right, (((Door)wall).Hinge.GetID() == left.GetID() ? left : right), ((Door)wall).Direction);
                        } else {
                            newWall = new Wall(wall.GetID(), left, right);
                        }

                        newWalls.Add(newWall);
                        newCorner.AddWall(newWall);
                    }
                }
                newRoom.IsChanged = room.IsChanged;
            }

            return newBp;
        }
コード例 #20
0
ファイル: Ball.cs プロジェクト: dajuanrobins/MazeGameDemo
 public override void CollideWith(Wall wall)
 {
     if (horizontalDirection == HorizontalDirection.LEFT)
         UpdatePosition(wall.Rectangle.Right, Y_Coordinate);
     else if (horizontalDirection == HorizontalDirection.RIGHT)
         UpdatePosition(wall.Rectangle.Left - Width, Y_Coordinate);
     else if (verticalDirection == VerticalDirection.UP)
         UpdatePosition(X_Coordinate, wall.Rectangle.Bottom);
     else if (verticalDirection == VerticalDirection.DOWN)
         UpdatePosition(X_Coordinate, wall.Rectangle.Top - Height);
 }
コード例 #21
0
ファイル: Map.cs プロジェクト: jtuttle/haven
    public Map(int size)
    {
        // make map size odd so that we can have a center square
        if(size % 2 != 0)
            size = size + 1;

        Width = size;
        Height = size;

        Wall = new Wall(5);
    }
コード例 #22
0
ファイル: Field.cs プロジェクト: T3H40/Worldofwartanks
 public void removeWallFromList(Wall w)
 {
     for(int i=0; i<this.walls.Count; i++)
     {
         if(this.walls[i].Equals(w))
         {
             this.walls.Remove(w);
             break;
         }
     }
 }
コード例 #23
0
ファイル: Wall.cs プロジェクト: LuciusSixPercent/Finsternis
 void FixedUpdate()
 {
     if (waitFrames < 0)
     {
         notifier = null;
         lastNotifier = null;
         targetAlpha = 1;
     }
     else
     {
         waitFrames--;
     }
 }
コード例 #24
0
ファイル: Entity.cs プロジェクト: Blkx-Darkreaper/Workspace
        public Entity(Point center, Size dimensions, Color lineColour, int lineThickness)
        {
            this.center = center;
            this.dimensions = dimensions;
            this.lineColour = lineColour;
            this.lineThickness = lineThickness;

            allWalls = new Wall[4];
            for (int i = 0; i < 4; i++)
            {
                InitWall(i, i);
            }
        }
コード例 #25
0
ファイル: TileVisualizer.cs プロジェクト: ubiquitous42/robots
    public void SetVisualizationForWall(Wall wall)
    {
        if (null != wall.visualization) {
            Debug.Log("Wall already has a visualization!", wall);
            return;
        }

        GameObject newVis = (GameObject)GameObject.Instantiate(wallVisualizationPrefabs[(int)wall.wallType]);
        newVis.transform.parent = wall.transform;
        newVis.transform.localPosition = Vector3.zero;
        newVis.transform.localRotation = Quaternion.identity;
        newVis.transform.localScale = Vector3.one;
        wall.visualization = newVis;
    }
コード例 #26
0
ファイル: BoardManager.cs プロジェクト: lalibelamonk/herman
	private float newYPosition(Wall lastWall){
		float nextPos = Random.Range (0, .5f) + lastWall.transform.position.y;
		float sign = Random.Range (0, 1);
		if (sign < .5) {
			nextPos = nextPos * -1f;
		}
		if (nextPos > upperLimit){
			return upperLimit;
		} else if (nextPos < lowerLimit) {
			return lowerLimit;
		} else {
			return nextPos;
		}
		
	}
コード例 #27
0
ファイル: WallTests.cs プロジェクト: Railec/SE1cKBS2
        public void Constructor()
        {
            //Arrange

            //Act
            Corner left = new Corner(1, new PointF(0, 0));
            Corner right = new Corner(2, new PointF(10, 0));
            Wall wall = new Wall(1, left, right);

            //Assert
            Assert.IsNotNull(wall);
            Assert.IsInstanceOf(typeof(Wall), wall);
            Assert.AreEqual(1, wall.GetID());
            Assert.AreEqual(left, wall.Left);
            Assert.AreEqual(right, wall.Right);
        }
コード例 #28
0
ファイル: clsVectors.cs プロジェクト: WeConnect/case-apps
        /// <summary>
        ///   Initializes a new instance of the <see cref="clsVectors" /> class.
        /// </summary>
        /// <param name="refElement">The reference element.</param>
        /// <param name="wall">The wall.</param>
        /// <exception cref="Exception">No Locations were found.</exception>
        public clsVectors(
      Element refElement,
      Wall wall)
        {
            _Wall = wall;
              _Ref = refElement;

              if (_WallLocation == null || _RefLocation == null)
              {
            throw new Exception("No Locations were found.");
              }

              GetOriginalAngles();
              GetDeltaAngle();
              CreateRotationAxis();
        }
コード例 #29
0
ファイル: game.cs プロジェクト: Balzhan/snake
        public static void Init()
        {
            isActive = true;
            snake = new Snake();
            food = new Food();
            wall = new Wall();

            snake.body.Add(new Point { x = 5, y = 10 }); //initial point of the head of the snake
            food.body.Add(new Point { x = 8, y = 15 });// The 1st position of the food
            //colors of the items
            food.color = ConsoleColor.Green;
            wall.color = ConsoleColor.White;
            snake.color = ConsoleColor.Yellow;

            Console.SetWindowSize(24, 32);

        }
コード例 #30
0
ファイル: CornerTest.cs プロジェクト: Railec/SE1cKBS2
        public void MixedAddWalls()
        {
            //Arrange
            Corner corn1 = new Corner(new PointF(0, 0));
            Corner corn2 = new Corner(new PointF(10, 0));
            Corner corn3 = new Corner(new PointF(10, 10));
            Wall wall = new Wall(corn1, corn2);
            Door door = new Door(corn2, corn3);

            //Act
            corn2.AddWalls(wall, door);

            //Assert
            IList lWalls = corn2.GetWalls();
            Assert.AreEqual(2, lWalls.Count);
            Assert.AreEqual(wall, lWalls[0]);
            Assert.AreEqual(door, lWalls[1]);
        }
コード例 #31
0
        /// <summary>
        /// Create walls with a rectangular profile from two coner points.
        /// </summary>
        public static List <Wall> CreateWalls(Document rvtDoc, XYZ pt1, XYZ pt2)
        {
            // Set the lower-left (x1, y1) and upper-right (x2, y2) corners of a house.
            double x1 = pt1.X;
            double x2 = pt2.X;

            if (pt1.X > pt2.X)
            {
                x1 = pt2.X;
                x2 = pt1.X;
            }

            double y1 = pt1.Y;
            double y2 = pt2.Y;

            if (pt1.Y > pt2.X)
            {
                y1 = pt2.Y;
                y2 = pt1.Y;
            }

            // Set four corner of walls from two croner point.
            // 5th point is for combenience to loop through.
            List <XYZ> pts = new List <XYZ>(5);

            pts.Add(new XYZ(x1, y1, pt1.Z));
            pts.Add(new XYZ(x2, y1, pt1.Z));
            pts.Add(new XYZ(x2, y2, pt1.Z));
            pts.Add(new XYZ(x1, y2, pt1.Z));
            pts.Add(pts[0]);

            // Get the levels we want to work on.
            // Note: hard coding for simplicity. Modify here you use a different template.
            Level level1 = ElementFiltering.FindElement(rvtDoc, typeof(Level), "Level 1", null) as Level;

            if (level1 == null)
            {
                TaskDialog.Show(
                    "Create walls", "Cannot find (Level 1). Maybe you use a different template? Try with DefaultMetric.rte."
                    );
                return(null);
            }

            Level level2 = ElementFiltering.FindElement(rvtDoc, typeof(Level), "Level 2", null) as Level;

            if (level2 == null)
            {
                TaskDialog.Show(
                    "Create walls", "Cannot find (Level 2). Maybe you use a different template? Try with DefaultMetric.rte."
                    );
                return(null);
            }

            // Flag for structural wall or not.
            bool isStructural = false;

            // Save walls we create.
            List <Wall> walls = new List <Wall>(4);

            // Loop through list of points and define four walls.
            for (int i = 0; i <= 3; i++)
            {
                // define a base curve from two points.
                Line baseCurve = Line.CreateBound(pts[i], pts[i + 1]);
                // create a wall using the one of overloaded methods.
                //Wall aWall = rvtDoc.Create.NewWall(baseCurve, level1, isStructural); // 2012
                Wall aWall = Wall.Create(rvtDoc, baseCurve, level1.Id, isStructural); // since 2013
                                                                                      // set the Top Constraint to Level 2
                aWall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).Set(level2.Id);
                // save the wall.
                walls.Add(aWall);
            }
            // This is important. we need these lines to have shrinkwrap working.
            rvtDoc.Regenerate();
            rvtDoc.AutoJoinElements();

            return(walls);
        }
コード例 #32
0
 public void Remove(Wall wallIn)
 {
     _wall.DeleteOne(wall => wall.UserId == wallIn.UserId);
 }
コード例 #33
0
 public Wall Create(Wall wall)
 {
     _wall.InsertOne(wall);
     return(wall);
 }
コード例 #34
0
ファイル: Tools.cs プロジェクト: wangzhefeng2000/RvtExporter
 public static List<Face> GetWallSideFace(Wall wall, bool isOuterFace)
 {
     var refs = HostObjectUtils.GetSideFaces(wall, isOuterFace ? ShellLayerType.Exterior : ShellLayerType.Interior);
     return refs.Select(rf => wall.GetGeometryObjectFromReference(rf) as Face).Where(obj => obj != null).ToList();
 }
コード例 #35
0
 public void SetPerp(Wall w)
 {
     Perp = (Center - w.Center).normalized;
 }
コード例 #36
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            m_revitApp = commandData.Application.Application;
            m_doc      = commandData.Application.ActiveUIDocument.Document;

            Level level1 = GetLevel();

            if (level1 == null)
            {
                throw new Exception("[ERROR] Failed to get level 1");
            }

            try
            {
                //
                // Post a warning and resolve it in FailurePreproccessor
                try
                {
                    Transaction            transaction   = new Transaction(m_doc, "Warning_FailurePreproccessor");
                    FailureHandlingOptions options       = transaction.GetFailureHandlingOptions();
                    FailurePreproccessor   preproccessor = new FailurePreproccessor();
                    options.SetFailuresPreprocessor(preproccessor);
                    transaction.SetFailureHandlingOptions(options);
                    transaction.Start();
                    FailureMessage fm = new FailureMessage(m_idWarning);
                    m_doc.PostFailure(fm);
                    transaction.Commit();
                }
                catch (System.Exception)
                {
                    message = "Failed to commit transaction Warning_FailurePreproccessor";
                    return(Result.Failed);
                }

                //
                // Dismiss the overlapped wall warning in FailurePreproccessor
                try
                {
                    Transaction            transaction   = new Transaction(m_doc, "Warning_FailurePreproccessor_OverlappedWall");
                    FailureHandlingOptions options       = transaction.GetFailureHandlingOptions();
                    FailurePreproccessor   preproccessor = new FailurePreproccessor();
                    options.SetFailuresPreprocessor(preproccessor);
                    transaction.SetFailureHandlingOptions(options);
                    transaction.Start();

                    Line line  = Line.CreateBound(new XYZ(-10, 0, 0), new XYZ(-20, 0, 0));
                    Wall wall1 = Wall.Create(m_doc, line, level1.Id, false);
                    Wall wall2 = Wall.Create(m_doc, line, level1.Id, false);
                    m_doc.Regenerate();

                    transaction.Commit();
                }
                catch (System.Exception)
                {
                    message = "Failed to commit transaction Warning_FailurePreproccessor_OverlappedWall";
                    return(Result.Failed);
                }

                //
                // Post an error and resolve it in FailuresProcessingEvent
                try
                {
                    m_revitApp.FailuresProcessing += new EventHandler <Autodesk.Revit.DB.Events.FailuresProcessingEventArgs>(FailuresProcessing);
                    Transaction transaction = new Transaction(m_doc, "Error_FailuresProcessingEvent");
                    transaction.Start();

                    Line line = Line.CreateBound(new XYZ(0, 10, 0), new XYZ(20, 10, 0));
                    Wall wall = Wall.Create(m_doc, line, level1.Id, false);
                    m_doc.Regenerate();

                    FailureMessage    fm = new FailureMessage(m_idError);
                    FailureResolution fr = DeleteElements.Create(m_doc, wall.Id);
                    fm.AddResolution(FailureResolutionType.DeleteElements, fr);
                    m_doc.PostFailure(fm);
                    transaction.Commit();
                }
                catch (System.Exception)
                {
                    message = "Failed to commit transaction Error_FailuresProcessingEvent";
                    return(Result.Failed);
                }

                //
                // Post an error and resolve it in FailuresProcessor
                try
                {
                    FailuresProcessor processor = new FailuresProcessor();
                    Application.RegisterFailuresProcessor(processor);
                    Transaction transaction = new Transaction(m_doc, "Error_FailuresProcessor");
                    transaction.Start();

                    Line line = Line.CreateBound(new XYZ(0, 20, 0), new XYZ(20, 20, 0));
                    Wall wall = Wall.Create(m_doc, line, level1.Id, false);
                    m_doc.Regenerate();

                    FailureMessage    fm = new FailureMessage(m_idError);
                    FailureResolution fr = DeleteElements.Create(m_doc, wall.Id);
                    fm.AddResolution(FailureResolutionType.DeleteElements, fr);
                    m_doc.PostFailure(fm);
                    transaction.Commit();
                }
                catch (System.Exception)
                {
                    message = "Failed to commit transaction Error_FailuresProcessor";
                    return(Result.Failed);
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
コード例 #37
0
        /// <summary>
        /// Retrieve all wall openings,
        /// including at start and end of wall.
        /// </summary>
        List <WallOpening2d> GetWallOpenings(
            Wall wall,
            View3D view)
        {
            Document doc           = wall.Document;
            Level    level         = doc.GetElement(wall.LevelId) as Level;
            double   elevation     = level.Elevation;
            Curve    c             = (wall.Location as LocationCurve).Curve;
            XYZ      wallOrigin    = c.GetEndPoint(0);
            XYZ      wallEndPoint  = c.GetEndPoint(1);
            XYZ      wallDirection = wallEndPoint - wallOrigin;
            double   wallLength    = wallDirection.GetLength();

            wallDirection = wallDirection.Normalize();
            UV offsetOut = _offset * new UV(wallDirection.X, wallDirection.Y);

            XYZ rayStart = new XYZ(wallOrigin.X - offsetOut.U,
                                   wallOrigin.Y - offsetOut.V, elevation + _offset);

            ReferenceIntersector intersector
                = new ReferenceIntersector(wall.Id,
                                           FindReferenceTarget.Face, view);

            IList <ReferenceWithContext> refs
                = intersector.Find(rayStart, wallDirection);

            // Extract the intersection points:
            // - only surfaces
            // - within wall length plus offset at each end
            // - sorted by proximity
            // - eliminating duplicates

            List <XYZ> pointList = new List <XYZ>(refs
                                                  .Where <ReferenceWithContext>(r => IsSurface(
                                                                                    r.GetReference()))
                                                  .Where <ReferenceWithContext>(r => r.Proximity
                                                                                < wallLength + _offset + _offset)
                                                  .OrderBy <ReferenceWithContext, double>(
                                                      r => r.Proximity)
                                                  .Select <ReferenceWithContext, XYZ>(r
                                                                                      => r.GetReference().GlobalPoint)
                                                  .Distinct <XYZ>(new XyzEqualityComparer()));

            // Check if first point is at the wall start.
            // If so, the wall does not begin with an opening,
            // so that point can be removed. Else, add it.

            XYZ q = wallOrigin + _offset * XYZ.BasisZ;

            bool wallHasFaceAtStart = Util.IsEqual(
                pointList[0], q);

            if (wallHasFaceAtStart)
            {
                pointList.RemoveAll(p
                                    //=> _eps > p.DistanceTo( q ) );
                                    => Util.IsEqual(p, q));
            }
            else
            {
                pointList.Insert(0, wallOrigin);
            }

            // Check if last point is at the wall end.
            // If so, the wall does not end with an opening,
            // so that point can be removed. Else, add it.

            q = wallEndPoint + _offset * XYZ.BasisZ;

            bool wallHasFaceAtEnd = Util.IsEqual(
                pointList.Last(), q);

            if (wallHasFaceAtEnd)
            {
                pointList.RemoveAll(p
                                    //=> _eps > p.DistanceTo( q ) );
                                    => Util.IsEqual(p, q));
            }
            else
            {
                pointList.Add(wallEndPoint);
            }

            int n = pointList.Count;

            Debug.Assert(IsEven(n),
                         "expected an even number of opening sides");

            var wallOpenings = new List <WallOpening2d>(
                n / 2);

            for (int i = 0; i < n; i += 2)
            {
                wallOpenings.Add(new WallOpening2d
                {
                    Start = pointList[i],
                    End   = pointList[i + 1]
                });
            }
            return(wallOpenings);
        }
コード例 #38
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), "a curtain wall", false)
                        as Wall;

            if (null == wall)
            {
                message = "Please select a single "
                          + "curtain wall element.";

                return(Result.Failed);
            }
            else
            {
                LocationCurve locationcurve
                    = wall.Location as LocationCurve;

                Curve curve = locationcurve.Curve;

                // move whole geometry over by length of wall:

                XYZ p = curve.GetEndPoint(0);
                XYZ q = curve.GetEndPoint(1);
                XYZ v = q - p;

                Transform tv = Transform.CreateTranslation(v);

                //curve = curve.get_Transformed( tv ); // 2013
                curve = curve.CreateTransformed(tv); // 2014

                Creator creator = new Creator(doc);
                creator.CreateModelCurve(curve);

                Options opt = app.Create.NewGeometryOptions();
                opt.IncludeNonVisibleObjects = true;

                GeometryElement e = wall.get_Geometry(opt);

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Create Model Curves");

                    foreach (GeometryObject obj in e)
                    {
                        curve = obj as Curve;

                        if (null != curve)
                        {
                            //curve = curve.get_Transformed( tv ); // 2013
                            curve = curve.CreateTransformed(tv); // 2014
                            creator.CreateModelCurve(curve);
                        }
                    }
                    t.Commit();
                }
                return(Result.Succeeded);
            }
        }
コード例 #39
0
 public Apartment(Wall wall, Roof roof) : base(wall, roof)
 {
 }
コード例 #40
0
ファイル: SectionLayout.cs プロジェクト: tkahng/BeyondAEC2020
        /// <summary>
        /// The SectionLayout function.
        /// </summary>
        /// <param name="model">The input model.</param>
        /// <param name="input">The arguments to the execution.</param>
        /// <returns>A SectionLayoutOutputs instance containing computed results and the model with any new elements.</returns>
        public static SectionLayoutOutputs Execute(Dictionary <string, Model> inputModels, SectionLayoutInputs input)
        {
            Envelope envelope = null;

            inputModels.TryGetValue("Envelope", out var model);
            var height = 0.0;

            if (model != null)
            {
                var envelopes = new List <Envelope>();
                envelopes.AddRange(model.AllElementsOfType <Envelope>());
                var aboveGradeEnvelopes = envelopes.Where(e => e.Elevation >= 0.0).ToList();
                if (aboveGradeEnvelopes.Count() > 0)
                {
                    envelope = aboveGradeEnvelopes.First();
                    height   = envelope.Height - 1.0;
                }
            }
            if (envelope == null)
            {
                var envMatl = new Material("envelope", new Color(1.0, 1.0, 1.0, 0.2), 0.0f, 0.0f);
                height = 10.0;
                var footprint = Polygon.Rectangle(60, 40);
                var extrude   = new Elements.Geometry.Solids.Extrude(footprint, height, Vector3.ZAxis, false);
                var geomRep   = new Representation(new List <Elements.Geometry.Solids.SolidOperation>()
                {
                    extrude
                });
                envelope = new Envelope(footprint, 0.0, height, Vector3.ZAxis, 0.0,
                                        new Transform(), envMatl, geomRep, false, System.Guid.NewGuid(), "");
            }

            var output = new SectionLayoutOutputs(10);

            var grid   = new Grid2d(envelope.Profile.Perimeter);
            var length = grid.V.Domain.Length;
            var width  = grid.U.Domain.Length;

            //Define Dimensions of non-prdoduct spaces
            var entryDepth     = 5;
            var checkoutDepth  = entryDepth + 5;
            var percentService = .25;

            //var buildingArea = envelope.Profile.Perimeter.Area();

            var circulationWidth = input.CirculationWidth;

            //Variables driving the division of the main shelf space

            var matAlpha = input.Transparency;

            if (matAlpha > 1)
            {
                matAlpha = 1;
            }
            var _percentProduce      = input.PercentProduce;
            var _percentPrepared     = input.PercentPrepared;
            var _percentGeneral      = input.PercentGeneral;
            var _percentRefrigerated = input.PercentRefrigerated;

            var _percentLeft = _percentProduce + _percentPrepared;
            var _leftSplit   = _percentProduce / (_percentProduce + _percentPrepared);

            var totalShelf = _percentLeft + _percentGeneral + _percentRefrigerated;

            var percentLeft    = _percentLeft / totalShelf;
            var percentGeneral = _percentGeneral / totalShelf + percentLeft;

            //var percentRefrigerated = _percentRefrigerated / totalShelf;


            //Split into rooms front to back
            grid.V.SplitAtParameters(new[] { entryDepth / length, checkoutDepth / length, (1 - percentService) });


            var mainEntryWidth    = 10;
            var secEntryWidth     = 5;
            var mainEntryPosition = .4;
            var secEntryPosition  = .8;

            if (input.EntryRight)
            {
                mainEntryPosition = 1 - mainEntryPosition;
                secEntryPosition  = 1 - secEntryPosition;
            }

            var mainEntryLeft  = mainEntryPosition - mainEntryWidth / 2 / length;
            var mainEntryRight = mainEntryPosition + mainEntryWidth / 2 / length;
            var secEntryLeft   = secEntryPosition - secEntryWidth / 2 / length;
            var secEntryRight  = secEntryPosition + secEntryWidth / 2 / length;


            var entryArea = grid.GetCellAtIndices(0, 0);

            entryArea.U.SplitAtParameters(new[] { mainEntryLeft, mainEntryRight, secEntryLeft, secEntryRight });
            var front1          = entryArea.GetCellAtIndices(0, 0);
            var entry1          = entryArea.GetCellAtIndices(1, 0);
            var front2          = entryArea.GetCellAtIndices(2, 0);
            var entry2          = entryArea.GetCellAtIndices(3, 0);
            var front3          = entryArea.GetCellAtIndices(4, 0);
            var checkoutArea    = grid.GetCellAtIndices(0, 1);
            var shelfArea       = grid.GetCellAtIndices(0, 2);
            var serviceAreaCell = grid.GetCellAtIndices(0, 3);

            //Split Shelf Area into sub-rooms
            shelfArea.U.SplitAtParameters(new[] { percentLeft, percentGeneral });
            var left = shelfArea.GetCellAtIndices(0, 0);

            left.V.SplitAtParameter(_leftSplit);
            var produce = left.GetCellAtIndices(0, 0);

            produce.U.SplitAtParameter(.5);
            var produce1 = produce.GetCellAtIndices(0, 0);
            var produce2 = produce.GetCellAtIndices(1, 0);
            var prepared = left.GetCellAtIndices(0, 1);
            var general  = shelfArea.GetCellAtIndices(1, 0);

            general.V.SplitAtParameter(.5);
            var general1 = general.GetCellAtIndices(0, 0);
            var general2 = general.GetCellAtIndices(0, 1);
            var refrig   = shelfArea.GetCellAtIndices(2, 0);

            refrig.V.SplitAtParameter(.5);
            var refrig1 = refrig.GetCellAtIndices(0, 0);
            var refrig2 = refrig.GetCellAtIndices(0, 1);

            var entryMaterial    = new Material("entry material", new Color(0, 0, 1, matAlpha));
            var frontMaterial    = new Material("front material", new Color(.9, .7, .7, matAlpha));
            var checkoutMaterial = new Material("checkout material", new Color(0, .5, .5, matAlpha));
            var serviceMaterial  = new Material("service material", new Color(.25, .25, .25, matAlpha));

            var produceMaterial  = new Material("produce material", new Color(0, 1, 0, matAlpha));
            var preparedMaterial = new Material("prepared material", new Color(1, .25, .25, matAlpha));
            var generalMaterial  = new Material("general material", new Color(1, 0, 0, matAlpha));
            var refrigMaterial   = new Material("refrigerated material", new Color(.75, .75, 1, matAlpha));
            var otherMaterial    = new Material("other material", new Color(0, 0, 0, matAlpha));


            //Label and return rooms --> shelf area excluded due to inclusion of sub-rooms
            //AddRoomFromCell(entryArea, "entry", entryMaterial, output.model, circulationWidth);

            AddRoomFromCell(front1, "front1", frontMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(entry1, "entrance1", entryMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(front2, "front2", frontMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(entry2, "entrance2", entryMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(front3, "front3", frontMaterial, output.model, circulationWidth, height);

            AddRoomFromCell(checkoutArea, "checkout", checkoutMaterial, output.model, circulationWidth, height);

            AddRoomFromCell(serviceAreaCell, "service", serviceMaterial, output.model, circulationWidth, height);

            AddRoomFromCell(produce1, "produce", produceMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(produce2, "produce", produceMaterial, output.model, circulationWidth, height);

            AddRoomFromCell(prepared, "prepared", preparedMaterial, output.model, circulationWidth, height);

            AddRoomFromCell(general1, "general", generalMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(general2, "general", generalMaterial, output.model, circulationWidth, height);

            AddRoomFromCell(refrig1, "refrig", refrigMaterial, output.model, circulationWidth, height);
            AddRoomFromCell(refrig2, "refrig", refrigMaterial, output.model, circulationWidth, height);



            //Create wall between service space and rest of the building
            var wallThickness = new Vector3(0, .5, 0);
            var cellSeps      = serviceAreaCell.GetCellSeparators(GridDirection.U);
            var servSep       = cellSeps[0];
            var wallPt1       = servSep.PointAt(0);
            var wallPt4       = servSep.PointAt(1) + wallThickness;
            var wallProfile   = Polygon.Rectangle(wallPt1, wallPt4);

            wallProfile = wallProfile.FitMost(envelope.Profile.Perimeter.Offset(-0.1).First());
            var serviceWall = new Wall(wallProfile, height);

            output.model.AddElement(serviceWall);

            return(output);
        }
コード例 #41
0
        private void CalculateDoorWindowInformation(ExporterIFC exporterIFC, FamilyInstance famInst,
                                                    ElementId overrideLevelId, Transform trf)
        {
            IFCFile file = exporterIFC.GetFile();

            if (ExportingDoor)
            {
                string doorOperationType = null;

                Element doorType = famInst.Document.GetElement(famInst.GetTypeId());
                if (doorType != null)
                {
                    ParameterUtil.GetStringValueFromElement(doorType, BuiltInParameter.DOOR_OPERATION_TYPE, out doorOperationType);
                }

                DoorOperationTypeString = "NOTDEFINED";
                if (!string.IsNullOrWhiteSpace(doorOperationType))
                {
                    Type enumType = null;
                    if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                    {
                        enumType = typeof(Toolkit.IFC4.IFCDoorStyleOperation);
                    }
                    else
                    {
                        enumType = typeof(Toolkit.IFCDoorStyleOperation);
                    }

                    foreach (Enum ifcDoorStyleOperation in Enum.GetValues(enumType))
                    {
                        string enumAsString = ifcDoorStyleOperation.ToString();
                        if (NamingUtil.IsEqualIgnoringCaseSpacesAndUnderscores(enumAsString, doorOperationType))
                        {
                            DoorOperationTypeString = enumAsString;
                            break;
                        }
                    }
                }

                if (DoorOperationTypeString == "NOTDEFINED")
                {
                    // We are going to try to guess the hinge placement.
                    DoorOperationTypeString = CalculateDoorOperationStyle(famInst);
                }

                if (FlippedX ^ FlippedY)
                {
                    DoorOperationTypeString = ReverseDoorStyleOperation(DoorOperationTypeString);
                }

                if (String.Compare(DoorOperationTypeString, "USERDEFINED", true) == 0)
                {
                    string userDefinedOperationType;
                    ParameterUtil.GetStringValueFromElementOrSymbol(doorType, "UserDefinedOperationType", out userDefinedOperationType);
                    if (!string.IsNullOrEmpty(userDefinedOperationType))
                    {
                        UserDefinedOperationType = userDefinedOperationType;
                    }
                    else
                    {
                        DoorOperationTypeString = "NOTDEFINED";         //re-set to NotDefined if operation type is set to UserDefined but the userDefinedOperationType parameter is empty!
                    }
                }
            }

            if (HasRealWallHost)
            {
                // do hingeside calculation
                Wall wall = HostObject as Wall;
                PosHingeSide = true;

                BoundingBoxXYZ  famBBox     = null;
                Options         options     = GeometryUtil.GetIFCExportGeometryOptions();
                GeometryElement geomElement = famInst.GetOriginalGeometry(options);
                if (geomElement != null)
                {
                    famBBox = geomElement.GetBoundingBox();
                }

                if (famBBox != null)
                {
                    XYZ bboxCtr = trf.OfPoint((famBBox.Min + famBBox.Max) / 2.0);

                    Curve curve = WallExporter.GetWallAxis(wall);

                    XYZ wallZDir = WallExporter.GetWallHeightDirection(wall);

                    // famInst.HostParameter will fail if FamilyPlacementType is WorkPlaneBased, regardless of whether or not the reported host is a Wall.
                    // In this case, just use the start parameter of the curve.
                    bool   hasHostParameter = famInst.Symbol.Family.FamilyPlacementType != FamilyPlacementType.WorkPlaneBased;
                    double param            = hasHostParameter ? famInst.HostParameter : curve.GetEndParameter(0);

                    Transform wallTrf  = curve.ComputeDerivatives(param, false);
                    XYZ       wallOrig = wallTrf.Origin;
                    XYZ       wallXDir = wallTrf.BasisX;
                    XYZ       wallYDir = wallZDir.CrossProduct(wallXDir);

                    double eps = MathUtil.Eps();

                    bboxCtr     -= wallOrig;
                    PosHingeSide = (bboxCtr.DotProduct(wallYDir) > -eps);

                    XYZ famInstYDir = trf.BasisY;
                    FlippedSymbol = (PosHingeSide != (wallYDir.DotProduct(famInstYDir) > -eps));
                }
            }
        }
コード例 #42
0
ファイル: Command.cs プロジェクト: xin1627/RevitSdkSamples
        ///<summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            try
            {
                Wall  wall  = null;
                Floor floor = null;

                ElementSet elems = new ElementSet();
                foreach (ElementId elementId in commandData.Application.ActiveUIDocument.Selection.GetElementIds())
                {
                    elems.Insert(commandData.Application.ActiveUIDocument.Document.GetElement(elementId));
                }
                #region selection handle -- select one Slab (or Structure Wall)
                //if user had some wrong selection, give user an Error message
                string errorMessage =
                    "Please select one Slab (or Structure Wall) to create PathReinforcement.";
                if (1 != elems.Size)
                {
                    message = errorMessage;
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                Autodesk.Revit.DB.Element selectElem = null;
                IEnumerator iter = elems.GetEnumerator();
                iter.Reset();
                if (iter.MoveNext())
                {
                    selectElem = (Autodesk.Revit.DB.Element)iter.Current;
                }

                if (selectElem is Wall)
                {
                    wall = selectElem as Wall;
                    if (null == wall.GetAnalyticalModel())
                    {
                        message = errorMessage;
                        return(Autodesk.Revit.UI.Result.Cancelled);
                    }
                }
                else if (selectElem is Floor)
                {
                    floor = selectElem as Floor;
                    if (null == floor.GetAnalyticalModel())
                    {
                        message = errorMessage;
                        return(Autodesk.Revit.UI.Result.Cancelled);
                    }
                }
                else
                {
                    message = errorMessage;
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }
                #endregion
                try
                {
                    if (null != wall)
                    {
                        ProfileWall profileWall = new ProfileWall(wall, commandData);
                        NewPathReinforcementForm newPathReinforcementForm =
                            new NewPathReinforcementForm(profileWall);
                        newPathReinforcementForm.ShowDialog();
                    }
                    else if (null != floor)
                    {
                        ProfileFloor             profileFloor             = new ProfileFloor(floor, commandData);
                        NewPathReinforcementForm newPathReinforcementForm =
                            new NewPathReinforcementForm(profileFloor);
                        newPathReinforcementForm.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
コード例 #43
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Select two walls and the dimension line point:

            Selection      sel  = uidoc.Selection;
            ReferenceArray refs = new ReferenceArray();

            try
            {
                ISelectionFilter f
                    = new JtElementsOfClassSelectionFilter <Wall>();

                refs.Append(sel.PickObject(
                                ObjectType.Element, f,
                                "Please select first wall"));

                refs.Append(sel.PickObject(
                                ObjectType.Element, f,
                                "Please pick dimension line "
                                + "point on second wall"));

                //rFace = sel.PickObject( ObjectType.Face,
                //  "Please select face on second wall at dimension line point" );
                //
                //rPoint = sel.PickObject( ObjectType.PointOnElement,
                //  "Please select point on first wall" );
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                message = "No two walls selected";
                return(Result.Failed);
            }

            // Ensure the two selected walls are straight and
            // parallel; determine their mutual normal vector
            // and a point on each wall for distance
            // calculations:

            Wall[]     walls = new Wall[2];
            List <int> ids   = new List <int>(2);

            XYZ[]              pts   = new XYZ[2];
            Line[]             lines = new Line[2];
            IntersectionResult ir;
            XYZ normal = null;
            int i      = 0;

            foreach (Reference r in refs)
            {
                // 'Autodesk.Revit.DB.Reference.Element' is
                // obsolete: Property will be removed. Use
                // Document.GetElement(Reference) instead.
                //Wall wall = r.Element as Wall; // 2011

                Wall wall = doc.GetElement(r) as Wall; // 2012

                walls[i] = wall;
                ids.Add(wall.Id.IntegerValue);

                // Obtain location curve and
                // check that it is straight:

                LocationCurve lc = wall.Location
                                   as LocationCurve;

                Curve curve = lc.Curve;
                lines[i] = curve as Line;

                if (null == lines[i])
                {
                    message = _prompt;
                    return(Result.Failed);
                }

                // Obtain normal vectors
                // and ensure that they are equal,
                // i.e. walls are parallel:

                if (null == normal)
                {
                    normal = Util.Normal(lines[i]);
                }
                else
                {
                    if (!Util.IsParallel(normal,
                                         Util.Normal(lines[i])))
                    {
                        message = _prompt;
                        return(Result.Failed);
                    }
                }

                // Obtain pick points and project
                // onto wall location lines:

                XYZ p = r.GlobalPoint;
                ir = lines[i].Project(p);

                if (null == ir)
                {
                    message = string.Format(
                        "Unable to project pick point {0} "
                        + "onto wall location line.",
                        i);

                    return(Result.Failed);
                }

                pts[i] = ir.XYZPoint;

                Debug.Print(
                    "Wall {0} id {1} at {2}, {3} --> point {4}",
                    i, wall.Id.IntegerValue,
                    Util.PointString(lines[i].GetEndPoint(0)),
                    Util.PointString(lines[i].GetEndPoint(1)),
                    Util.PointString(pts[i]));

                if (0 < i)
                {
                    // Project dimension point selected on second wall
                    // back onto first wall, and ensure that normal
                    // points from second wall to first:

                    ir = lines[0].Project(pts[1]);
                    if (null == ir)
                    {
                        message = string.Format(
                            "Unable to project selected dimension "
                            + "line point {0} on second wall onto "
                            + "first wall's location line.",
                            Util.PointString(pts[1]));

                        return(Result.Failed);
                    }
                    pts[0] = ir.XYZPoint;
                }

                ++i;
            }

            XYZ v = pts[0] - pts[1];

            if (0 > v.DotProduct(normal))
            {
                normal = -normal;
            }

            // Shoot a ray back from the second
            // picked wall towards first:

            Debug.Print(
                "Shooting ray from {0} in direction {1}",
                Util.PointString(pts[1]),
                Util.PointString(normal));

            View3D view = Get3DView(doc);

            if (null == view)
            {
                message = "No 3D view named '{3D}' found; "
                          + "run the View > 3D View command once "
                          + "to generate it.";

                return(Result.Failed);
            }

            //refs = doc.FindReferencesByDirection(
            //  pts[1], normal, view ); // 2011

            //IList<ReferenceWithContext> refs2
            //  = doc.FindReferencesWithContextByDirection(
            //    pts[1], normal, view ); // 2012

            // In the Revit 2014 API, the call to
            // FindReferencesWithContextByDirection causes a
            // warning saying:
            // "FindReferencesWithContextByDirection is obsolete:
            // This method is deprecated in Revit 2014.
            // Use the ReferenceIntersector class instead."

            ReferenceIntersector ri
                = new ReferenceIntersector(
                      walls[0].Id, FindReferenceTarget.Element, view);

            ReferenceWithContext ref2
                = ri.FindNearest(pts[1], normal);

            if (null == ref2)
            {
                message = "ReferenceIntersector.FindNearest"
                          + " returned null!";

                return(Result.Failed);
            }

            #region Obsolete code to determine the closest reference
#if NEED_TO_DETERMINE_CLOSEST_REFERENCE
            // Store the references to the wall surfaces:

            Reference[] surfrefs = new Reference[2] {
                null, null
            };

            // Find the two closest intersection
            // points on each of the two walls:

            double[] minDistance = new double[2] {
                double.MaxValue,
                double.MaxValue
            };

            //foreach( Reference r in refs )
            foreach (ReferenceWithContext rc in refs2)
            {
                // 'Autodesk.Revit.DB.Reference.Element' is
                // obsolete: Property will be removed. Use
                // Document.GetElement(Reference) instead.
                //Element e = r.Element; // 2011

                Reference r = rc.GetReference();
                Element   e = doc.GetElement(r); // 2012

                if (e is Wall)
                {
                    i = ids.IndexOf(e.Id.IntegerValue);

                    if (-1 < i &&
                        ElementReferenceType.REFERENCE_TYPE_SURFACE
                        == r.ElementReferenceType)
                    {
                        //GeometryObject g = r.GeometryObject; // 2011
                        GeometryObject g = e.GetGeometryObjectFromReference(r); // 2012

                        if (g is PlanarFace)
                        {
                            PlanarFace face = g as PlanarFace;

                            Line line = (e.Location as LocationCurve)
                                        .Curve as Line;

                            Debug.Print(
                                "Wall {0} at {1}, {2} surface {3} "
                                + "normal {4} proximity {5}",
                                e.Id.IntegerValue,
                                Util.PointString(line.GetEndPoint(0)),
                                Util.PointString(line.GetEndPoint(1)),
                                Util.PointString(face.Origin),
                                Util.PointString(face.Normal),
                                rc.Proximity);

                            // First reference: assert it is a face on this wall
                            // and the distance is half the wall thickness.
                            // Second reference: the first reference on the other
                            // wall; assert the distance between the two references
                            // equals the distance between the wall location lines
                            // minus half of the sum of the two wall thicknesses.

                            if (rc.Proximity < minDistance[i])
                            {
                                surfrefs[i]    = r;
                                minDistance[i] = rc.Proximity;
                            }
                        }
                    }
                }
            }

            if (null == surfrefs[0])
            {
                message = "No suitable face intersection "
                          + "points found on first wall.";

                return(Result.Failed);
            }

            if (null == surfrefs[1])
            {
                message = "No suitable face intersection "
                          + "points found on second wall.";

                return(Result.Failed);
            }

            CmdDimensionWallsIterateFaces
            .CreateDimensionElement(doc.ActiveView,
                                    pts[0], surfrefs[0], pts[1], surfrefs[1]);
#endif // NEED_TO_DETERMINE_CLOSEST_REFERENCE
            #endregion // Obsolete code to determine the closest reference

            CmdDimensionWallsIterateFaces
            .CreateDimensionElement(doc.ActiveView,
                                    pts[0], ref2.GetReference(), pts[1], refs.get_Item(1));

            return(Result.Succeeded);
        }
コード例 #44
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Debug.Assert(false,
                         "setting the disallow join property was not possible prior to Revit 2012. "
                         + "In Revit 2012, you can use the WallUtils.DisallowWallJoinAtEnd method.");

            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            string s = "a wall, to retrieve its join types";

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), s, false) as Wall;

            if (null == wall)
            {
                message = "Please select a wall.";
            }
            else
            {
                JoinType []     a1 = ( JoinType [] )Enum.GetValues(typeof(JoinType));
                List <JoinType> a  = new List <JoinType>((JoinType[])Enum.GetValues(typeof(JoinType)));
                int             n  = a.Count;

                LocationCurve lc = wall.Location as LocationCurve;

                s = Util.ElementDescription(wall) + ":\n";

                /*for( int i = 0; i < 2; ++i )
                 * {
                 * JoinType jt = lc.get_JoinType( i );
                 * int j = a.IndexOf( jt ) + 1;
                 * JoinType jtnew = a[ j < n ? j : 0];
                 * lc.set_JoinType( j, jtnew );
                 * s += string.Format(
                 *  "\nChanged join type at {0} from {1} to {2}.",
                 *  ( 0 == i ? "start" : "end" ), jt, jtnew );
                 * }
                 * // wall.Location = lc; // Property or indexer 'Autodesk.Revit.Element.Location' cannot be assigned to -- it is read only
                 */

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Set Wall Join Type");

                    for (int i = 0; i < 2; ++i)
                    {
                        JoinType jt    = ((LocationCurve)wall.Location).get_JoinType(i);
                        int      j     = a.IndexOf(jt) + 1;
                        JoinType jtnew = a[j < n ? j : 0];
                        ((LocationCurve)wall.Location).set_JoinType(j, jtnew);
                        s += string.Format(
                            "\nChanged join type at {0} from {1} to {2}.",
                            (0 == i ? "start" : "end"), jt, jtnew);
                    }
                    t.Commit();
                }
            }
            Util.InfoMsg(s);
            return(Result.Succeeded);
        }
コード例 #45
0
 public FoodHash(Wall wall) : base(wall, foodSymbol, points)
 {
 }
コード例 #46
0
        void RoomFinish(UIDocument uiDoc, Transaction tx)
        {
            Document doc = uiDoc.Document;

            tx.Start(Tools.LangResMan.GetString("roomFinishes_transactionName", Tools.Cult));

            //Load the selection form
            RoomsFinishesControl userControl = new RoomsFinishesControl(uiDoc);

            userControl.InitializeComponent();

            if (userControl.ShowDialog() == true)
            {
                //Select wall types
                WallType plinte      = userControl.SelectedWallType;
                WallType newWallType = userControl.DuplicatedWallType;

                //Get all finish properties
                double height = userControl.BoardHeight;

                //Select Rooms in model
                IEnumerable <Room> modelRooms = userControl.SelectedRooms;

                Dictionary <ElementId, ElementId> skirtingDictionary = new Dictionary <ElementId, ElementId>();
                List <KeyValuePair <Wall, Wall> > addedWalls         = new List <KeyValuePair <Wall, Wall> >();

                //Loop on all rooms to get boundaries
                foreach (Room currentRoom in modelRooms)
                {
                    ElementId roomLevelId = currentRoom.LevelId;

                    SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions();
                    opt.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish;

                    IList <IList <Autodesk.Revit.DB.BoundarySegment> > boundarySegmentArray = currentRoom.GetBoundarySegments(opt);
                    if (null == boundarySegmentArray)  //the room may not be bound
                    {
                        continue;
                    }

                    foreach (IList <Autodesk.Revit.DB.BoundarySegment> boundarySegArr in boundarySegmentArray)
                    {
                        if (0 == boundarySegArr.Count)
                        {
                            continue;
                        }
                        else
                        {
                            foreach (Autodesk.Revit.DB.BoundarySegment boundarySegment in boundarySegArr)
                            {
                                //Check if the boundary is a room separation lines
                                Element boundaryElement = doc.GetElement(boundarySegment.ElementId);

                                if (boundaryElement == null)
                                {
                                    continue;
                                }

                                Categories categories            = doc.Settings.Categories;
                                Category   RoomSeparetionLineCat = categories.get_Item(BuiltInCategory.OST_RoomSeparationLines);

                                if (boundaryElement.Category.Id != RoomSeparetionLineCat.Id)
                                {
                                    Wall      currentWall       = Wall.Create(doc, boundarySegment.GetCurve(), newWallType.Id, roomLevelId, height, 0, false, false);
                                    Parameter wallJustification = currentWall.get_Parameter(BuiltInParameter.WALL_KEY_REF_PARAM);
                                    wallJustification.Set(2);

                                    skirtingDictionary.Add(currentWall.Id, boundarySegment.ElementId);
                                }
                            }
                        }
                    }
                }

                FailureHandlingOptions options = tx.GetFailureHandlingOptions();

                options.SetFailuresPreprocessor(new PlintePreprocessor());
                // Now, showing of any eventual mini-warnings will be postponed until the following transaction.
                tx.Commit(options);

                tx.Start(Tools.LangResMan.GetString("roomFinishes_transactionName", Tools.Cult));

                List <ElementId> addedIds = new List <ElementId>(skirtingDictionary.Keys);
                foreach (ElementId addedSkirtingId in addedIds)
                {
                    if (doc.GetElement(addedSkirtingId) == null)
                    {
                        skirtingDictionary.Remove(addedSkirtingId);
                    }
                }

                Wall.ChangeTypeId(doc, skirtingDictionary.Keys, plinte.Id);

                //Join both wall
                if (userControl.JoinWall)
                {
                    foreach (ElementId skirtingId in skirtingDictionary.Keys)
                    {
                        Wall skirtingWall = doc.GetElement(skirtingId) as Wall;

                        if (skirtingWall != null)
                        {
                            Parameter wallJustification = skirtingWall.get_Parameter(BuiltInParameter.WALL_KEY_REF_PARAM);
                            wallJustification.Set(3);
                            Wall baseWall = doc.GetElement(skirtingDictionary[skirtingId]) as Wall;

                            if (baseWall != null)
                            {
                                JoinGeometryUtils.JoinGeometry(doc, skirtingWall, baseWall);
                            }
                        }
                    }
                }

                doc.Delete(newWallType.Id);

                tx.Commit();
            }
            else
            {
                tx.RollBack();
            }
        }
コード例 #47
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool");

            try
            {
                transaction.Start();
                Wall  wall  = null;
                Floor floor = null;

                ElementSet elems = commandData.Application.ActiveUIDocument.Selection.Elements;
                #region selection error handle
                //if user have some wrong selection, give user an error message
                if (1 != elems.Size)
                {
                    message = "please selected one Object (Floor or Wall) to create Opening.";
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                Autodesk.Revit.DB.Element selectElem = null;
                foreach (Autodesk.Revit.DB.Element e in elems)
                {
                    selectElem = e;
                }

                if (!(selectElem is Wall) && !(selectElem is Floor))
                {
                    message = "please selected one Object (Floor or Wall) to create Opening.";
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }
                #endregion
                try
                {
                    if (selectElem is Wall)
                    {
                        wall = selectElem as Wall;
                        ProfileWall     profileWall     = new ProfileWall(wall, commandData);
                        NewOpeningsForm newOpeningsForm = new NewOpeningsForm(profileWall);
                        newOpeningsForm.ShowDialog();
                    }
                    else if (selectElem is Floor)
                    {
                        floor = selectElem as Floor;
                        ProfileFloor    profileFloor    = new ProfileFloor(floor, commandData);
                        NewOpeningsForm newOpeningsForm = new NewOpeningsForm(profileFloor);
                        newOpeningsForm.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
            finally
            {
                transaction.Commit();
            }
        }
コード例 #48
0
        public void Perform()
        {
            Func <bool> f_ゴミ回収 = SCommon.Supplier(this.E_ゴミ回収());

            this.Map = new Map(GameCommon.GetMapFile(this.World.GetCurrMapName()));
            this.ReloadEnemies();

            // デフォルトの「プレイヤーのスタート地点」
            // -- マップの中央
            this.Player.X = this.Map.W * GameConsts.TILE_W / 2.0;
            this.Player.Y = this.Map.H * GameConsts.TILE_H / 2.0;

            {
                Enemy enemy = this.Enemies.Iterate().FirstOrDefault(v => v is Enemy_スタート地点 && ((Enemy_スタート地点)v).Direction == this.Status.StartPointDirection);

                if (enemy != null)
                {
                    this.Player.X = enemy.X;
                    this.Player.Y = enemy.Y;
                }
            }

            // ★★★★★
            // プレイヤー・ステータス反映(マップ入場時)
            // その他の反映箇所:
            // -- マップ退場時
            // -- セーブ時
            {
                this.Player.HP         = this.Status.StartHP;
                this.Player.FacingLeft = this.Status.StartFacingLeft;
                this.Player.武器         = this.Status.Start_武器;
            }

            this.Wall = WallCreator.Create(this.Map.WallName);

            MusicCollection.Get(this.Map.MusicName).Play();

            DDGround.Camera.X = this.Player.X - DDConsts.Screen_W / 2.0;
            DDGround.Camera.Y = this.Player.Y - DDConsts.Screen_H / 2.0;

            DDCurtain.SetCurtain(0, -1.0);
            DDCurtain.SetCurtain(10);

            DDEngine.FreezeInput();

            for (this.Frame = 0; ; this.Frame++)
            {
                if (!this.UserInputDisabled && DDInput.PAUSE.GetInput() == 1)
                {
                    this.Pause();

                    if (this.Pause_ReturnToTitleMenu)
                    {
                        this.Status.ExitDirection = 5;
                        break;
                    }
                }
                if (this.RequestReturnToTitleMenu)
                {
                    this.Status.ExitDirection = 5;
                    break;
                }
                if (DDConfig.LOG_ENABLED && DDKey.GetInput(DX.KEY_INPUT_RETURN) == 1)
                {
                    this.DebugPause();
                }

                // 死亡時にカメラ移動を止める。
                //if (this.Player.DeadFrame == 0)
                //    this.カメラ位置調整(false);

                this.カメラ位置調整(false);

                if (DDConfig.LOG_ENABLED && DDKey.GetInput(DX.KEY_INPUT_E) == 1)                 // エディットモード(デバッグ用)
                {
                    this.Edit();
                    this.ReloadEnemies();
                    this.Frame = 0;
                }

                // プレイヤー入力
                {
                    bool deadOrDamageOrUID = 1 <= this.Player.DeadFrame || 1 <= this.Player.DamageFrame || this.UserInputDisabled;
                    bool move     = false;
                    bool slow     = false;
                    bool camSlide = false;
                    int  jump     = 0;
                    bool shagami  = false;
                    bool attack   = false;

                    if (!deadOrDamageOrUID && 1 <= DDInput.DIR_2.GetInput() || this.PlayerHacker.DIR_2)
                    {
                        shagami = true;
                    }

                    // 入力抑止中であるか否かに関わらず左右の入力は受け付ける様にする。
                    int freezeInputFrameBackup = DDEngine.FreezeInputFrame;
                    DDEngine.FreezeInputFrame = 0;

                    if (!deadOrDamageOrUID && 1 <= DDInput.DIR_4.GetInput() || this.PlayerHacker.DIR_4)
                    {
                        this.Player.FacingLeft = true;
                        move = true;
                    }
                    if (!deadOrDamageOrUID && 1 <= DDInput.DIR_6.GetInput() || this.PlayerHacker.DIR_6)
                    {
                        this.Player.FacingLeft = false;
                        move = true;
                    }

                    DDEngine.FreezeInputFrame = freezeInputFrameBackup;                     // restore

                    if (1 <= DDInput.L.GetInput())
                    {
                        move     = false;
                        shagami  = false;
                        camSlide = true;
                    }
                    if (!deadOrDamageOrUID && 1 <= DDInput.R.GetInput() || this.PlayerHacker.Slow)
                    {
                        slow = true;
                    }
                    if (!deadOrDamageOrUID && 1 <= DDInput.A.GetInput())
                    {
                        jump = DDInput.A.GetInput();
                    }
                    if (this.PlayerHacker.Jump != 0)
                    {
                        jump = this.PlayerHacker.Jump;
                    }
                    if (!deadOrDamageOrUID && 1 <= DDInput.B.GetInput() || this.PlayerHacker.Attack)
                    {
                        attack = true;
                    }

                    if (move)
                    {
                        this.Player.MoveFrame++;
                        shagami = false;
                    }
                    else
                    {
                        this.Player.MoveFrame = 0;
                    }

                    this.Player.MoveSlow = move && slow;

                    if (1 <= this.Player.JumpFrame)
                    {
                        const int JUMP_FRAME_MAX = 22;

                        if (1 <= jump && this.Player.JumpFrame < JUMP_FRAME_MAX)
                        {
                            this.Player.JumpFrame++;
                        }
                        else
                        {
                            this.Player.JumpFrame = 0;
                        }
                    }
                    else
                    {
                        // 事前入力 == 着地前の数フレーム間にジャンプボタンを押し始めてもジャンプできるようにする。
                        // 入力猶予 == 落下(地面から離れた)直後の数フレーム間にジャンプボタンを押し始めてもジャンプできるようにする。

                        const int 事前入力時間 = 5;
                        const int 入力猶予時間 = 5;

                        if (1 <= jump && jump < 事前入力時間 && this.Player.AirborneFrame < 入力猶予時間)
                        {
                            this.Player.JumpFrame = 1;
                        }
                    }

                    if (camSlide)
                    {
                        if (DDInput.DIR_4.IsPound())
                        {
                            this.CamSlideCount++;
                            this.CamSlideX--;
                        }
                        if (DDInput.DIR_6.IsPound())
                        {
                            this.CamSlideCount++;
                            this.CamSlideX++;
                        }
                        if (DDInput.DIR_8.IsPound())
                        {
                            this.CamSlideCount++;
                            this.CamSlideY--;
                        }
                        if (DDInput.DIR_2.IsPound())
                        {
                            this.CamSlideCount++;
                            this.CamSlideY++;
                        }
                        DDUtils.ToRange(ref this.CamSlideX, -1, 1);
                        DDUtils.ToRange(ref this.CamSlideY, -1, 1);
                    }
                    else
                    {
                        if (this.CamSlideMode && this.CamSlideCount == 0)
                        {
                            this.CamSlideX = 0;
                            this.CamSlideY = 0;
                        }
                        this.CamSlideCount = 0;
                    }
                    this.CamSlideMode = camSlide;

                    if (1 <= this.Player.AirborneFrame)
                    {
                        shagami = false;
                    }

                    if (shagami)
                    {
                        this.Player.ShagamiFrame++;
                    }
                    else
                    {
                        this.Player.ShagamiFrame = 0;
                    }

                    if (attack)
                    {
                        this.Player.AttackFrame++;
                    }
                    else
                    {
                        this.Player.AttackFrame = 0;
                    }
                }

                //startDead:
                if (1 <= this.Player.DeadFrame)                 // プレイヤー死亡中の処理
                {
                    if (GameConsts.PLAYER_DEAD_FRAME_MAX < ++this.Player.DeadFrame)
                    {
                        this.Player.DeadFrame     = 0;
                        this.Status.ExitDirection = 5;
                        break;
                    }
                    int    frame = this.Player.DeadFrame;                  // 値域 == 2 ~ GameConsts.PLAYER_DEAD_FRAME_MAX
                    double rate  = DDUtils.RateAToB(2, GameConsts.PLAYER_DEAD_FRAME_MAX, frame);

                    // ---- Dead

                    const int HIT_BACK_FRAME_MAX = 30;

                    if (frame < HIT_BACK_FRAME_MAX)
                    {
                        double hitBackRate = (double)frame / HIT_BACK_FRAME_MAX;

                        this.Player.X -= 10.0 * (1.0 - hitBackRate) * (this.Player.FacingLeft ? -1 : 1);
                    }
                }
                //endDead:

                //startDamage:
                if (1 <= this.Player.DamageFrame)                 // プレイヤー・ダメージ中の処理
                {
                    if (GameConsts.PLAYER_DAMAGE_FRAME_MAX < ++this.Player.DamageFrame)
                    {
                        this.Player.DamageFrame     = 0;
                        this.Player.InvincibleFrame = 1;
                        goto endDamage;
                    }
                    int    frame = this.Player.DamageFrame;                  // 値域 == 2 ~ GameConsts.PLAYER_DAMAGE_FRAME_MAX
                    double rate  = DDUtils.RateAToB(2, GameConsts.PLAYER_DAMAGE_FRAME_MAX, frame);

                    // ---- Damage

                    this.Player.X -= (9.0 - 6.0 * rate) * (this.Player.FacingLeft ? -1 : 1);
                }
endDamage:

                //startInvincible:
                if (1 <= this.Player.InvincibleFrame)                 // プレイヤー無敵時間中の処理
                {
                    if (GameConsts.PLAYER_INVINCIBLE_FRAME_MAX < ++this.Player.InvincibleFrame)
                    {
                        this.Player.InvincibleFrame = 0;
                        goto endInvincible;
                    }
                    int    frame = this.Player.InvincibleFrame;                  // 値域 == 2 ~ GameConsts.PLAYER_INVINCIBLE_FRAME_MAX
                    double rate  = DDUtils.RateAToB(2, GameConsts.PLAYER_INVINCIBLE_FRAME_MAX, frame);

                    // ---- Invincible

                    // noop
                }
endInvincible:

                // プレイヤー移動
                {
                    if (1 <= this.Player.MoveFrame)
                    {
                        double speed = 0.0;

                        if (this.Player.MoveSlow)
                        {
                            speed = this.Player.MoveFrame * 0.2;
                            DDUtils.Minim(ref speed, GameConsts.PLAYER_SLOW_SPEED);
                        }
                        else
                        {
                            speed = GameConsts.PLAYER_SPEED;
                        }

                        speed *= this.Player.FacingLeft ? -1 : 1;

                        this.Player.X += speed;
                    }
                    else
                    {
                        this.Player.X = (double)SCommon.ToInt(this.Player.X);
                    }

                    if (1 <= this.Player.JumpFrame)
                    {
                        this.Player.YSpeed = GameConsts.PLAYER_ジャンプによる上昇速度;
                    }
                    else
                    {
                        this.Player.YSpeed += GameConsts.PLAYER_GRAVITY;
                    }

                    DDUtils.Minim(ref this.Player.YSpeed, GameConsts.PLAYER_FALL_SPEED_MAX);

                    this.Player.Y += this.Player.YSpeed;                     // 自由落下
                }

                // プレイヤー位置矯正
                {
                    bool touchSide_L =
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X - GameConsts.PLAYER_側面判定Pt_X, this.Player.Y - GameConsts.PLAYER_側面判定Pt_Y)).Tile.IsWall() ||
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X - GameConsts.PLAYER_側面判定Pt_X, this.Player.Y)).Tile.IsWall() ||
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X - GameConsts.PLAYER_側面判定Pt_X, this.Player.Y + GameConsts.PLAYER_側面判定Pt_Y)).Tile.IsWall();

                    bool touchSide_R =
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X + GameConsts.PLAYER_側面判定Pt_X, this.Player.Y - GameConsts.PLAYER_側面判定Pt_Y)).Tile.IsWall() ||
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X + GameConsts.PLAYER_側面判定Pt_X, this.Player.Y)).Tile.IsWall() ||
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X + GameConsts.PLAYER_側面判定Pt_X, this.Player.Y + GameConsts.PLAYER_側面判定Pt_Y)).Tile.IsWall();

                    if (touchSide_L && touchSide_R)                     // -> 壁抜け防止のため再チェック
                    {
                        touchSide_L = this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X - GameConsts.PLAYER_側面判定Pt_X, this.Player.Y)).Tile.IsWall();
                        touchSide_R = this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X + GameConsts.PLAYER_側面判定Pt_X, this.Player.Y)).Tile.IsWall();
                    }

                    if (touchSide_L && touchSide_R)
                    {
                        // noop
                    }
                    else if (touchSide_L)
                    {
                        this.Player.X = (double)SCommon.ToInt(this.Player.X / GameConsts.TILE_W) * GameConsts.TILE_W + GameConsts.PLAYER_側面判定Pt_X;
                    }
                    else if (touchSide_R)
                    {
                        this.Player.X = (double)SCommon.ToInt(this.Player.X / GameConsts.TILE_W) * GameConsts.TILE_W - GameConsts.PLAYER_側面判定Pt_X;
                    }

                    bool touchCeiling_L =
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X - GameConsts.PLAYER_脳天判定Pt_X, this.Player.Y - GameConsts.PLAYER_脳天判定Pt_Y)).Tile.IsWall();

                    bool touchCeiling_R =
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X + GameConsts.PLAYER_脳天判定Pt_X, this.Player.Y - GameConsts.PLAYER_脳天判定Pt_Y)).Tile.IsWall();

                    if (touchCeiling_L && touchCeiling_R)
                    {
                        if (this.Player.YSpeed < 0.0)
                        {
                            double plY = ((int)((this.Player.Y - GameConsts.PLAYER_脳天判定Pt_Y) / GameConsts.TILE_H) + 1) * GameConsts.TILE_H + GameConsts.PLAYER_脳天判定Pt_Y;

                            this.Player.Y         = plY;
                            this.Player.YSpeed    = 0.0;
                            this.Player.JumpFrame = 0;
                        }
                    }
                    else if (touchCeiling_L)
                    {
                        this.Player.X = (double)SCommon.ToInt(this.Player.X / GameConsts.TILE_W) * GameConsts.TILE_W + GameConsts.PLAYER_脳天判定Pt_X;
                    }
                    else if (touchCeiling_R)
                    {
                        this.Player.X = (double)SCommon.ToInt(this.Player.X / GameConsts.TILE_W) * GameConsts.TILE_W - GameConsts.PLAYER_脳天判定Pt_X;
                    }

                    bool touchGround =
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X - GameConsts.PLAYER_接地判定Pt_X, this.Player.Y + GameConsts.PLAYER_接地判定Pt_Y)).Tile.IsWall() ||
                        this.Map.GetCell(GameCommon.ToTablePoint(this.Player.X + GameConsts.PLAYER_接地判定Pt_X, this.Player.Y + GameConsts.PLAYER_接地判定Pt_Y)).Tile.IsWall();

                    if (touchGround)
                    {
                        if (0.0 < this.Player.YSpeed)
                        {
                            double plY = (int)((this.Player.Y + GameConsts.PLAYER_接地判定Pt_Y) / GameConsts.TILE_H) * GameConsts.TILE_H - GameConsts.PLAYER_接地判定Pt_Y;

                            this.Player.Y      = plY;
                            this.Player.YSpeed = 0.0;
                        }
                    }

                    if (touchGround)
                    {
                        this.Player.AirborneFrame = 0;
                    }
                    else
                    {
                        this.Player.AirborneFrame++;
                    }
                }
                //endPlayer:

                if (this.Player.X < 0.0)                 // ? マップの左側に出た。
                {
                    this.Status.ExitDirection = 4;
                    break;
                }
                if (this.Map.W * GameConsts.TILE_W < this.Player.X)                 // ? マップの右側に出た。
                {
                    this.Status.ExitDirection = 6;
                    break;
                }
                if (this.Player.Y < 0.0)                 // ? マップの上側に出た。
                {
                    this.Status.ExitDirection = 8;
                    break;
                }
                if (this.Map.H * GameConsts.TILE_H < this.Player.Y)                 // ? マップの下側に出た。
                {
                    this.Status.ExitDirection = 2;
                    break;
                }

                // 画面遷移時の微妙なカメラ位置ズレ解消
                // -- スタート地点(入場地点)が地面と接していると、最初のフレームでプレイヤーは上に押し出されてカメラの初期位置とズレてしまう。
                if (this.Frame == 0 || this.次のカメラ位置調整を一瞬で)
                {
                    this.次のカメラ位置調整を一瞬で = false;
                    this.カメラ位置調整(true);
                }

                if (1 <= this.Player.AttackFrame)
                {
                    this.Player.Attack();
                }

                DDCrash plCrash = DDCrashUtils.Point(new D2Point(this.Player.X, this.Player.Y + (1 <= this.Player.ShagamiFrame ? 16 : 0)));

                // ====
                // 描画ここから
                // ====

                this.DrawWall();
                this.DrawMap();
                this.Player.Draw();

                // memo: DeadFlag をチェックするのは「当たり判定」から

                foreach (Enemy enemy in this.Enemies.Iterate())
                {
                    enemy.Crash = DDCrashUtils.None();                     // reset
                    enemy.Draw();
                }
                foreach (Shot shot in this.Shots.Iterate())
                {
                    shot.Crash = DDCrashUtils.None();                     // reset
                    shot.Draw();
                }

                if (this.当たり判定表示)
                {
                    // 最後に描画されるように DDGround.EL.Add() する。

                    DDGround.EL.Add(() =>
                    {
                        DDCurtain.DrawCurtain(-0.7);

                        const double A = 0.7;

                        DDCrashView.Draw(new DDCrash[] { plCrash }, new I3Color(255, 0, 0), 1.0);
                        DDCrashView.Draw(this.Enemies.Iterate().Select(v => v.Crash), new I3Color(255, 255, 255), A);
                        DDCrashView.Draw(this.Shots.Iterate().Select(v => v.Crash), new I3Color(0, 255, 255), A);

                        return(false);
                    });
                }

                // ====
                // 描画ここまで
                // ====

                // ====
                // 当たり判定ここから
                // ====

                foreach (Enemy enemy in this.Enemies.Iterate())
                {
                    if (1 <= enemy.HP)                     // ? 敵:生存 && 無敵ではない
                    {
                        foreach (Shot shot in this.Shots.Iterate())
                        {
                            // 衝突判定:敵 x 自弾
                            if (
                                !shot.DeadFlag &&                                 // ? 自弾:生存
                                enemy.Crash.IsCrashed(shot.Crash)                 // ? 衝突
                                )
                            {
                                // ★ 敵_被弾ここから

                                if (!shot.敵を貫通する)
                                {
                                    shot.Kill();
                                }

                                enemy.HP -= shot.AttackPoint;

                                if (1 <= enemy.HP)                                 // ? まだ生存している。
                                {
                                    enemy.Damaged(shot);
                                }
                                else                                 // ? 撃破した。
                                {
                                    enemy.Kill(true);
                                    break;                                     // この敵は死亡したので、この敵について以降の当たり判定は不要
                                }

                                // ★ 敵_被弾ここまで
                            }
                        }
                    }

                    // 衝突判定:敵 x 自機
                    if (
                        this.Player.DeadFrame == 0 &&                // ? プレイヤー死亡中ではない。
                        this.Player.DamageFrame == 0 &&              // ? プレイヤー・ダメージ中ではない。
                        this.Player.InvincibleFrame == 0 &&          // ? プレイヤー無敵時間中ではない。
                        !enemy.DeadFlag &&                           // ? 敵:生存
                        DDCrashUtils.IsCrashed(enemy.Crash, plCrash) // ? 衝突
                        )
                    {
                        // ★ 自機_被弾ここから

                        if (enemy.自機に当たると消滅する)
                        {
                            enemy.Kill();
                        }

                        this.Player.HP -= enemy.AttackPoint;

                        if (1 <= this.Player.HP)                         // ? まだ生存している。
                        {
                            this.Player.DamageFrame = 1;
                        }
                        else                         // ? 死亡した。
                        {
                            this.Player.HP        = -1;
                            this.Player.DeadFrame = 1;
                        }

                        // ★ 自機_被弾ここまで
                    }
                }

                foreach (Shot shot in this.Shots.Iterate())
                {
                    // 壁への当たり判定は自弾の「中心座標のみ」であることに注意して下さい。

                    if (
                        !shot.DeadFlag &&                                                       // ? 自弾:生存
                        !shot.壁をすり抜ける &&                                                        // ? この自弾は壁に当たる。
                        this.Map.GetCell(GameCommon.ToTablePoint(shot.X, shot.Y)).Tile.IsWall() // ? 壁に当たった。
                        )
                    {
                        shot.Kill();
                    }
                }

                // ====
                // 当たり判定ここまで
                // ====

                f_ゴミ回収();

                this.Enemies.RemoveAll(v => v.DeadFlag);
                this.Shots.RemoveAll(v => v.DeadFlag);

                DDEngine.EachFrame();

                // ★★★ ゲームループの終わり ★★★
            }
            DDEngine.FreezeInput();

            if (this.Status.ExitDirection == 5)
            {
                DDMusicUtils.Fade();
                DDCurtain.SetCurtain(30, -1.0);

                foreach (DDScene scene in DDSceneUtils.Create(40))
                {
                    this.DrawWall();
                    this.DrawMap();

                    DDEngine.EachFrame();
                }
            }
            else
            {
                double destSlide_X = 0.0;
                double destSlide_Y = 0.0;

                switch (this.Status.ExitDirection)
                {
                case 4:
                    destSlide_X = DDConsts.Screen_W;
                    break;

                case 6:
                    destSlide_X = -DDConsts.Screen_W;
                    break;

                case 8:
                    destSlide_Y = DDConsts.Screen_H;
                    break;

                case 2:
                    destSlide_Y = -DDConsts.Screen_H;
                    break;

                default:
                    throw null;                             // never
                }
                using (DDSubScreen wallMapScreen = new DDSubScreen(DDConsts.Screen_W, DDConsts.Screen_H))
                {
                    using (wallMapScreen.Section())
                    {
                        this.DrawWall();
                        this.DrawMap();
                    }
                    foreach (DDScene scene in DDSceneUtils.Create(30))
                    {
                        double slide_X = destSlide_X * scene.Rate;
                        double slide_Y = destSlide_Y * scene.Rate;

                        DDCurtain.DrawCurtain();
                        DDDraw.DrawSimple(wallMapScreen.ToPicture(), slide_X, slide_Y);

                        DDEngine.EachFrame();
                    }
                }
                DDCurtain.SetCurtain(0, -1.0);
            }

            // ★★★★★
            // プレイヤー・ステータス反映(マップ退場時)
            // その他の反映箇所:
            // -- マップ入場時
            // -- セーブ時
            {
                this.Status.StartHP         = this.Player.HP;
                this.Status.StartFacingLeft = this.Player.FacingLeft;
                this.Status.Start_武器        = this.Player.武器;
            }

            // ★★★ end of Perform() ★★★
        }
コード例 #49
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            #region TEST_1
#if TEST_1
            //
            // you cannot create your own parameter, because the
            // constuctor is for internal use only. This is due
            // to the fact that a parameter cannot live on its own,
            // it is linked to a definition and needs to be hooked
            // up properly in the Revit database system to work
            // ... case 1245614 [Formatting units strings]:
            //
            bool iReallyWantToCrash = false;
            if (iReallyWantToCrash)
            {
                Parameter p = new Parameter();
                p.Set(1.0);
                string s = p.AsDouble().ToString();
                string t = p.AsValueString();
                Debug.WriteLine("Value " + s);
                Debug.WriteLine("Value string " + t);
            }
#endif // TEST
            #endregion // TEST_1

            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            // Loop through all pre-selected elements:

            foreach (ElementId id in uidoc.Selection.GetElementIds())
            {
                Element e = doc.GetElement(id);

                string s = string.Empty;

                // set this variable to false to analyse the element's own parameters,
                // i.e. instance parameters for a family instance, and set it to true
                // to analyse a family instance's type parameters:

                bool analyseTypeParameters = false;

                if (analyseTypeParameters)
                {
                    if (e is FamilyInstance)
                    {
                        FamilyInstance inst = e as FamilyInstance;
                        if (null != inst.Symbol)
                        {
                            e = inst.Symbol;
                            s = " type";
                        }
                    }
                    else if (e is Wall)
                    {
                        Wall wall = e as Wall;
                        if (null != wall.WallType)
                        {
                            e = wall.WallType;
                            s = " type";
                        }
                    }
                    // ... add support for other types if desired ...
                }

                // Loop through and list all UI-visible element parameters

                List <string> a = new List <string>();

                #region 4.1.a Iterate over element parameters and retrieve their name, type and value:

                foreach (Parameter p in e.Parameters)
                {
                    string name  = p.Definition.Name;
                    string type  = p.StorageType.ToString();
                    string value = LabUtils.GetParameterValue2(p, uidoc.Document);
                    //bool read_only = p.Definition.IsReadOnly; // 2013
                    bool read_only = p.IsReadOnly; // 2014
                    a.Add(string.Format(
                              "Name={0}; Type={1}; Value={2}; ValueString={3}; read-{4}",
                              name, type, value, p.AsValueString(),
                              (read_only ? "only" : "write")));
                }

                #endregion // 4.1.a

                string what = e.Category.Name
                              + " (" + e.Id.IntegerValue.ToString() + ")";

                LabUtils.InfoMsg(what + " has {0} parameter{1}{2}", a);

                // If we know which param we are looking for, then:
                // A) If a standard parameter, we can get it via BuiltInParam
                // signature of Parameter method:

                try
                {
                    #region 4.1.b Retrieve a specific built-in parameter:

                    Parameter p = e.get_Parameter(
                        BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM);

                    #endregion // 4.1.b

                    if (null == p)
                    {
                        LabUtils.InfoMsg("FAMILY_BASE_LEVEL_OFFSET_PARAM is NOT available for this element.");
                    }
                    else
                    {
                        string name  = p.Definition.Name;
                        string type  = p.StorageType.ToString();
                        string value = LabUtils.GetParameterValue2(p, doc);
                        LabUtils.InfoMsg("FAMILY_BASE_LEVEL_OFFSET_PARAM: Name=" + name
                                         + "; Type=" + type + "; Value=" + value);
                    }
                }
                catch (Exception)
                {
                    LabUtils.InfoMsg("FAMILY_BASE_LEVEL_OFFSET_PARAM is NOT available for this element.");
                }

                // B) For a shared parameter, we can get it via "GUID" signature
                // of Parameter method  ... this will be shown later in Labs 4 ...

                // C) or we can get the parameter by name:
                // alternatively, loop through all parameters and
                // search for the name (this works for either
                // standard or shared). Note that the same name
                // may occur multiple times:

                const string paramName = "Base Offset";

                //Parameter parByName = e.get_Parameter( paramName ); // 2014

                IList <Parameter> paramsByName = e.GetParameters(paramName); // 2015

                if (0 == paramsByName.Count)
                {
                    LabUtils.InfoMsg(paramName + " is NOT available for this element.");
                }
                else
                {
                    foreach (Parameter p in paramsByName)
                    {
                        string parByNameName  = p.Definition.Name;
                        string parByNameType  = p.StorageType.ToString();
                        string parByNameValue = LabUtils.GetParameterValue2(p, doc);
                        LabUtils.InfoMsg(paramName + ": Name=" + parByNameName
                                         + "; Type=" + parByNameType + "; Value=" + parByNameValue);
                    }
                }

                #region TEST_2
#if TEST_2
                List <string> a = GetParameters(doc, e);
                foreach (string s2 in a)
                {
                    Debug.WriteLine(s2);
                }
#endif // TEST_2
                #endregion // TEST_2
            }
            return(Result.Failed);
        }
コード例 #50
0
        /// <summary>
        /// Builds the maze and forces a visual update to see the maze.
        /// </summary>
        private void generateMaze()
        {
            //don't queue up generation of mazes
            if (!my_generating)
            {
                my_generating = true;

                //track time taken during the algorithm
                long start_time = DateTime.Now.Ticks;

                //get dimensions we need
                my_rows = my_sizes[cmbSize.SelectedIndex];
                my_cols = my_rows;

                //helper variables
                int total_cells     = my_rows * my_cols;
                int row_walls       = my_rows - 1;
                int col_walls       = my_cols - 1;
                int total_ver_walls = my_rows * col_walls;
                int total_hor_walls = row_walls * my_cols;

                //initialize (progress maximum = preparings sets, preparing walls (hor/ver) and set unions)
                initializeGeneration(total_cells + total_hor_walls + total_ver_walls + total_cells - 1);

                //add all sets to the disjoint sets class
                for (int i = 0; i < total_cells; i++)
                {
                    my_d_sets.addSet(new DSInteger(i));
                    updateProgress();
                }

                //prepare vertical walls
                for (int i = 0; i < my_rows; i++)
                {
                    for (int j = 0; j < col_walls; j++)
                    {
                        int row_total = i * my_cols;
                        my_walls.add(new Wall(new DSInteger(row_total + j), new DSInteger(row_total + j + 1)));
                        updateProgress();
                    }
                }

                //prepare horizontal walls
                for (int i = 0; i < row_walls; i++)
                {
                    for (int j = 0; j < my_cols; j++)
                    {
                        int row_total = i * my_cols;
                        my_walls.add(new Wall(new DSInteger(row_total + j), new DSInteger(row_total + j + my_cols)));
                        updateProgress();
                    }
                }

                //scramble the ordering in the walls well (three times)
                Wall[] scramble = my_walls.toArray();
                Randomization.shuffleArray <Wall>(ref scramble);
                Randomization.shuffleArray <Wall>(ref scramble);
                Randomization.shuffleArray <Wall>(ref scramble);

                //prepare list of walls
                my_walls.clear();
                //add to linked list for cost-effective removal
                for (int i = 0; i < scramble.Length; i++)
                {
                    my_walls.add(scramble[i]);
                }

                int count = 0;
                //generate the maze
                Iterator <Wall> it = my_walls.iterator();
                while (it.hasNext())
                {
                    Wall w = it.next();

                    //if the cells don't belong to the same set
                    if (my_d_sets.find(w.cell_one) != my_d_sets.find(w.cell_two))
                    {
                        //union the sets and remove the wall
                        my_d_sets.union(w.cell_one, w.cell_two);
                        my_removed_walls.add(it.remove());
                        count++;
                        updateProgress();
                    }

                    //check if all cells belong to the same set
                    if (count == total_cells - 1) //once they are a tree will exist with n-1 edges (total_cells-1 edges)
                    {
                        break;
                    }
                }

                //cleanup
                cleanupGeneration(start_time, total_cells);

                my_generating = false;
            }
        }
コード例 #51
0
ファイル: Game1.cs プロジェクト: Zarnosch/3DPrototype
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            //Points
            points = 0;
            //Keyboard
            oldState = Keyboard.GetState();
            //Environment
            upperWorld = new GameEnvironment(Content, "upperWorld", new Vector3(0, 0, 0), new Vector3(0, 0, 0));
            //Grounds
            Ground testGround01 = new Ground(new Vector3(0, 0, 0), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround02 = new Ground(new Vector3(2, 0, 0), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround03 = new Ground(new Vector3(0, 0, 2), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround04 = new Ground(new Vector3(-2, 0, 0), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround05 = new Ground(new Vector3(0, 0, -2), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround06 = new Ground(new Vector3(-4, 0, 0), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround07 = new Ground(new Vector3(0, 0, 4), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround08 = new Ground(new Vector3(0, 0, -4), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround09 = new Ground(new Vector3(4, 0, 0), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround10 = new Ground(new Vector3(-2, 0, 2), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround11 = new Ground(new Vector3(2, 0, 2), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround12 = new Ground(new Vector3(2, 0, -2), new Vector3(0, 0, 0), "FloorPlate", Content);
            Ground testGround13 = new Ground(new Vector3(-2, 0, -2), new Vector3(0, 0, 0), "FloorPlate", Content);
            //Walls
            Wall testWall01 = new Wall(new Vector3(0, 0, 0), new Vector3(0, 0, 0), "WallLeft", Content);
            Wall testWall02 = new Wall(new Vector3(0, 0, 0), new Vector3(0, 0, 0), "WallBack", Content);
            Wall testWall03 = new Wall(new Vector3(0, 0, 0), new Vector3(0, 0, 0), "WallRight", Content);

            //Wall testWall04 = new Wall(new Vector3(0, 0, 0), new Vector3(0, 0, 0), "WallFront", Content);



            //Player
            player = new Player(new Vector3(0, 0, 0), new Vector3(0, 0, 0), "ApeMonster", Content);

            //Creatures

            //Collectables
            Collectable Vase01 = new Collectable(new Vector3(2, 1, 0), new Vector3(0, 0, 0), "Vase", Content);

            upperWorld.addWall(testWall01);
            upperWorld.addWall(testWall02);
            upperWorld.addWall(testWall03);
            //upperWorld.addWall(testWall04);
            upperWorld.addGround(testGround01);
            upperWorld.addGround(testGround02);
            upperWorld.addGround(testGround03);
            upperWorld.addGround(testGround04);
            upperWorld.addGround(testGround05);
            upperWorld.addGround(testGround06);
            upperWorld.addGround(testGround07);
            upperWorld.addGround(testGround08);
            upperWorld.addGround(testGround09);
            upperWorld.addGround(testGround10);
            upperWorld.addGround(testGround11);
            upperWorld.addGround(testGround12);
            upperWorld.addGround(testGround13);
            upperWorld.addCollectable(Vase01);



            Ground testGround = new Ground(new Vector3(0, 0, 4), new Vector3(0, 0, 0), "FloorPlate", Content);

            //upperWorld.addGround(3, 4, "FloorPlate");
            //upperWorld.addGround(testGround);
            base.Initialize();
        }
コード例 #52
0
        //---------------------- CONTROL EVENT HANDLERS -----------------------

        //draws the maze on a panel.
        private void pnlDraw_Paint(object sender, PaintEventArgs e)
        {
            //only draw if a maze has been generated.
            if (my_maze_generated)
            {
                Graphics g;
                if (my_buffer == null)
                {
                    //get dimensions/spacing for drawing
                    updateAfterResize();

                    my_buffer = new Bitmap(pnlDraw.Width, pnlDraw.Height);
                    g         = Graphics.FromImage(my_buffer);
                    Pen p = new Pen(new SolidBrush(Color.Black), 2.0f);

                    //draw outer edge
                    float right_x  = MAZE_OFFSET + my_draw_width;
                    float bottom_y = MAZE_OFFSET + my_draw_height;
                    g.DrawLine(p, MAZE_OFFSET, MAZE_OFFSET, right_x, MAZE_OFFSET);                   //top edge
                    g.DrawLine(p, right_x, MAZE_OFFSET, right_x, bottom_y - my_cell_height);         //right edge
                    g.DrawLine(p, MAZE_OFFSET, bottom_y, right_x, bottom_y);                         //bottom edge
                    g.DrawLine(p, MAZE_OFFSET, MAZE_OFFSET + my_cell_height, MAZE_OFFSET, bottom_y); //left edge

                    //make pen small for maze drawing
                    p = new Pen(new SolidBrush(Color.Black), 1.0f);

                    //draw walls
                    int             count = 0;
                    Iterator <Wall> it    = my_walls.iterator();
                    while (it.hasNext())
                    {
                        //update periodically
                        count++;
                        if (count % 1000 == 0)
                        {
                            Application.DoEvents();
                        }

                        Wall w = it.next();

                        float x1, x2, y1, y2;

                        //vertical wall
                        if (w.cell_one.value == w.cell_two.value - 1)
                        {
                            x1 = w.cell_two.value % my_cols;
                            y1 = w.cell_one.value / my_rows;

                            x2 = x1;
                            y2 = y1 + 1;
                        }
                        else //horizontal wall
                        {
                            x1 = w.cell_one.value % my_cols;
                            y1 = w.cell_two.value / my_rows;

                            x2 = x1 + 1;
                            y2 = y1;
                        }

                        g.DrawLine(p, MAZE_OFFSET + x1 * my_cell_width,
                                   MAZE_OFFSET + y1 * my_cell_height,
                                   MAZE_OFFSET + x2 * my_cell_width,
                                   MAZE_OFFSET + y2 * my_cell_height);
                    }
                }

                g = e.Graphics;
                g.DrawImage(my_buffer, new Rectangle(0, 0, pnlDraw.Width, pnlDraw.Height),
                            new Rectangle(0, 0, my_buffer.Width, my_buffer.Height), GraphicsUnit.Pixel);

                //draw solution if there is one
                drawSolution();
                drawUserSolution(true, null);
            }
        }
コード例 #53
0
 public void SetPerp(Wall w, Vector3 cent)
 {
     Perp = (Center - cent).normalized;
 }
コード例 #54
0
 public bool IsReachable(Wall w)
 {
     return(Vector3.Distance(w.transform.position, transform.position) < maxDistance);
 }
コード例 #55
0
 /// <summary>
 /// Deletes mesh colliders in the wall game object.
 /// </summary>
 public void DestroyWallMeshColliders()
 {
     wall = GetComponentInChildren <Wall>();
     wall.DestroyWallMeshColliders();
 }
コード例 #56
0
        //mapItems = new Wall(120, 210, new Blue(), mapAdapter, mapItems);

        //for (int i = 1; i <= 10; i++)
        //{
        //    mapItems = new Wall(i*10, 30, new Blue(), mapAdapter, mapItems);
        //}

        //PowerUpCrateBuildDirector director = new PowerUpCrateBuildDirector();
        //IPowerUpCrateBuilder builder = new QuantityCrateBuilder();
        //director.Construct(builder, 300, 300, mapAdapter, mapItems);
        //mapItems = builder.GetCrate();

        private async Task TryToCreateMap(Form form)
        {
            // MAP
            IMap      mapAdapter = new MapAdapter();
            IMapItems mapItems   = mapAdapter;

            // WALLS LOGIC
            mapItems = new Wall(0, 40, new Blue(), mapAdapter, mapItems);
            mapItems = new Wall(0, 542, new Blue(), mapAdapter, mapItems);
            mapItems = new Wall(0, 0, new Blue(), mapAdapter, mapItems);
            mapItems = new Wall(565, 0, new Blue(), mapAdapter, mapItems);


            PowerUpCrateBuildDirector director = new PowerUpCrateBuildDirector();
            PowerUpCrateBuilder       builder  = new QuantityCrateBuilder();
            PowerUpCrateBuilder       builders = new SpeedCrateBuilder();

            director.Construct(builder, 60, 60, mapAdapter, mapItems);
            mapItems = builder.GetCrate();

            director.Construct(builder, 60, 450, mapAdapter, mapItems);
            mapItems = builder.GetCrate();

            director.Construct(builders, 450, 450, mapAdapter, mapItems);
            mapItems = builders.GetCrate();
            mapItems.AddMapItem();

            Iterator mapIterator = mapAdapter.GetMap().GetIterator();
            int      wallIndex   = 0;

            //mapItems.AddMapItem();
            for (IGameObject gameObject = (IGameObject)mapIterator.First(); !mapIterator.IsDone(); gameObject = (IGameObject)mapIterator.Next())
            {
                if (gameObject is Crate)
                {
                    //IColor c = (Crate)VARIABLE.
                    form.Controls.Add(new PictureBox {
                        Name = "Crate", Location = new Point(gameObject.x, gameObject.y), Size = new Size(25, 25), BackColor = (gameObject as Crate).GetColor().GetColor()
                    });
                    Crate c = (Crate)gameObject;
                    c.Type = c.powerUp.getPowerUpType();
                    HttpResponseMessage response = await client.PostAsJsonAsync(cratesData, c);
                }
                else if (gameObject is Wall)
                {
                    if (wallIndex < 2)
                    {
                        form.Controls.Add(new PictureBox {
                            Name = "Wall", Location = new Point(gameObject.x, gameObject.y), Size = new Size(600, 20), BackColor = Color.DarkSlateBlue
                        });
                    }
                    else
                    {
                        form.Controls.Add(new PictureBox {
                            Name = "Wall", Location = new Point(gameObject.x, gameObject.y), Size = new Size(20, 600), BackColor = Color.DarkSlateBlue
                        });
                    }
                    roomWalls.Add((Wall)gameObject);
                    HttpResponseMessage response = await client.PostAsJsonAsync(wallsData, gameObject);

                    wallIndex++;
                }
            }
        }
コード例 #57
0
 public void Update(string id, Wall wallIn)
 {
     _wall.ReplaceOne(wall => wall.UserId == id, wallIn);
 }
コード例 #58
0
        public static bool GenRandomRoom(World world, float x, float y, Wall theWall)
        {
            try
            {
                Random rand = new Random();
                if (rand.Next(1, 60) != 1)
                {
                    return(false);
                }
                //Console.Out.WriteLine("Generating room...");
                List <string> dirs = new List <string>();
                for (int tx = -1; tx <= 1; tx++)
                {
                    for (int ty = -1; ty <= 1; ty++)
                    {
                        WmapTile targetTile = world.Map[(int)x + tx, (int)y + ty];
                        WmapTile thisTile   = world.Map[(int)x, (int)y];
                        if (targetTile.TileId == 0xff)
                        {
                            if (tx == -1 && ty == 0)
                            {
                                dirs.Add("left");
                            }
                            else if (tx == 1 && ty == 0)
                            {
                                dirs.Add("right");
                            }
                            else if (tx == 0 && ty == 1)
                            {
                                dirs.Add("down");
                            }
                            else if (tx == 0 && ty == -1)
                            {
                                dirs.Add("up");
                            }
                        }
                    }
                }
                if (dirs.Count < 1)
                {
                    return(false);
                }
                dirs.Shuffle();
                //Console.Out.WriteLine("Room direction: " + dirs.First());
                float mainX     = x;
                float mainY     = y;
                float entranceX = x;
                float entranceY = y;
                switch (dirs.First())
                {
                case "up":
                    mainX     = x - 6; mainY = y - 8;
                    entranceY = y - 1; break;

                case "down":
                    mainX     = x - 6; mainY = y + 1;
                    entranceY = y + 1; break;

                case "left":
                    mainX     = x - 12; mainY = y - 3;
                    entranceX = x - 1; break;

                case "right":
                    mainX     = x + 1; mainY = y - 3;
                    entranceX = x + 1; break;
                }
                List <WmapTile> addedTiles = new List <WmapTile>();
                for (int ty = (int)mainY; ty <= mainY + 7; ty++)
                {
                    for (int tx = (int)mainX; tx <= mainX + 11; tx++)
                    {
                        WmapTile tTile = world.Map[tx, ty];
                        if (tTile.TileId != 0xff || tTile.ObjType != 0)
                        {
                            //Console.Out.WriteLine("Found collision while generating room!");
                            return(false);
                        }
                        tTile.TileId = world.Map[(int)x, (int)y].TileId;
                        addedTiles.Add(tTile);
                    }
                }
                //Console.Out.WriteLine("Generated tiles, placing...");
                int tileNum = 0;
                for (int ty = (int)mainY; ty <= mainY + 7; ty++)
                {
                    for (int tx = (int)mainX; tx <= mainX + 11; tx++)
                    {
                        WmapTile ctile = addedTiles[tileNum];
                        if ((tx == (int)mainX || tx == (int)mainX + 11 || ty == (int)mainY || ty == (int)mainY + 7) && !(tx == entranceX && ty == entranceY))
                        {
                            //Console.Out.WriteLine("Placed wall");
                            Wall e = new Wall(theWall.ObjectType, XmlDatas.TypeToElement[theWall.ObjectType]);
                            e.Move(tx, ty);
                            world.EnterWorld(e);
                            ctile.ObjType = theWall.ObjectType;
                        }
                        else
                        {
                            //Console.Out.WriteLine("Placed treasure");
                            if (rand.Next(1, 30) == 1)
                            {
                                Entity e = Entity.Resolve(XmlDatas.IdToType["Coral Gift"]);
                                e.Move(tx + 0.5f, ty + 0.5f);
                                world.EnterWorld(e);
                                ctile.ObjType = XmlDatas.IdToType["Coral Gift"];
                            }
                        }
                        world.Map[tx, ty] = ctile;
                    }
                }
                //Console.Out.WriteLine("Placed tiles!");
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
コード例 #59
0
        /// <summary>
        /// There are five override methods for creating walls.
        /// We assume you are using metric template, where you have
        /// "Level 1" and "Level 2"
        /// cf. Developer Guide page 117
        /// </summary>
        public List <Wall> CreateWalls_v1()
        {
            // Hard coding the size of the house for simplicity
            double width = 16;
            double depth = 16;

            // Get the levels we want to work on.
            // Note: hard coding for simplicity. Modify here you use a different template.
            Level level1 = ElementFiltering.FindElement(_doc, typeof(Level), "Level 1", null) as Level;

            if (level1 == null)
            {
                TaskDialog.Show("Create walls",
                                "Cannot find (Level 1). Maybe you use a different template? Try with DefaultMetric.rte.");
                return(null);
            }

            Level level2 = ElementFiltering.FindElement(_doc, typeof(Level), "Level 2", null) as Level;

            if (level2 == null)
            {
                TaskDialog.Show("Create walls",
                                "Cannot find (Level 2). Maybe you use a different template? Try with DefaultMetric.rte.");
                return(null);
            }

            // Set four corner of walls.
            // 5th point is for combenience to loop through.
            double dx = width / 2.0;
            double dy = depth / 2.0;

            List <XYZ> pts = new List <XYZ>(5);

            pts.Add(new XYZ(-dx, -dy, 0.0));
            pts.Add(new XYZ(dx, -dy, 0.0));
            pts.Add(new XYZ(dx, dy, 0.0));
            pts.Add(new XYZ(-dx, dy, 0.0));
            pts.Add(pts[0]);

            // Flag for structural wall or not.
            bool isStructural = false;

            // Save walls we create.
            List <Wall> walls = new List <Wall>(4);

            // Loop through list of points and define four walls.
            for (int i = 0; i <= 3; i++)
            {
                // Define a base curve from two points.
                Line baseCurve = Line.CreateBound(pts[i], pts[i + 1]);
                // Create a wall using the one of overloaded methods.

                //Wall aWall = _doc.Create.NewWall(baseCurve, level1, isStructural); // 2012
                Wall aWall = Wall.Create(_doc, baseCurve, level1.Id, isStructural); // since 2013

                // Set the Top Constraint to Level 2
                aWall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).Set(level2.Id);
                // Save the wall.
                walls.Add(aWall);
            }

            // This is important. we need these lines to have shrinkwrap working.
            _doc.Regenerate();
            _doc.AutoJoinElements();

            return(walls);
        }
コード例 #60
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), "a wall", false)
                        as Wall;

            if (null == wall)
            {
                message
                    = "Please select a single wall element.";

                return(Result.Failed);
            }

            ICollection <ElementId> delIds = null;

            using (Transaction t = new Transaction(doc))
            {
                try
                {
                    t.Start("Temporary Wall Deletion");

                    delIds = doc.Delete(wall.Id);

                    t.RollBack();
                }
                catch (Exception ex)
                {
                    message = "Deletion failed: " + ex.Message;
                    t.RollBack();
                }
            }

            WallFoundation footing = null;

            foreach (ElementId id in delIds)
            {
                footing = doc.GetElement(id) as WallFoundation;

                if (null != footing)
                {
                    break;
                }
            }

            string s = Util.ElementDescription(wall);

            Util.InfoMsg((null == footing)
        ? string.Format("No footing found for {0}.", s)
        : string.Format("{0} has {1}.", s,
                        Util.ElementDescription(footing)));

            return(Result.Succeeded);
        }