Beispiel #1
0
        public Shape GetShape(int x, int y, int z)
        {
            Shape s;

            ShapeCollection.TryGetShape(GetShapeIDUnsafe(x, y, z), out s);
            return(s);
        }
Beispiel #2
0
        private Connector FindConnectableConnector(ShapeCollection shapes)
        {
            RectangleF t_area        = GetConnectableArea(LeftConnector);
            int        t_minDistance = m_autoShiftY + 999;
            Connector  t_connector   = null;

            foreach (Shape shape in shapes)
            {
                if (shape == this)
                {
                    continue;
                }
                if (shape.Connectors["Left"] == null)
                {
                    continue;
                }

                //when check the Y distance, only check the distance between edges of two shapes.
                RectangleF t_leftEdge = new RectangleF(shape.X, shape.Y, 0, shape.Height);
                if (!t_area.IntersectsWith(t_leftEdge))
                {
                    continue;
                }

                int t_dy = (int)(Math.Abs(LeftConnector.Location.Y - shape.Connectors["Left"].Location.Y)
                                 - (LeftConnector.BelongsTo.Height + shape.Height) / 2);
                if (t_dy < t_minDistance)
                {
                    t_minDistance = t_dy;
                    t_connector   = shape.Connectors["Left"];
                }
            }

            return(t_connector);
        }
Beispiel #3
0
        /// <summary>
        /// Updates the cursor during the tool actions.
        /// </summary>
        /// <param name="document">Informations transferred from DrawingPanel.</param>
        /// <param name="shapes">Shapes to manage.</param>
        /// <param name="point">Mouse point.</param>
        /// <returns>True if it is updated.</returns>
        public override bool UpdateCursor(IDocument document, ShapeCollection shapes, Point point)
        {
            foreach (IShape shape in shapes)
            {
                if (
                    shape.HitTest(point) != HitPositions.Center &&
                    shape.HitTest(point) != HitPositions.All &&
                    shape.HitTest(point) != HitPositions.None)
                {
                    if (MousePressed)
                    {
                        return(false);
                    }

                    return(base.UpdateCursor(document, shapes, point));
                }
                else if (shape.HitTest(MouseDownPoint) == HitPositions.Center && shape.Selected && MousePressed)
                {
                    document.ActiveCursor = Cursors.SizeAll;
                    return(true);
                }
            }

            if (MousePressed)
            {
                return(false);
            }

            document.ActiveCursor = Cursors.Default;
            return(false);
        }
Beispiel #4
0
        public SortShapesIntoZonesAction(ShapeCollection shapes, ZoneCollection zones)
            : base("Sort shapes into zones")
        {
            _zones = zones;
            if (_zones == null)
            {
                _zones = EditorManager.Scene.Zones;
            }

            foreach (ShapeBase shape in shapes)
            {
                Layer layer            = GetBestLayer(shape);
                bool  bIsExternalLayer = !EditorManager.Scene.Layers.Contains(shape.ParentLayer);

                if (layer == shape.ParentLayer) // do not re-assign, just leave in the layer
                {
                    continue;
                }
                if (layer == null)
                {
                    layer = GetBestLayer(shape); // see again why this failed (debug)
                    layer = GetUnAssignedLayer(shape);
                }

                if (bIsExternalLayer)
                {
                    shape.ChildIndex = -1;
                    this.Add(AddShapeAction.CreateAddShapeAction(shape, layer.Root, layer, false));
                }
                else
                {
                    this.Add(new SetShapeParentAction(shape, layer.Root));
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Add all the unique scripts from shape list to the dictionary
        /// </summary>
        private void AddScriptsRecursively(ShapeCollection shapes, ref Dictionary <string, int> scriptsDictionaryOut)
        {
            ShapeComponentType scriptComponentType = (ShapeComponentType)EditorManager.EngineManager.ComponentClassManager.GetCollectionType("VScriptComponent");

            foreach (ShapeBase shape in shapes)
            {
                if (shape.HasChildren())
                {
                    AddScriptsRecursively(shape.ChildCollection, ref scriptsDictionaryOut);
                }

                if (shape.Components == null)
                {
                    continue;
                }

                foreach (ShapeComponent comp in shape.Components)
                {
                    if (comp.CollectionType == scriptComponentType)
                    {
                        string script = comp.GetPropertyByName("ScriptFile").Value.ToString();

                        if (string.IsNullOrEmpty(script))
                        {
                            continue;
                        }

                        int references = 0;
                        scriptsDictionaryOut.TryGetValue(script, out references);
                        scriptsDictionaryOut[script] = references + 1;
                    }
                }
            }
        }
Beispiel #6
0
 public void Visit(ShapeCollection shapes)
 {
     using (var textReader = GetTextReader <Shape>())
     {
         Feed.Shapes = new ShapeCollection(GetEntityParser <Shape>().Parse(textReader).Cast <Shape>());
     }
 }
        public SortShapesIntoZonesAction(ShapeCollection shapes, ZoneCollection zones)
            : base("Sort shapes into zones")
        {
            _zones = zones;
              if (_zones == null)
            _zones = EditorManager.Scene.Zones;

              foreach (ShapeBase shape in shapes)
              {
            Layer layer = GetBestLayer(shape);
            bool bIsExternalLayer = !EditorManager.Scene.Layers.Contains(shape.ParentLayer);

            if (layer == shape.ParentLayer) // do not re-assign, just leave in the layer
              continue;
            if (layer == null)
            {
              layer = GetBestLayer(shape); // see again why this failed (debug)
              layer = GetUnAssignedLayer(shape);
            }

            if (bIsExternalLayer)
            {
              shape.ChildIndex = -1;
              this.Add(AddShapeAction.CreateAddShapeAction(shape, layer.Root, layer, false));
            }
            else
              this.Add(new SetShapeParentAction(shape, layer.Root));
              }
        }
        private void windowLoadedHandler()
        {
            // Load sections from database and display on canvas
            _storeSectionList = _db.TableStoreSection.GetAllStoreSections(_floorplanID);
            foreach (var section in _storeSectionList)
            {
                SectionShape loadedSectionShape = new SectionShape();
                loadedSectionShape.Top   = section.CoordinateY;
                loadedSectionShape.Left  = section.CoordinateX;
                loadedSectionShape.Shape = ShapeButtonCreator.CreateShapeForButton();
                loadedSectionShape.Name  = "Button" + section.StoreSectionID;
                loadedSectionShape.ID    = section.StoreSectionID;

                ShapeCollection.Add(loadedSectionShape);
            }

            // Load items from database and display on itemdatagrid
            ListOfItems.Populate(_db.TableItem.SearchItems(""));


            // Load floorplan and display on canvas
            _db.TableFloorplan.DownloadFloorplan(@"../../images/");

            FloorplanImage = null;
            ImageBrush       floorplanImgBrush = new ImageBrush();
            RefreshableImage refresh           = new RefreshableImage();
            BitmapImage      result            = refresh.Get("../../images/floorplan.jpg");

            floorplanImgBrush.ImageSource = result;
            FloorplanImage = floorplanImgBrush;
        }
        public void ShouldReturnCorrectSuperHappyCornersSumOfShapeCollection()
        {
            //Arrange
            var shapeCollection = new ShapeCollection();

            shapeCollection.Add(new Triangle(2, 3)
            {
                Mood = MoodTypes.SuperHappy
            });
            shapeCollection.Add(new Square(2)
            {
                Mood = MoodTypes.SuperHappy
            });
            shapeCollection.Add(new Rectangle(4, 3)
            {
                Mood = MoodTypes.SuperHappy
            });
            shapeCollection.Add(new Circle(5)
            {
                Mood = MoodTypes.SuperHappy
            });

            //Act
            //Assert
            Assert.AreEqual(shapeCollection.CornerSum(), 11 * 3 + 10);
        }
Beispiel #10
0
        private List <PositionedNode> GetNodesThatCollideWithShapeCollection(ShapeCollection sc, Dictionary <int, Dictionary <int, PositionedNode> > allNodes)
        {
            var returnValue = new List <PositionedNode>();

            if (sc != null && sc.Polygons != null)
            {
                foreach (Polygon polygon in sc.Polygons)
                {
                    polygon.ForceUpdateDependencies();
                }

                foreach (var xpair in allNodes)
                {
                    foreach (var ypair in xpair.Value)
                    {
                        PositionedNode node      = ypair.Value;
                        var            rectangle = new AxisAlignedRectangle {
                            Position = node.Position, ScaleX = 1, ScaleY = 1
                        };

                        if (sc.CollideAgainst(rectangle))
                        {
                            returnValue.Add(node);
                        }
                    }
                }
            }
            return(returnValue);
        }
Beispiel #11
0
        private void recentItem_Click(object sender, EventArgs e)
        {
            this.Focus();
            ToolStripMenuItem recentItem = sender as ToolStripMenuItem;

            if (recentItem == null)
            {
                return;
            }

            object obj = recentItem.Tag;

            if (obj == null)
            {
                return;
            }

            if (obj.GetType() == typeof(Layer) || obj.GetType() == typeof(V3DLayer))
            {
                IScene.SendLayerChangedEvent(new LayerChangedArgs((Layer)obj, null, LayerChangedArgs.Action.Selected));
            }
            else if (obj.GetType() == typeof(Zone))
            {
                IScene.SendZoneChangedEvent(new ZoneChangedArgs((Zone)obj, ZoneChangedArgs.Action.Selected));
            }
            else
            {
                ShapeCollection shapes = new ShapeCollection();
                shapes.Add((ShapeBase)obj);
                EditorManager.SelectedShapes = shapes;

                // Fire event manually in case selection was the same (so event will not get fired)
                EditorManager.OnShapeSelectionChanged(new ShapeSelectionChangedArgs(null, shapes));
            }
        }
Beispiel #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="points">ordered control points. If empty then this shape is empty.</param>
        /// <param name="buf">Buffer &gt;= 0</param>
        /// <param name="expandBufForLongitudeSkew">
        /// See <see cref="BufferedLine.ExpandBufForLongitudeSkew(IPoint, IPoint, double)"/>
        /// If true then the buffer for each segment is computed.
        /// </param>
        /// <param name="ctx"></param>
        public BufferedLineString(IList <IPoint> points, double buf, bool expandBufForLongitudeSkew,
                                  SpatialContext ctx)
        {
            this.buf = buf;

            if (!points.Any())
            {
                this.segments = ctx.MakeCollection(new List <IShape>());
            }
            else
            {
                List <IShape> segments = new List <IShape>(points.Count - 1);

                IPoint prevPoint = null;
                foreach (IPoint point in points)
                {
                    if (prevPoint != null)
                    {
                        double segBuf = buf;
                        if (expandBufForLongitudeSkew)
                        {
                            //TODO this is faulty in that it over-buffers.  See Issue#60.
                            segBuf = BufferedLine.ExpandBufForLongitudeSkew(prevPoint, point, buf);
                        }
                        segments.Add(new BufferedLine(prevPoint, point, segBuf, ctx));
                    }
                    prevPoint = point;
                }
                if (!segments.Any())
                {//TODO throw exception instead?
                    segments.Add(new BufferedLine(prevPoint, prevPoint, buf, ctx));
                }
                this.segments = ctx.MakeCollection(segments);
            }
        }
Beispiel #13
0
        public ShapeCollection Path(double inc)
        {
            ShapeCollection pc = new ShapeCollection();

            pc.AddShape(Outline(inc));
            return(pc);
        }
Beispiel #14
0
 private void RemoveShapes(ShapeCollection shapes)
 {
     for (int i = shapes.AxisAlignedRectangles.Count - 1; i >= 0; i--)
     {
         ShapeManager.Remove(shapes.AxisAlignedRectangles[i]);
     }
 }
Beispiel #15
0
        /// <summary>
        /// Updates the cursor during the tool actions.
        /// </summary>
        /// <param name="document">Informations transferred from DrawingPanel.</param>
        /// <param name="shapes">Shapes to manage.</param>
        /// <param name="point">Mouse point.</param>
        /// <returns>True if it is updated.</returns>
        public override bool UpdateCursor(IDocument document, ShapeCollection shapes, Point point)
        {
            bool updated = false;

            foreach (IShape shape in shapes)
            {
                if (shape.HitTest(MouseDownPoint) != HitPositions.None && shape.Selected && MousePressed)
                {
                    updated = true;
                }
                else
                {
                    updated = false;
                }
            }

            if (updated)
            {
                document.ActiveCursor = Cursors.SizeAll;
            }
            else
            {
                document.ActiveCursor = Cursors.Default;
            }

            return(updated);
        }
        public void ShouldReturnCorrectSuperHappyAreaSumOfShapeCollection()
        {
            //Arrange
            var shapeCollection = new ShapeCollection();

            shapeCollection.Add(new Triangle(2, 3)
            {
                Mood = MoodTypes.SuperHappy
            });                                                                     //3
            shapeCollection.Add(new Square(2)
            {
                Mood = MoodTypes.SuperHappy
            });                                                                //4
            shapeCollection.Add(new Square(3)
            {
                Mood = MoodTypes.SuperHappy
            });                                                                //9
            shapeCollection.Add(new Circle(5)
            {
                Mood = MoodTypes.SuperHappy
            });                                                                //78.5875

            //Act
            //Assert
            Assert.AreEqual(shapeCollection.AreaSum(), 94.5375f * 3);
        }
Beispiel #17
0
        /// <summary>
        /// Updates the cursor during the tool actions.
        /// </summary>
        /// <param name="document">Informations transferred from DrawingPanel.</param>
        /// <param name="shapes">Shapes to manage.</param>
        /// <param name="point">Mouse point.</param>
        /// <returns>True if it is updated.</returns>
        public override bool UpdateCursor(IDocument document, ShapeCollection shapes, Point point)
        {
            if (MousePressed)
            {
                return(false);
            }

            if (Select.LastSelectedShape == null)
            {
                return(false);
            }

            RectangleF[] markers = Select.LastSelectedShape.GetMarkers();
            foreach (RectangleF marker in markers)
            {
                if (marker.Contains(point))
                {
                    document.ActiveCursor = Cursors.Cross;
                    return(true);
                }
            }

            document.ActiveCursor = Cursors.Default;
            return(false);
        }
Beispiel #18
0
        private static void CreateEntitiesFromCircles(LayeredTileMap layeredTileMap, ShapeCollection shapeCollection)
        {
            var circles = shapeCollection.Circles;

            for (int i = circles.Count - 1; i > -1; i--)
            {
                var circle = circles[i];
                if (!string.IsNullOrEmpty(circle.Name) && layeredTileMap.ShapeProperties.ContainsKey(circle.Name))
                {
                    var properties           = layeredTileMap.ShapeProperties[circle.Name];
                    var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type");

                    var entityType = entityAddingProperty.Value as string;

                    if (!string.IsNullOrEmpty(entityType))
                    {
                        IEntityFactory factory = GetFactory(entityType);

                        var entity = factory.CreateNew(null) as PositionedObject;

                        entity.Name = circle.Name;
                        ApplyPropertiesTo(entity, properties, circle.Position);
                        shapeCollection.Circles.Remove(circle);

                        if (entity is Math.Geometry.ICollidable)
                        {
                            var entityCollision = (entity as Math.Geometry.ICollidable).Collision;
                            entityCollision.Circles.Add(circle);
                            circle.AttachTo(entity, false);
                        }
                    }
                }
            }
        }
        public override void Run()
        {
            Point p = new Point(10, 10);

            for (int k = 0; k < 10; k++)
            {
                mediator.GraphControl.AddBasicShape("Item " + k, p);
            }


            ShapeCollection nodes = mediator.GraphControl.Shapes;

            Connect(nodes[0], nodes[1], ConnectionEnd.NoEnds);
            Connect(nodes[0], nodes[2], ConnectionEnd.NoEnds);
            Connect(nodes[0], nodes[3], ConnectionEnd.NoEnds);
            Connect(nodes[2], nodes[4], ConnectionEnd.NoEnds);
            Connect(nodes[2], nodes[5], ConnectionEnd.NoEnds);
            Connect(nodes[3], nodes[6], ConnectionEnd.NoEnds);
            Connect(nodes[3], nodes[7], ConnectionEnd.NoEnds);
            Connect(nodes[7], nodes[8], ConnectionEnd.NoEnds);
            Connect(nodes[7], nodes[9], ConnectionEnd.NoEnds);



            mediator.SetLayoutAlgorithm(GraphLayoutAlgorithms.Tree);
            mediator.GraphControl.StartLayout();
            mediator.GraphControl.Focus();
            mediator.GraphControl.Invalidate(mediator.GraphControl.ClientRectangle);
            mediator.GraphControl.Update();
        }
        public static ShapeCollection ToShapeCollection(this TiledMapSave tiledMapSave, string layerName)
        {
            MapLayer mapLayer = null;

            if (!string.IsNullOrEmpty(layerName))
            {
                mapLayer = tiledMapSave.Layers.FirstOrDefault(l => l.Name.Equals(layerName));
            }
            var shapes = new ShapeCollection();

            if ((mapLayer != null && !mapLayer.IsVisible && mapLayer.VisibleBehavior == TMXGlueLib.TiledMapSave.LayerVisibleBehavior.Skip) ||
                tiledMapSave.objectgroup == null || tiledMapSave.objectgroup.Count == 0)
            {
                return(shapes);
            }

            foreach (mapObjectgroup group in tiledMapSave.objectgroup)
            {
                if (group.@object != null && !string.IsNullOrEmpty(group.Name) && (string.IsNullOrEmpty(layerName) || group.Name.Equals(layerName)))
                {
                    foreach (mapObjectgroupObject @object in group.@object)
                    {
                        AddShapeToShapeCollection(@object, shapes);
                    }
                }
            }
            return(shapes);
        }
Beispiel #21
0
        /// <summary>
        /// Ungroup in a single shape all selected shapes.
        /// </summary>
        /// <param name="document">Informations transferred from DrawingPanel.</param>
        public static void Ungroup(IDocument document)
        {
            ShapeCollection selectedShapes = Select.GetSelectedShapes(document.Shapes);

            foreach (IShape shape in selectedShapes)
            {
                CompositeShape group = shape as CompositeShape;
                if (group == null)
                {
                    continue;
                }

                document.Shapes.Remove(group);

                foreach (IShape grouppedShape in group.Shapes)
                {
                    grouppedShape.Selected = true;
                    document.Shapes.Add(grouppedShape);
                }

                while (group.Shapes.Count != 0)
                {
                    group.Shapes.RemoveAt(0);
                }
            }
        }
        public static void AddShapeToShapeCollection(mapObjectgroupObject @object, ShapeCollection shapes)
        {
            //////////////////////////Early out////////////////////////////////
            ///November 8th, 2015
            ///Jesse Crafts-Finch
            ///If a polygon has a gid, and therefore an image associate with it, it will be turned into a spritesave, not a polygon.
            if (@object.gid != null)
            {
                return;
            }
            ////////////////////////End Early Out/////////////////////////////////
            Polygon polygon;
            AxisAlignedRectangle rectangle;
            Circle circle;

            ConvertTiledObjectToFrbShape(@object, out polygon, out rectangle, out circle);

            if (polygon != null)
            {
                shapes.Polygons.Add(polygon);
            }
            if (rectangle != null)
            {
                shapes.AxisAlignedRectangles.Add(rectangle);
            }
            if (circle != null)
            {
                shapes.Circles.Add(circle);
            }
        }
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            List <object> items = new List <object>();

            foreach (object v in values)
            {
                if (v is ShapeCollection)
                {
                    ShapeCollection shapes = v as ShapeCollection;
                    shapeCollections.Add(shapes);
                    int id = shapeCollections.Count - 1;
                    // the ID of a ShapeCollection is formatted as "parent-id:self-id"
                    // the OD of all other shapes is formatted as "parent-id"
                    shapes.ID = string.Format("{0}:{1}", shapes.ID, id);

                    foreach (Shape shape in shapes)
                    {
                        shape.ID = id.ToString();
                    }

                    items.Add(new ChildShapes(v as ShapeCollection));
                }
                else
                {
                    items.Add(v);
                }
            }

            return(items);
        }
Beispiel #24
0
        /// <summary>
        /// 布局线路 
        /// </summary>
        /// <param name="pshape"></param>
        void layeroutmx(BaseShape pshape)
        {
            ShapeCollection childshapes = pshape.GetChildShapes();

            if (pshape is MX1Shape)
            {
                MX1Shape mx1 = pshape as MX1Shape;
                mx1.Width           = Math.Max(mx1.Width, 40 * childshapes.Count);
                mx1.ConnectorNumber = childshapes.Count;
            }
            foreach (Connector cr in pshape.Connectors)
            {
                if (cr.ConnectorLocation == ConnectorLocation.South)
                {
                    foreach (Connection cn in cr.Connections)
                    {
                        Connector crto = cn.From;
                        if (cn.From == cr)
                        {
                            crto = cn.To;
                        }
                        if (!movedshapes.Contains(crto.BelongsTo))
                        {
                            movedshapes.Add(crto.BelongsTo);
                            PointF pf1  = crto.BelongsTo.ConnectionPoint(crto);
                            PointF pf2  = cr.BelongsTo.ConnectionPoint(cr);
                            float  offx = pf2.X - pf1.X;
                            float  offy = 50;
                            crto.BelongsTo.X += offx;
                            crto.BelongsTo.Y += offy;
                        }
                    }
                }
            }
            float xlright = 0;  //线路右边范围
            int   xlnum   = -1; //有设备的线路

            foreach (BaseShape sp1 in childshapes)
            {
                if (!layershapes.Contains(sp1))
                {
                    layershapes.Add(sp1);
                    {
                        if (sp1.GetChildShapes().Count > 1)
                        {
                            if (xlright > sp1.X)
                            {
                                sp1.X = xlright + 30;
                            }
                            if (sp1.DeviceType != "01")
                            {
                                sp1.Y -= xlnum * 3; xlnum++;
                            }
                            layeroutsb(sp1, ref xlright);
                        }
                    }
                }
            }
            curWidth = Math.Max(xlright, pshape.X + pshape.Width);
        }
Beispiel #25
0
        /// <summary>
        /// Handle mouse double click on script list
        /// </summary>
        private void OnMouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                usedByMenuItem.DropDownItems.Clear();

                string selectedScript = scriptsListControl.SelectedItems[0].Text;

                string sceneScript = "";
                bool   found       = ScriptManager.GetSceneScriptFile(ref sceneScript);

                if (found && selectedScript == sceneScript)
                {
                    ToolStripMenuItem item = new ToolStripMenuItem("Scene Script", null, new EventHandler(ScriptListSubmenuItemMainLayer_Click));
                    usedByMenuItem.DropDownItems.Add(item);
                }
                else
                {
                    ShapeCollection shapes = EditorManager.Scene.GetShapesByScript(selectedScript);

                    foreach (ShapeBase shape in shapes)
                    {
                        ToolStripMenuItem item = new ToolStripMenuItem(shape.ShapeName, null, new EventHandler(ScriptListSubmenuItem_Click));
                        item.Tag = shape.UniqueID;

                        usedByMenuItem.DropDownItems.Add(item);
                    }
                }

                usedByMenuItem.Enabled = (usedByMenuItem.DropDownItems.Count > 0);
                scriptListContextMenu.Show(scriptsListControl, e.Location);
            }
        }
        private void FlagEntityRecursive(ShapeCollection siblings, GroupAction actions, int iGroupID)
        {
            EditorManager.Actions.StartGroup("EnumerateEntities");

            int iSibling = 0;

            foreach (ShapeBase shape in siblings)
            {
                EntityShape entity = shape as EntityShape;
                if (entity == null || !entity.Modifiable)
                {
                    continue;
                }

                // Simply change the name to communicate a change to the user
                EditorManager.Actions.Add(new SetShapeNameAction(entity, string.Format("Group_{0}_Sibling_{1}", iGroupID, iSibling)));

                // When editing properties of custom entity classes use a SetPropertyAction
                // e.g.:
                // DynamicPropertyCollection properties = entity.EntityProperties;
                // actions.Add(new SetPropertyAction(properties, "PropertyName", string.Format("PropertyValue")));

                // Recurse through children
                FlagEntityRecursive(shape.ChildCollection, actions, iGroupID + 1);

                iSibling++; // Increase sibling index for neighboring entities
            }

            EditorManager.Actions.EndGroup();
        }
Beispiel #27
0
 internal SCSlideLayout(SCSlideMaster slideMaster, SlideLayoutPart sldLayoutPart)
 {
     _slideMaster    = slideMaster;
     SlideLayoutPart = sldLayoutPart;
     _shapes         = new ResettableLazy <ShapeCollection>(() =>
                                                            ShapeCollection.CreateForSlideLayout(sldLayoutPart.SlideLayout.CommonSlideData.ShapeTree, this));
 }
Beispiel #28
0
 public Decorator()
     : base(ControlTag + (++count), string.Empty)
 {
     IsFocusable = false;
     CanRaiseEvents = false;
     Shapes = new ShapeCollection(1);
 }
        public static void SaveScheme(ShapeCollection shapes, int sldW, int sldH, string filePath)
        {
            var bitmap = GetBitmap(shapes, sldW, sldH);

            bitmap.Save(filePath);
            bitmap.Dispose();
        }
Beispiel #30
0
        /// <summary>
        /// Overridden save function
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public override bool Save(string filename)
        {
            PrefabDesc      prefab = new PrefabDesc(filename);
            ShapeCollection all    = new ShapeCollection();

            // the following shapes go into the prefab: lightgrid boxes, lights
            foreach (ShapeBase shape in this.FilteredSupplier)
            {
                all.Add(shape);
            }

            foreach (ShapeBase shape in this.FilteredLights)
            {
                if (!all.Contains(shape))
                {
                    all.Add(shape);
                }
            }

            if (!prefab.CreateFromInstances(all, Vector3F.Zero, false, false))
            {
                return(false);
            }
            return(prefab.SaveToFile(null));
        }
Beispiel #31
0
 public void Remove(ShapeCollection shapeCollection)
 {
     foreach (var item in shapeCollection.AxisAlignedCubes)
     {
         Remove(item);
     }
     foreach (var item in shapeCollection.AxisAlignedRectangles)
     {
         Remove(item);
     }
     foreach (var item in shapeCollection.Capsule2Ds)
     {
         Remove(item);
     }
     foreach (var item in shapeCollection.Circles)
     {
         Remove(item);
     }
     foreach (var item in shapeCollection.Lines)
     {
         Remove(item);
     }
     foreach (var item in shapeCollection.Polygons)
     {
         Remove(item);
     }
     foreach (var item in shapeCollection.Spheres)
     {
         Remove(item);
     }
 }
        /// <summary>
        ///     Saves in PNG.
        /// </summary>
        /// <param name="shapes"></param>
        /// <param name="sldW"></param>
        /// <param name="sldH"></param>
        /// <param name="stream"></param>
        public static void SaveScheme(ShapeCollection shapes, int sldW, int sldH, Stream stream)
        {
            var bitmap = GetBitmap(shapes, sldW, sldH);

            bitmap.Save(stream, ImageFormat.Png);
            bitmap.Dispose();
        }
        public static bool IsInLineOfSight(Vector3 position1, Vector3 position2, float collisionThreshold, ShapeCollection shapeCollection)
        {
            Segment segment = new Segment(new FlatRedBall.Math.Geometry.Point(ref position1),
                new FlatRedBall.Math.Geometry.Point(ref position2));

            for(int i = 0; i < shapeCollection.Polygons.Count; i++)
            {
                Polygon polygon = shapeCollection.Polygons[i];

                if (polygon.CollideAgainst(segment) ||
                    (collisionThreshold > 0 && segment.DistanceTo(polygon) < collisionThreshold))
                {
                    return false;
                }
            }

            for (int i = 0; i < shapeCollection.AxisAlignedRectangles.Count; i++)
            {
                AxisAlignedRectangle rectangle = shapeCollection.AxisAlignedRectangles[i];

                FlatRedBall.Math.Geometry.Point throwaway;

                if (rectangle.Intersects(segment, out throwaway) ||
                    (collisionThreshold > 0 && segment.DistanceTo(rectangle) < collisionThreshold))
                {
                    return false;
                }
            }

            for (int i = 0; i < shapeCollection.Circles.Count; i++)
            {
                Circle circle = shapeCollection.Circles[i];               

                if (segment.DistanceTo(circle) < collisionThreshold)
                {
                    return false;
                }
            }

#if DEBUG
            if (shapeCollection.Capsule2Ds.Count != 0)
            {
                throw new Exception("IsInLineOfSight does not support ShapeCollections with Capsule2Ds");
            }
#endif

            for (int i = 0; i < shapeCollection.Lines.Count; i++)
            {
                Line line = shapeCollection.Lines[i];

                if (segment.DistanceTo(line.AsSegment()) < collisionThreshold)
                {
                    return false;
                }
            }

            return true;

        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="shapes"></param>
 /// <param name="mode"></param>
 /// <param name="includeShapes"></param>
 public DropToFloorAction(ShapeCollection shapes, Shape3D.DropToFloorMode mode, Vector3F axis, bool includeShapes)
     : base("Drop to Floor")
 {
     _shapes = shapes;
       _mode = mode;
       _axis = axis;
       _includeShapes = includeShapes;
 }
 public ShapeContainer()
 {
     ShapeType = RoundedBox.Creator;
     LineType = Line.Creator;
     ShapeList = new ShapeCollection ();
     back = new Bitmap (Width, Height);
     current = new Bitmap (Width, Height);
     InitializeComponent ();
 }
Beispiel #36
0
 public ControlSelector()
     : base(ControlTag + ++count, ControlTag)
 {
     ApplyControlDescription(StyleManager.GetControlDescription(ControlTag));
     ApplyStatusChanges = false;
     handleSize = new Size(12, 12);
     sensibleArea = new Size(handleSize.Width, handleSize.Height);
     Shapes = new ShapeCollection(8);
 }
Beispiel #37
0
 public DecoratorButton()
     : base(ControlTag + (++count), ControlTag)
 {
     IsFocusable = false;
     Shapes = new ShapeCollection(2);
     decorator = new Decorator
                     {
                         Parent = this,
                         DecorationType = DecorationType.DownsideTriangle,
                     };
 }
        public SpriterObject(string contentManagerName, bool addToManagers)
        {
            LayerProvidedByContainer = null;
            Animating = false;
            SecondsIn = 0f;
            CurrentKeyFrameIndex = 0;
            ScaleX = 1.0f;
            ScaleY = 1.0f;
            Animations = new Dictionary<string, SpriterObjectAnimation>(1);

            ContentManagerName = contentManagerName;
            InitializeSpriterObject(addToManagers);
            ObjectList = new List<PositionedObject>();
            CollisionBoxes = new ShapeCollection();
        }
        /// <summary>
        /// Overridden save function
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public override bool Save(string filename)
        {
            PrefabDesc prefab = new PrefabDesc(filename);
              ShapeCollection all = new ShapeCollection();

              // the following shapes go into the prefab: lightgrid boxes, lights
              foreach (ShapeBase shape in this.FilteredSupplier)
            all.Add(shape);

              foreach (ShapeBase shape in this.FilteredLights)
            if (!all.Contains(shape))
              all.Add(shape);

              if (!prefab.CreateFromInstances(all, Vector3F.Zero, false, false))
            return false;
              return prefab.SaveToFile(null);
        }
        private void reportlist_DoubleClick(object sender, System.EventArgs e)
        {
            ShapeBase shape = (ShapeBase)reportlist.SelectedItems[0].Tag;
              ShapeCollection shapes = new ShapeCollection();
              shapes.Add(shape);

              EditorManager.SelectedShapes = shapes;

              //jump to selection
              BoundingBox mergedBox = EditorManager.SelectedShapes.BoundingBox;
              if (!mergedBox.Valid)
            return;

              // make it local again
              Vector3F center = mergedBox.Center;
              mergedBox.Translate(-center);

              EditorManager.ActiveView.LookAt(center, mergedBox);
        }
Beispiel #41
0
        public Model()
        {
            mAmbience = new Ambience(this);
            //listen to events
            AttachToAmbience(mAmbience);

            //here I'll have to work on the scene graph
            this.mShapes = new ShapeCollection();

            //the page collection
            mPages = new CollectionBase<IPage>();

            //the default page
            mDefaultPage = new Page("Default Page");
            mDefaultPage.OnEntityAdded += new EventHandler<EntityEventArgs>(mDefaultPage_OnEntityAdded);
            mDefaultPage.OnEntityRemoved += new EventHandler<EntityEventArgs>(mDefaultPage_OnEntityRemoved);
            mDefaultPage.OnClear += new EventHandler(mDefaultPage_OnClear);
            mPages.Add(mDefaultPage);
            //initially the current page is the one and only default page
            mCurrentPage = mDefaultPage;

            //the paintables
            mPaintables = new CollectionBase<IDiagramEntity>();
        }
        /// <summary>
        /// This function converts all shapes from the old SoundPlugin to the corresponding shapes of the new FmodPlugin
        /// </summary>
        void MigrateToFmodShapes()
        {
            // If old Sound plugin is not loaded, don't do anything
              IEditorPluginModule soundPlugin = EditorManager.GetPluginByName("SoundEditorPlugin.EditorPlugin");
              if (soundPlugin == null || !soundPlugin.Initialized)
            return;

              // collect all sound specific shapes
              ShapeCollection soundShapes = new ShapeCollection();
              foreach (Layer layer in EditorManager.Scene.Layers)
            if (layer.Modifiable && layer.Loaded)
              AddSoundShapesRecursive(soundShapes, layer.Root);

              if (soundShapes.Count == 0)
            return;

              // prompt a dialog
              DialogResult res = EditorManager.ShowMessageBox("Shapes from old Sound Plugin have been found in loaded layers.\n\nShould these be permanently converted to the corresponding shapes of the Fmod Plugin?", "Old Sound Plugin and Fmod Plugin are both loaded", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
              if (res != DialogResult.Yes)
            return;

              ShapeCollection newShapes = new ShapeCollection();
              int iConvertedCount = 0;
              if (soundShapes.Count > 0)
              {
            GroupAction actions = new GroupAction("Migrate Sound shapes");
            foreach (ShapeObject3D oldShape in soundShapes)
            {
              ShapeObject3D newShape = null;
              if (oldShape.GetType().FullName == "SoundEditorPlugin.SoundShape")
              {
            newShape = new FmodSoundShape(oldShape.ShapeName);
            MigrateSoundShapeProperties(oldShape, (FmodSoundShape)newShape);

            actions.Add(AddShapeAction.CreateAddShapeAction(newShape, oldShape.Parent, oldShape.ParentLayer, false));

            actions.Add(new MigrateSoundLinksAction(oldShape, (FmodSoundShape)newShape));
            actions.Add(new MigrateChildrenAction(oldShape, newShape));
            actions.Add(RemoveShapeAction.CreateRemoveShapeAction(oldShape));
            newShapes.Add(newShape);
              }
              else if (oldShape.GetType().FullName == "SoundEditorPlugin.SoundCollisionShape")
              {
            newShape = new FmodCollisionMeshShape(oldShape.ShapeName);
            MigrateSoundCollisionShapeProperties(oldShape, (FmodCollisionMeshShape)newShape);

            actions.Add(AddShapeAction.CreateAddShapeAction(newShape, oldShape.Parent, oldShape.ParentLayer, false));
            actions.Add(new MigrateChildrenAction(oldShape, newShape));
            actions.Add(RemoveShapeAction.CreateRemoveShapeAction(oldShape));
            newShapes.Add(newShape);
              }
              if (newShape == null)
            continue;

              iConvertedCount++;
            }

            // EditorManager.Actions.Add() is not used, in order to prevent a undo of the conversion
            actions.Do();
              }

              // ensure, that all migrated childs have valid engine instances
              foreach (ShapeBase shape in newShapes)
            foreach (ShapeBase child in shape.ChildCollection)
              child.ReCreateEngineInstance(true);

              EditorManager.ShowMessageBox(iConvertedCount.ToString() + " Shape(s) have been successfully converted.", "Sound to Fmod shapes conversion", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
 private string ShapeNameList(ShapeCollection shapes)
 {
     string txt = "";
       foreach (ShapeBase shape in shapes)
     txt += shape.ShapePath + "\r\n";
       return txt;
 }
 public static void UnloadStaticContent()
 {
     IsStaticContentLoaded = false;
     mHasRegisteredUnload = false;
     if (Capacitor != null)
     {
         Capacitor = null;
     }
     if (SceneFile2 != null)
     {
         SceneFile2.RemoveFromManagers(ContentManagerName != "Global");
         SceneFile2 = null;
     }
     if (CapacitorCollisionFile != null)
     {
         CapacitorCollisionFile.RemoveFromManagers(ContentManagerName != "Global");
         CapacitorCollisionFile = null;
     }
 }
        void AddSoundShapesRecursive(ShapeCollection shapeList, ShapeBase parent)
        {
            if (parent.ShapeVirtualCounter > 0 || !parent.Modifiable)
            return;

              ShapeBase soundShape = parent as ShapeObject3D;
              if (soundShape != null && (soundShape.GetType().FullName == "SoundEditorPlugin.SoundShape" || soundShape.GetType().FullName == "SoundEditorPlugin.SoundCollisionShape"))
            shapeList.Add(soundShape);

              if (parent.HasChildren())
            foreach (ShapeBase shape in parent.ChildCollection)
              AddSoundShapesRecursive(shapeList, shape);
        }
Beispiel #46
0
 public static void LoadStaticContent(string contentManagerName)
 {
     ContentManagerName = contentManagerName;
     #if DEBUG
     if (contentManagerName == FlatRedBallServices.GlobalContentManager)
     {
         HasBeenLoadedWithGlobalContentManager = true;
     }
     else if (HasBeenLoadedWithGlobalContentManager)
     {
         throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global.  This can lead to a lot of bugs");
     }
     #endif
     if (IsStaticContentLoaded == false)
     {
         IsStaticContentLoaded = true;
         lock (mLockObject)
         {
             if (!mHasRegisteredUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
             {
                 FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("PlayerStaticUnload", UnloadStaticContent);
                 mHasRegisteredUnload = true;
             }
         }
         bool registerUnload = false;
         if (!FlatRedBallServices.IsLoaded<FlatRedBall.Math.Geometry.ShapeCollection>(@"content/entities/player/shapecollectionfile.shcx", ContentManagerName))
         {
             registerUnload = true;
         }
         ShapeCollectionFile = FlatRedBallServices.Load<FlatRedBall.Math.Geometry.ShapeCollection>(@"content/entities/player/shapecollectionfile.shcx", ContentManagerName);
         if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/player/mech.png", ContentManagerName))
         {
             registerUnload = true;
         }
         mech = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/player/mech.png", ContentManagerName);
         if (!FlatRedBallServices.IsLoaded<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/player/redball.bmp", ContentManagerName))
         {
             registerUnload = true;
         }
         redball = FlatRedBallServices.Load<Microsoft.Xna.Framework.Graphics.Texture2D>(@"content/entities/player/redball.bmp", ContentManagerName);
         if (!FlatRedBallServices.IsLoaded<FlatRedBall.ManagedSpriteGroups.SpriteRig>(@"content/entities/player/ballman.srgx", ContentManagerName))
         {
             registerUnload = true;
         }
         ballMan = FlatRedBallServices.Load<FlatRedBall.ManagedSpriteGroups.SpriteRig>(@"content/entities/player/ballman.srgx", ContentManagerName);
         if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
         {
             lock (mLockObject)
             {
                 if (!mHasRegisteredUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
                 {
                     FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("PlayerStaticUnload", UnloadStaticContent);
                     mHasRegisteredUnload = true;
                 }
             }
         }
         CustomLoadStaticContent(contentManagerName);
     }
 }
 public static void LoadStaticContent(string contentManagerName)
 {
     ContentManagerName = contentManagerName;
     #if DEBUG
     if (contentManagerName == FlatRedBallServices.GlobalContentManager)
     {
         HasBeenLoadedWithGlobalContentManager = true;
     }
     else if (HasBeenLoadedWithGlobalContentManager)
     {
         throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global.  This can lead to a lot of bugs");
     }
     #endif
     if (IsStaticContentLoaded == false)
     {
         IsStaticContentLoaded = true;
         lock (mLockObject)
         {
             if (!mHasRegisteredUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
             {
                 FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("CapacitorPlatformCopyCopyStaticUnload", UnloadStaticContent);
                 mHasRegisteredUnload = true;
             }
         }
         bool registerUnload = false;
         if (!FlatRedBallServices.IsLoaded<Texture2D>(@"content/entities/capacitorplatform/capacitor.png", ContentManagerName))
         {
             registerUnload = true;
         }
         Capacitor = FlatRedBallServices.Load<Texture2D>(@"content/entities/capacitorplatform/capacitor.png", ContentManagerName);
         if (!FlatRedBallServices.IsLoaded<Scene>(@"content/entities/capacitorplatform/scenefile2.scnx", ContentManagerName))
         {
             registerUnload = true;
         }
         SceneFile2 = FlatRedBallServices.Load<Scene>(@"content/entities/capacitorplatform/scenefile2.scnx", ContentManagerName);
         if (!FlatRedBallServices.IsLoaded<ShapeCollection>(@"content/entities/capacitorplatform/capacitorcollisionfile.shcx", ContentManagerName))
         {
             registerUnload = true;
         }
         CapacitorCollisionFile = FlatRedBallServices.Load<ShapeCollection>(@"content/entities/capacitorplatform/capacitorcollisionfile.shcx", ContentManagerName);
         if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
         {
             lock (mLockObject)
             {
                 if (!mHasRegisteredUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
                 {
                     FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("CapacitorPlatformCopyCopyStaticUnload", UnloadStaticContent);
                     mHasRegisteredUnload = true;
                 }
             }
         }
         CustomLoadStaticContent(contentManagerName);
     }
 }
        void CommonInit(ShapeCollection shapes, Shape3D.DropToFloorMode mode, Vector3F axis, bool includeShapes)
        {
            for (int i=0;i<shapes.Count;i++)
              {
            Shape3D shape = shapes[i] as Shape3D;
            if (shape==null || !shape.Traceable || !shape.Modifiable) continue;

            ShapeCollection colliderShapes = null;
            if (includeShapes)
            {
              colliderShapes = EditorManager.Scene.AllShapesOfType(typeof(Shape3D), true);
              if (colliderShapes.Contains(shape))
            colliderShapes.Remove(shape);
            }

            // use a replacement action? (e.g. billboards rather want to drop every single instance)
            IAction custom = shape.GetCustomDropToFloorAction(mode, axis, colliderShapes);
            if (custom != null)
            {
              this.Add(custom);
              continue;
            }

            float fHeight = EditorApp.ActiveView.EngineManager.GetDropToFloorHeight(shape,mode,axis,colliderShapes);
            if (fHeight==0.0f) continue;
            this.Add(new MoveShapeAction(shape,shape.Position, shape.Position + axis * fHeight));
              }
        }
        public BillboardDropToFloorAction(BillboardGroupShape shape, BillboardInstance[] instances, Shape3D.DropToFloorMode mode, Vector3F axis, ShapeCollection colliderShapes)
        {
            _instances = instances;
              if (_instances == null)
            _instances = shape.Instances;

              _shape = shape;
              _mode = mode;
              _oldHeights = new float[_instances.Length];
              _newHeights = new float[_instances.Length];

              for (int i = 0; i < _instances.Length; i++)
            _oldHeights[i] = _instances[i].Z;
              _shape.EngineMesh.GetDropToFloorHeights(_shape, _instances, _mode, axis, colliderShapes);
              for (int i = 0; i < _instances.Length; i++)
            _newHeights[i] = _instances[i].Z;
        }
 public override IAction GetCustomDropToFloorAction(Shape3D.DropToFloorMode mode, Vector3F axis, ShapeCollection colliderShapes)
 {
     if (!HasEngineInstance() || Instances.Length < 1)
     return base.GetCustomDropToFloorAction(mode, axis, colliderShapes);
       return new BillboardDropToFloorAction(this, null, mode, axis, colliderShapes); // all instances
 }
 public override void OnPostPrefabCreation(ShapeCollection allRootShapes, PrefabDesc prefab)
 {
     base.OnPostPrefabCreation(allRootShapes, prefab);
       if (_entityProperties != null)
       {
     if (!string.IsNullOrEmpty(_pendingEntityPropertyString))
       _entityProperties.ParseParameterString(_pendingEntityPropertyString, ",");
     _entityProperties.OnPostPrefabCreation(allRootShapes, prefab);
       }
       _pendingEntityPropertyString = null;
 }
        void AddShapesRecursive(ShapeCollection target, ShapeBase parent, Rectangle2D selection )
        {
            if (parent.ShapeVirtualCounter==0 && parent.CanCopyPaste && (parent is Shape3D))
              {
            Shape3D shape3D = (Shape3D)parent;
            if (selection.IsInside(shape3D.x, shape3D.y))
            {
              target.Add(parent);
              //return; // iterate through children as well - the CloneForClipboard will take care of handling duplicates
            }
              }

              if (parent.HasChildren())
              {
            ShapeCollection children = parent.ChildCollection;
            foreach (ShapeBase child in children)
              AddShapesRecursive(target, child, selection);
              }
        }
        public override void Perform2DViewAction(Scene2DView view, GroupAction parent, string action)
        {
            base.Perform2DViewAction(view, parent, action);

              // sector range - used by all actions
              BoundingBox selBox = view.SelectionMarqueeWorldBox;
              int x1, y1, x2, y2;
              Config.GetSectorIndicesAtWorldPos(selBox.vMin, out x1, out y1);
              Config.GetSectorIndicesAtWorldPos(selBox.vMax, out x2, out y2);
              Config.ClampSectorRange(ref x1, ref y1, ref x2, ref y2);

              if (action == VA_EDIT_SECTOR_PROPERTIES)
              {
             ShapeCollection shapes = new ShapeCollection();
             for (int sy = y1; sy <= y2; sy++)
               for (int sx = x1; sx <= x2; sx++)
             shapes.Add(GetZone(sx, sy));
             EditorManager.SelectedShapes = shapes;
              }
              else if (action == VA_IMPORT_HEIGHTMAP)
              {
            ImportHeightmapDDS import = new ImportHeightmapDDS();
            x1 *= Config.SamplesPerSectorX;
            y1 *= Config.SamplesPerSectorY;
            x2 = (x2 + 1) * Config.SamplesPerSectorX;
            y2 = (y2 + 1) * Config.SamplesPerSectorY;
            ApplyHeightmapFilterDlg.RunFilter(import, x1, y1, x2, y2);
              }
              else if (action == VA_REPAIR_SECTORS)
              {
            EditorManager.Progress.ShowProgressDialog("Repair Sectors");
            EngineTerrain.EnsureSectorRangeLoaded(x1, y1, x2, y2, (int)SectorEditorFlags_e.AnythingDirty, true, true, EditorManager.Progress);
            EditorManager.Progress.HideProgressDialog();
              }
              else if (action == VA_RELOAD_SECTORS)
              {
            EditorManager.Progress.ShowProgressDialog("Reload Sectors");
            EngineTerrain.ReloadSectorRange(x1, y1, x2, y2, false, EditorManager.Progress);
            EditorManager.Progress.HideProgressDialog();
            EditorManager.ActiveView.UpdateView(false);
              }
        }
        /// <summary>
        /// Creates a clipboard object that holds the clone of relevant terrain data
        /// </summary>
        /// <param name="selection">Selection to clone. Can be null to use TerrainEditor.CurrentSelection</param>
        /// <returns>The clipboard data object</returns>
        public ITerrainClipboardObject CopySelection(TerrainSelection selection)
        {
            if (!HasEngineInstance())
            return null;
              if (selection == null)
            selection = TerrainEditor.CurrentSelection;
              if (selection == null || !selection.Valid)
            return null;
              ITerrainClipboardObject data = EngineTerrain.CopySelection(selection);

              // add shapes to clone
              if ((selection.SelectionFilter & TerrainSelection.SelectionFilter_e.Shapes) != 0)
              {
            ShapeCollection shapesOnTerrain = new ShapeCollection();
            ShapeCollection roots = EditorManager.Scene.RootShapes;
            Rectangle2D rect = selection.WorldSpaceExtent;
            foreach (ShapeBase root in roots)
              AddShapesRecursive(shapesOnTerrain, root, rect);
            if (shapesOnTerrain.Count > 0)
            {
              data.ShapesToPaste = shapesOnTerrain.CloneForClipboard();

              // remap position xy to [0..1] range inside the selection
              float fInvX = 1.0f / rect.GetSizeX();
              float fInvY = 1.0f / rect.GetSizeY();
              foreach (Shape3D shape in data.ShapesToPaste)
            shape.Position = new Vector3F((shape.x - rect.X1) * fInvX, (shape.y - rect.Y1) * fInvY, shape.z);
            }
              }

              return data;
        }
        public static void gatherGeometricShapes(ref ShapeCollection shapesOut, ref int numEntitiesOut, ref int numStaticMeshesOut, ref int numTerrainsOut, ref int numCarversOut, ref int numSeedPointsOut, ref int numLocalSettingsOut)
        {
            // Grab all shapes from all layers
              foreach (Layer layer in EditorManager.Scene.Layers)
              {
            if (layer.GetIncludeInNavMesh())
            {
              recursivelyAddShapes(layer.Root.ChildCollection, ref shapesOut);
            }
              }

              // calculate some statistics
              foreach (ShapeBase shape in shapesOut)
              {
            // check if the shape to be added is in the same zone as the HavokNavMeshShape's parentZone
            // note that if HavokNavMeshShape is not in a zone, then it will only include other shapes that aren't in zones also.

            Shape3D shape3d = shape as Shape3D;
            Shape3D.eNavMeshUsage usage = shape3d.GetNavMeshUsage();
            if (usage != Shape3D.eNavMeshUsage.ExcludeFromNavMesh)
            {
              if (shape is EntityShape)
              {
            numEntitiesOut++;
              }
              else if (shape is StaticMeshShape)
              {
            numStaticMeshesOut++;
              }
              else if (shape is TerrainShape)
              {
            numTerrainsOut++;
              }
            }
              }

              ShapeCollection carvers = EditorManager.Scene.AllShapesOfType(typeof(HavokNavMeshCarverShape));
              numCarversOut = carvers.Count;

              ShapeCollection seedPoints = EditorManager.Scene.AllShapesOfType(typeof(HavokNavMeshSeedPointShape));
              numSeedPointsOut = seedPoints.Count;

              // Add local settings
              ShapeCollection localSettings = EditorManager.Scene.AllShapesOfType(typeof(HavokNavMeshLocalSettingsShape));
              numLocalSettingsOut = localSettings.Count;
        }
Beispiel #56
0
 public static void UnloadStaticContent()
 {
     IsStaticContentLoaded = false;
     mHasRegisteredUnload = false;
     if (ShapeCollectionFile != null)
     {
         ShapeCollectionFile.RemoveFromManagers(ContentManagerName != "Global");
         ShapeCollectionFile= null;
     }
     if (mech != null)
     {
         mech= null;
     }
     if (redball != null)
     {
         redball= null;
     }
     if (ballMan != null)
     {
         ballMan.Destroy();
         ballMan= null;
     }
 }
Beispiel #57
0
 public void AddShape(ShapeCollection shapeCollection)
 {
     throw new System.NotImplementedException();
 }
        public static void recursivelyAddShapes(ShapeCollection siblings, ref ShapeCollection shapesOut)
        {
            foreach (ShapeBase shape in siblings)
              {
            recursivelyAddShapes(shape.ChildCollection, ref shapesOut);

            if (shape is StaticMeshShape || shape is EntityShape || shape is TerrainShape
            #if !HK_ANARCHY
            || shape is DecorationGroupShape
            #endif
            #if USE_SPEEDTREE
            || shape is SpeedTree5GroupShape
            || shape is Speedtree6GroupShape
            #endif
            )
            {
              shapesOut.Add(shape);
            }
              }
        }
Beispiel #59
0
			public EditBuffer()
			{
				action = EditAction.None;
				initialMousePos = Geometry.InvalidPoint;
				pasteCount = 0;
				shapes = new ShapeCollection();
				connections = new List<ShapeConnection>();
			}
        /// <summary>
        /// Build nav mesh button
        /// </summary>
        private void BuildNavMesh_Click(object sender, EventArgs e)
        {
            CSharpFramework.Scene.ZoneCollection zones = EditorManager.Scene.Zones.ShallowClone();
              GroupAction groupLoadAction = new GroupAction("Load all zones");

              foreach (CSharpFramework.Scene.Zone zone in zones)
            groupLoadAction.Add(new CSharpFramework.Actions.SetZoneLoadedStatusAction(zone, true));
              groupLoadAction.Do();

              {
            // for printing out stats
            BuildStatisticsRichTextBox.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
            Font oldFont = BuildStatisticsRichTextBox.SelectionFont;
            Font newFontPlain = new Font(oldFont, oldFont.Style & ~FontStyle.Bold);
            Font newFontBold = new Font(oldFont, oldFont.Style | FontStyle.Bold);

            ShapeCollection navMeshShapes = EditorManager.Scene.AllShapesOfType(typeof(HavokNavMeshShape));

            // gather all geometry once (divide by zone later)
            ShapeCollection staticGeometries = new ShapeCollection();
            {
              int numEntities = 0, numStaticMeshes = 0, numTerrains = 0;
              int numCarvers = 0, numSeedPoints = 0, numLocalSettings = 0;
              gatherGeometricShapes(ref staticGeometries, ref numEntities, ref numStaticMeshes, ref numTerrains, ref numCarvers, ref numSeedPoints, ref numLocalSettings);

              //
              // print out some debug info
              //
              BuildStatisticsRichTextBox.SelectionStart = BuildStatisticsRichTextBox.Text.Length;
              {
            String inputGeometryLabel = "Input Geometry";
            BuildStatisticsRichTextBox.Text = inputGeometryLabel;
              }
              BuildStatisticsRichTextBox.SelectionLength = BuildStatisticsRichTextBox.Text.Length - BuildStatisticsRichTextBox.SelectionStart;
              BuildStatisticsRichTextBox.SelectionFont = newFontBold;

              {
            String inputGlobalGeometryInfo = "\n\nStatic meshes\t: " + numStaticMeshes + "\nTerrains\t\t: " + numTerrains + "\nEntities\t\t: " + numEntities +
                "\n\nCarvers\t\t: " + numCarvers + "\nSeed points\t: " + numSeedPoints + "\nLocal settings\t: " + numLocalSettings + "\n\n";
            BuildStatisticsRichTextBox.Text += inputGlobalGeometryInfo;
              }
              BuildStatisticsRichTextBox.SelectionLength = BuildStatisticsRichTextBox.Text.Length - BuildStatisticsRichTextBox.SelectionStart;
              BuildStatisticsRichTextBox.SelectionFont = newFontPlain;

              //
              // debug info end
              //
            }

            // actually build the navmeshes here
            int numBuiltNavMeshShapes = 0;
            bool allCompleted = true;
            foreach (HavokNavMeshShape shape in navMeshShapes)
            {
              int numGeometryVertices = 0, numGeometryTriangles = 0;

              // note that the build function only uses static geometries that lie in the same zone!
              bool built = shape.Build(staticGeometries, ref numGeometryVertices, ref numGeometryTriangles);

              if (built)
              {
            numBuiltNavMeshShapes++;

            //
            // print out some debug info
            //
            BuildStatisticsRichTextBox.SelectionStart = BuildStatisticsRichTextBox.Text.Length;
            {
              String navMeshLabel = "\n\nNav Mesh #" + numBuiltNavMeshShapes;
              BuildStatisticsRichTextBox.Text += navMeshLabel;
            }
            BuildStatisticsRichTextBox.SelectionLength = BuildStatisticsRichTextBox.Text.Length - BuildStatisticsRichTextBox.SelectionStart;
            BuildStatisticsRichTextBox.SelectionFont = newFontBold;

            BuildStatisticsRichTextBox.SelectionStart = BuildStatisticsRichTextBox.Text.Length;
            {
              String inputPerNavMeshGeometryInfo = "\nTotal input triangles\t: " + numGeometryTriangles + "\nTotal input vertices\t: " + numGeometryVertices + "\n\n";
              int facesSize = shape.GetNavMeshFaceSize() * shape.GetNumNavMeshFaces();
              int edgesSize = shape.GetNavMeshEdgeSize() * shape.GetNumNavMeshEdges();
              int verticesSize = shape.GetNavMeshVertexSize() * shape.GetNumNavMeshVertices();
              int totalSize = shape.GetNavMeshStructSize() + facesSize + edgesSize + verticesSize;

              String navMeshInfo = "\nTotal size\t\t: " + totalSize +
                  " bytes\nFaces ( " + shape.GetNumNavMeshFaces() + " )\t: " + facesSize +
                  "\nEdges ( " + shape.GetNumNavMeshEdges() + " )\t: " + edgesSize +
                  "\nVertices ( " + shape.GetNumNavMeshVertices() + " )\t: " + verticesSize;
              BuildStatisticsRichTextBox.Text += navMeshInfo;
            }
            BuildStatisticsRichTextBox.SelectionLength = BuildStatisticsRichTextBox.Text.Length - BuildStatisticsRichTextBox.SelectionStart;
            BuildStatisticsRichTextBox.SelectionFont = newFontPlain;

            //
            // debug info end
            //
              }
              else
              {
              allCompleted = false;
              break;
              }
            }

            if (allCompleted)
            {
            // stitch the navmeshes together
            using (HavokAiManaged.EngineInstanceHavokNavMeshLinker linker = new HavokAiManaged.EngineInstanceHavokNavMeshLinker())
            {
                // collect all navmeshes at once
                foreach (HavokNavMeshShape shape in navMeshShapes)
                {
                    if (shape.HasEngineInstance())
                    {
                        linker.AddNavMeshShape(shape._engineInstance.GetNativeObject());

                        HavokNavMeshGlobalSettings globalSettings = GetGlobalSettings(shape.NavMeshGlobalSettingsKey);
                        if (globalSettings != null)
                        {
                          linker.m_linkEdgeMatchTolerance = globalSettings.LinkEdgeMatchTolerance;
                          linker.m_linkMaxStepHeight = globalSettings.LinkMaxStepHeight;
                          linker.m_linkMaxSeparation = globalSettings.LinkMaxSeparation;
                          linker.m_linkMaxOverhang = globalSettings.LinkMaxOverhang;

                          linker.m_linkCosPlanarAlignmentAngle = (float)Math.Cos(globalSettings.LinkPlanarAlignmentAngle / 180.0f * 3.14159f);
                          linker.m_linkCosVerticalAlignmentAngle = (float)Math.Cos(globalSettings.LinkVerticalAlignmentAngle / 180.0f * 3.14159f);
                          linker.m_linkMinEdgeOverlap = globalSettings.LinkMinEdgeOverlap;
                        }
                    }
                }

                // link them together
                linker.LinkNavMeshes();
            }

            // save it to disk (separate from next loop because we want to guarantee that we don't serialize out some runtime only data)
            foreach (HavokNavMeshShape shape in navMeshShapes)
            {
                shape.SaveNavMeshesToFile();
            }

            // finally load it into the havok ai world
            foreach (HavokNavMeshShape shape in navMeshShapes)
            {
                shape.AddNavMeshToWorld();
            }

            if (EditorManager.InPlayingMode && WantPhysicsConnection())
            {
                HavokAiManaged.ManagedModule.SetConnectToPhysicsWorld(true, false);
            }
            }

            EnableBuildButtonAsterisk(false);
            //EnableStreamingDependentControls(shape.GetNumNavMeshes()>1);
              }

              groupLoadAction.Undo();

              EditorManager.ActiveView.UpdateView(true);
        }