void IInitializable.Initialize()
        {
            m_controlInfo = new ControlInfo("DesignView", "DesignView", StandardControlGroup.CenterPermanent);
            m_controlHostService.RegisterControl(m_designView.HostControl, m_controlInfo, this);

            Application.ApplicationExit += delegate
            {
                Util3D.Shutdown();
                GameEngine.Shutdown();
            };

            GameEngine.RefreshView += delegate
            {
                m_designView.InvalidateViews();
            };

            m_gameDocumentRegistry.DocumentAdded   += new EventHandler <ItemInsertedEventArgs <IGameDocument> >(m_gameDocumentRegistry_DocumentAdded);
            m_gameDocumentRegistry.DocumentRemoved += new EventHandler <ItemRemovedEventArgs <IGameDocument> >(m_gameDocumentRegistry_DocumentRemoved);

            string ns = m_schemaLoader.NameSpace;

            // register GridRenderer on grid child.
            DomNodeType gridType = m_schemaLoader.TypeCollection.GetNodeType(ns, "gridType");

            gridType.Define(new ExtensionInfo <GridRenderer>());

            // register NativeGameWorldAdapter on game type.
            m_schemaLoader.GameType.Define(new ExtensionInfo <NativeGameWorldAdapter>());

            // parse schema annotation.
            foreach (DomNodeType domType in m_schemaLoader.TypeCollection.GetNodeTypes())
            {
                IEnumerable <XmlNode> annotations = domType.GetTagLocal <IEnumerable <XmlNode> >();
                if (annotations == null)
                {
                    continue;
                }


                // collect all the properties that only exist in native side.
                List <NativeAttributeInfo> nativeAttribs = new List <NativeAttributeInfo>();

                foreach (XmlNode annot in annotations)
                {
                    XmlElement elm = annot as XmlElement;
                    if (elm.LocalName == NativeAnnotations.NativeType)
                    {
                        string typeName = elm.GetAttribute(NativeAnnotations.NativeName);
                        domType.SetTag(NativeAnnotations.NativeType, GameEngine.GetObjectTypeId(typeName));
                        if (domType.IsAbstract == false)
                        {
                            domType.Define(new ExtensionInfo <NativeObjectAdapter>());
                        }
                    }
                    else if (elm.LocalName == NativeAnnotations.NativeProperty)
                    {
                        // find a prop name and added to the attribute.


                        string nativePropName = elm.GetAttribute(NativeAnnotations.NativeName);
                        string attribName     = elm.GetAttribute(NativeAnnotations.Name);
                        uint   typeId         = (uint)domType.GetTag(NativeAnnotations.NativeType);
                        uint   propId         = GameEngine.GetObjectPropertyId(typeId, nativePropName);
                        if (!string.IsNullOrEmpty(attribName))
                        {
                            AttributeInfo attribInfo = domType.GetAttributeInfo(elm.GetAttribute(NativeAnnotations.Name));
                            attribInfo.SetTag(NativeAnnotations.NativeProperty, propId);
                        }
                        else
                        {
                            NativeAttributeInfo attribInfo = new NativeAttributeInfo(domType, nativePropName, typeId, propId);
                            nativeAttribs.Add(attribInfo);
                        }
                    }
                    else if (elm.LocalName == NativeAnnotations.NativeElement)
                    {
                        ChildInfo info   = domType.GetChildInfo(elm.GetAttribute(NativeAnnotations.Name));
                        uint      typeId = (uint)domType.GetTag(NativeAnnotations.NativeType);
                        string    name   = elm.GetAttribute(NativeAnnotations.NativeName);
                        info.SetTag(NativeAnnotations.NativeElement, GameEngine.GetObjectChildListId(typeId, name));
                    }
                }

                if (nativeAttribs.Count > 0)
                {
                    domType.SetTag(nativeAttribs.ToArray());
                }
            }


            // register BoundableObject
            m_schemaLoader.GameObjectType.Define(new ExtensionInfo <BoundableObject>());
            m_schemaLoader.GameObjectFolderType.Define(new ExtensionInfo <BoundableObject>());



            #region code to handle gameObjectFolder

            {
                // This code is fragile and need to be updated whenever
                // any relevant part of the schema changes.
                // purpose:
                // gameObjectFolderType does not exist in C++
                // this code will map gameObjectFolderType to gameObjectGroupType.
                DomNodeType gobFolderType = m_schemaLoader.GameObjectFolderType;
                DomNodeType groupType     = m_schemaLoader.GameObjectGroupType;

                // map native bound attrib from gameObject to GobFolder
                NativeAttributeInfo[] nativeAttribs = m_schemaLoader.GameObjectType.GetTag <NativeAttributeInfo[]>();
                foreach (var attrib in nativeAttribs)
                {
                    if (attrib.Name == "Bounds")
                    {
                        gobFolderType.SetTag(new NativeAttributeInfo[] { attrib });
                        break;
                    }
                }

                // map type.
                gobFolderType.Define(new ExtensionInfo <NativeObjectAdapter>());
                gobFolderType.SetTag(NativeAnnotations.NativeType, groupType.GetTag(NativeAnnotations.NativeType));

                // map all native attributes of gameObjectGroup to gameFolder
                foreach (AttributeInfo srcAttrib in groupType.Attributes)
                {
                    object nativeIdObject = srcAttrib.GetTag(NativeAnnotations.NativeProperty);
                    if (nativeIdObject == null)
                    {
                        continue;
                    }
                    AttributeInfo destAttrib = gobFolderType.GetAttributeInfo(srcAttrib.Name);
                    if (destAttrib == null)
                    {
                        continue;
                    }
                    destAttrib.SetTag(NativeAnnotations.NativeProperty, nativeIdObject);
                    destAttrib.SetTag(NativeAnnotations.MappedAttribute, srcAttrib);
                }

                // map native element from gameObjectGroupType to gameObjectFolderType.
                object gobsId = groupType.GetChildInfo("gameObject").GetTag(NativeAnnotations.NativeElement);
                foreach (ChildInfo srcChildInfo in gobFolderType.Children)
                {
                    if (srcChildInfo.IsList)
                    {
                        srcChildInfo.SetTag(NativeAnnotations.NativeElement, gobsId);
                    }
                }

                m_schemaLoader.GameType.GetChildInfo("gameObjectFolder").SetTag(NativeAnnotations.NativeElement, gobsId);
            }

            #endregion
        }
Exemple #2
0
        public void Render(GUILayer.SimpleRenderingContext context, Camera cam)
        {
            GameEngine.SetRendererFlag(context, BasicRendererFlags.WireFrame);
            IGrid grid = this.As <IGrid>();

            if (grid.Visible == false)
            {
                return;
            }

            float s = grid.Size;

            Matrix4F scale = new Matrix4F();

            scale.Scale(new Vec3F(s, s, s));

            Matrix4F gridXform = new Matrix4F();

            if (cam.Frustum.IsOrtho)
            {
                float     dist = cam.ViewMatrix.Translation.Z;
                ViewTypes vt   = cam.ViewType;
                if (vt == ViewTypes.Top)
                {
                    gridXform.Translation
                        = new Vec3F(0, dist, 0);
                }
                else if (vt == ViewTypes.Bottom)
                {
                    gridXform.Translation
                        = new Vec3F(0, -dist, 0);
                }
                else if (vt == ViewTypes.Right)
                {
                    gridXform.RotZ(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(dist, 0, 0);
                }
                else if (vt == ViewTypes.Left)
                {
                    gridXform.RotZ(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(-dist, 0, 0);
                }
                else if (vt == ViewTypes.Front)
                {
                    gridXform.RotX(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(0, 0, dist);
                }
                else if (vt == ViewTypes.Back)
                {
                    gridXform.RotX(MathHelper.PiOver2);
                    gridXform.Translation
                        = new Vec3F(0, 0, -dist);
                }
                gridXform.Mul(scale, gridXform);
            }
            else
            {
                Matrix4F trans = new Matrix4F();
                trans.Translation = new Vec3F(0, grid.Height, 0);
                gridXform         = Matrix4F.Multiply(scale, trans);
            }

            GameEngine.DrawPrimitive(context, PrimitiveType.LineList, m_gridVBId, 0, m_gridVertexCount, Color.LightGray,
                                     Matrix4F.Multiply(gridXform, cam.AxisSystem));

            GameEngine.DrawPrimitive(context, PrimitiveType.LineList, m_basisAxesVBId, 0, m_basisAxesVertexCount, Color.White,
                                     gridXform);
        }
Exemple #3
0
        void IInitializable.Initialize()
        {
            m_controlInfo = new ControlInfo("DesignView", "DesignView", StandardControlGroup.CenterPermanent);
            m_controlHostService.RegisterControl(m_designView.HostControl, m_controlInfo, this);

            Application.ApplicationExit += delegate
            {
                Util3D.Shutdown();
                GameEngine.Shutdown();
            };

            GameEngine.RefreshView += (sender, e) => m_designView.InvalidateViews();

            m_gameDocumentRegistry.DocumentAdded   += m_gameDocumentRegistry_DocumentAdded;
            m_gameDocumentRegistry.DocumentRemoved += m_gameDocumentRegistry_DocumentRemoved;

            string ns = m_schemaLoader.NameSpace;

            // register GridRenderer on grid child.
            DomNodeType gridType = m_schemaLoader.TypeCollection.GetNodeType(ns, "gridType");

            gridType.Define(new ExtensionInfo <GridRenderer>());

            // register NativeGameWorldAdapter on game type.
            m_schemaLoader.GameType.Define(new ExtensionInfo <NativeDocumentAdapter>());

            // parse schema annotation.
            foreach (DomNodeType domType in m_schemaLoader.TypeCollection.GetNodeTypes())
            {
                var topLevelAnnotations = domType.GetTagLocal <IEnumerable <XmlNode> >();
                if (topLevelAnnotations == null)
                {
                    continue;
                }

                // First, go through and interpret the annotations that are not inherited
                foreach (XmlNode annot in topLevelAnnotations)
                {
                    XmlElement elm = annot as XmlElement;
                    if (elm.LocalName == NativeAnnotations.NativeType)
                    {
                        string typeName = elm.GetAttribute(NativeAnnotations.NativeName);
                        domType.SetTag(NativeAnnotations.NativeType, GameEngine.GetObjectTypeId(typeName));
                        if (domType.IsAbstract == false)
                        {
                            domType.Define(new ExtensionInfo <NativeObjectAdapter>());
                        }
                    }
                    else if (elm.LocalName == NativeAnnotations.NativeDocumentType)
                    {
                        string typeName = elm.GetAttribute(NativeAnnotations.NativeName);
                        domType.SetTag(NativeAnnotations.NativeDocumentType, GameEngine.GetDocumentTypeId(typeName));
                        if (domType.IsAbstract == false)
                        {
                            domType.Define(new ExtensionInfo <NativeDocumentAdapter>());
                        }
                    }
                }

                if (domType.GetTag(NativeAnnotations.NativeType) == null)
                {
                    continue;
                }
                uint typeId          = (uint)domType.GetTag(NativeAnnotations.NativeType);
                bool isBoundableType = false;

                // Now, go through and interpret annotations that can be inheritted from base clases.
                // Sometimes a native property can be inheritted from a base class. In this model, we
                // will create a separate "property id" for each concrete class. When a property is
                // inheritted, the "property ids" for each type in the inheritance chain will be different
                // and unrelated.

                List <NativeAttributeInfo> nativeAttribs = new List <NativeAttributeInfo>();
                foreach (var inherittedType in domType.Lineage)
                {
                    var annotations = inherittedType.GetTagLocal <IEnumerable <XmlNode> >();
                    if (annotations == null)
                    {
                        continue;
                    }

                    foreach (XmlNode annot in annotations)
                    {
                        XmlElement elm = annot as XmlElement;
                        if (elm.LocalName == NativeAnnotations.NativeProperty)
                        {
                            // find a prop name and added to the attribute.
                            string nativePropName = elm.GetAttribute(NativeAnnotations.NativeName);
                            string attribName     = elm.GetAttribute(NativeAnnotations.Name);
                            uint   propId         = GameEngine.GetObjectPropertyId(typeId, nativePropName);
                            if (!string.IsNullOrEmpty(attribName))
                            {
                                AttributeInfo attribInfo = domType.GetAttributeInfo(elm.GetAttribute(NativeAnnotations.Name));
                                attribInfo.SetTag(NativeAnnotations.NativeProperty, propId);
                            }
                            else
                            {
                                NativeAttributeInfo attribInfo = new NativeAttributeInfo(domType, nativePropName, typeId, propId);
                                nativeAttribs.Add(attribInfo);
                            }

                            if (nativePropName == "Bounds" || nativePropName == "LocalBounds")
                            {
                                isBoundableType = true;
                            }
                        }
                        else if (elm.LocalName == NativeAnnotations.NativeElement)
                        {
                            ChildInfo info = domType.GetChildInfo(elm.GetAttribute(NativeAnnotations.Name));
                            string    name = elm.GetAttribute(NativeAnnotations.NativeName);
                            info.SetTag(NativeAnnotations.NativeElement, GameEngine.GetObjectChildListId(typeId, name));
                        }
                        else if (elm.LocalName == NativeAnnotations.NativeVis)
                        {
                            using (var transfer = new NativeObjectAdapter.NativePropertyTransfer())
                            {
                                using (var stream = transfer.CreateStream())
                                    foreach (var a in elm.Attributes)
                                    {
                                        var attrib = a as XmlAttribute;
                                        if (attrib.Name == "geo")
                                        {
                                            NativeObjectAdapter.PushAttribute(
                                                0,
                                                typeof(string), 1,
                                                attrib.Value,
                                                transfer.Properties, stream);
                                        }
                                    }

                                GameEngine.SetTypeAnnotation(typeId, "vis", transfer.Properties);
                            }
                        }
                    }
                }

                if (nativeAttribs.Count > 0)
                {
                    domType.SetTag(nativeAttribs.ToArray());
                }

                if (isBoundableType && domType.IsAbstract == false)
                {
                    domType.Define(new ExtensionInfo <BoundableObject>());
                }
            }


            // register BoundableObject
            m_schemaLoader.GameObjectFolderType.Define(new ExtensionInfo <BoundableObject>());   // doesn't have a bound native attributes -- is this really intended?s

            #region code to handle gameObjectFolder

            {
                // This code is fragile and need to be updated whenever
                // any relevant part of the schema changes.
                // purpose:
                // gameObjectFolderType does not exist in C++
                // this code will map gameObjectFolderType to gameObjectGroupType.
                DomNodeType gobFolderType = m_schemaLoader.GameObjectFolderType;
                DomNodeType groupType     = m_schemaLoader.GameObjectGroupType;

                // map native bound attrib from gameObject to GobFolder
                NativeAttributeInfo[] nativeAttribs = m_schemaLoader.GameObjectType.GetTag <NativeAttributeInfo[]>();
                foreach (var attrib in nativeAttribs)
                {
                    if (attrib.Name == "Bounds")
                    {
                        gobFolderType.SetTag(new NativeAttributeInfo[] { attrib });
                        break;
                    }
                }

                // map type.
                //      XLE --> Separate GameObjectFolder type from GameObjectGroup type
                // gobFolderType.Define(new ExtensionInfo<NativeObjectAdapter>());
                // gobFolderType.SetTag(NativeAnnotations.NativeType, groupType.GetTag(NativeAnnotations.NativeType));

                // map all native attributes of gameObjectGroup to gameFolder
                foreach (AttributeInfo srcAttrib in groupType.Attributes)
                {
                    object nativeIdObject = srcAttrib.GetTag(NativeAnnotations.NativeProperty);
                    if (nativeIdObject == null)
                    {
                        continue;
                    }
                    AttributeInfo destAttrib = gobFolderType.GetAttributeInfo(srcAttrib.Name);
                    if (destAttrib == null)
                    {
                        continue;
                    }
                    destAttrib.SetTag(NativeAnnotations.NativeProperty, nativeIdObject);
                    destAttrib.SetTag(NativeAnnotations.MappedAttribute, srcAttrib);
                }

                // map native element from gameObjectGroupType to gameObjectFolderType.
                object gobsId = groupType.GetChildInfo("object").GetTag(NativeAnnotations.NativeElement);
                foreach (ChildInfo srcChildInfo in gobFolderType.Children)
                {
                    if (srcChildInfo.IsList)
                    {
                        srcChildInfo.SetTag(NativeAnnotations.NativeElement, gobsId);
                    }
                }

                m_schemaLoader.GameType.GetChildInfo("gameObjectFolder").SetTag(NativeAnnotations.NativeElement, gobsId);
            }

            #endregion

            // set up scripting bindings
            if (m_scriptingService != null)
            {
                m_scriptingService.SetVariable("cv", new GUILayer.TweakableBridge());
            }
        }
Exemple #4
0
 public GameEngine()
 {
     CriticalError = s_notInitialized;
     s_inist       = this;
     GameEngine.Init();
 }
Exemple #5
0
            // render the scene.
            public void Render()
            {
                if (GameEngine.IsInError ||
                    SurfaceId == 0 ||
                    Visible == false ||
                    Width == 0 ||
                    Height == 0 ||
                    Game == null)
                {
                    return;
                }


                NativeObjectAdapter gameLevel = GameEngine.GetGameLevel();

                try
                {
                    NativeObjectAdapter game = Game.As <NativeObjectAdapter>();
                    GameEngine.SetGameLevel(game);
                    GameEngine.SetRenderState(m_renderState);
                    if (Game.RootGameObjectFolder.GameObjects.Count > 0)
                    {
                        GameEngine.Update(0, 0, true);
                    }

                    if (ResetCamera)
                    {
                        // save view type
                        ViewTypes viewtype = this.ViewType;
                        ViewType = ViewTypes.Perspective;
                        Size       sz        = ClientSize;
                        float      aspect    = (float)sz.Width / (float)sz.Height;
                        IBoundable boundable = Game.RootGameObjectFolder.Cast <IBoundable>();
                        Sce.Atf.VectorMath.Sphere3F sphere = boundable.BoundingBox.ToSphere();
                        float nearZ = sphere.Radius * 0.01f;
                        nearZ = Math.Min(0.1f, nearZ);
                        Camera.SetPerspective(
                            (float)Math.PI / 4,
                            aspect,
                            nearZ,
                            sphere.Radius * 10.0f);

                        Vec3F camPos = sphere.Center + new Vec3F(sphere.Radius, sphere.Radius, sphere.Radius) * 1.2f;
                        Camera.Set(camPos, sphere.Center, new Vec3F(0, 1, 0));
                        ViewType    = viewtype;
                        ResetCamera = false;
                    }

                    GameEngine.Begin(SurfaceId, Camera.ViewMatrix, Camera.ProjectionMatrix);
                    if (Game.RootGameObjectFolder.GameObjects.Count > 0)
                    {
                        GameEngine.RenderGame();
                    }
                    string str = "View Type: " + ViewType.ToString();
                    GameEngine.DrawText2D(str, Util3D.CaptionFont, 1, 1, Color.White);
                    GameEngine.End();
                }
                finally
                {
                    GameEngine.SetGameLevel(gameLevel);
                }
            }
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_cancelDrag || m_hitRegion == HitRegion.None || NodeList.Count == 0)
            {
                return;
            }

            bool hitAxis = m_hitRegion == HitRegion.XAxis ||
                           m_hitRegion == HitRegion.YAxis ||
                           m_hitRegion == HitRegion.ZAxis;


            Matrix4F view = vc.Camera.ViewMatrix;
            Matrix4F proj = vc.Camera.ProjectionMatrix;
            Matrix4F vp   = view * proj;

            // create ray in world space.
            Ray3F rayW = vc.GetRay(scrPt, vp);

            // create ray in view space.
            Ray3F rayV      = vc.GetRay(scrPt, proj);
            Vec3F translate = m_translatorControl.OnDragging(rayV);

            ISnapSettings snapSettings = (ISnapSettings)DesignView;
            bool          snapToGeom   = Control.ModifierKeys == m_snapGeometryKey;

            if (snapToGeom)
            {
                Vec3F manipPos = HitMatrix.Translation;
                Vec3F manipMove;
                if (hitAxis)
                {
                    //Make rayw to point toward moving axis and starting
                    // from manipulator’s world position.
                    rayW.Direction = Vec3F.Normalize(translate);
                    rayW.Origin    = manipPos;
                    manipMove      = Vec3F.ZeroVector;
                    m_cancelDrag   = true; //stop further snap-to's
                }
                else
                {
                    manipMove = rayW.ProjectPoint(manipPos) - manipPos;
                }

                for (int i = 0; i < NodeList.Count; i++)
                {
                    ITransformable node               = NodeList[i];
                    Vec3F          snapOffset         = TransformUtils.CalcSnapFromOffset(node, snapSettings.SnapFrom);
                    Path <DomNode> path               = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                    Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                    Vec3F          orgPosW;
                    parentLocalToWorld.Transform(m_originalValues[i], out orgPosW);

                    Matrix4F parentWorldToLocal = new Matrix4F();
                    parentWorldToLocal.Invert(parentLocalToWorld);

                    rayW.MoveToIncludePoint(orgPosW + snapOffset + manipMove);

                    HitRecord[] hits    = GameEngine.RayPick(view, proj, rayW, true);
                    bool        cansnap = false;
                    HitRecord   target  = new HitRecord();
                    if (hits.Length > 0)
                    {
                        // find hit record.
                        foreach (var hit in hits)
                        {
                            if (m_snapFilter.CanSnapTo(node, GameEngine.GetAdapterFromId(hit.instanceId)))
                            {
                                target  = hit;
                                cansnap = true;
                                break;
                            }
                        }
                    }

                    if (cansnap)
                    {
                        Vec3F pos;
                        if (target.hasNearestVert && snapSettings.SnapVertex)
                        {
                            pos = target.nearestVertex;
                        }
                        else
                        {
                            pos = target.hitPt;
                        }

                        pos -= snapOffset;
                        parentWorldToLocal.Transform(ref pos);
                        Vec3F diff = pos - node.Transform.Translation;
                        node.Translation += diff;
                        bool rotateOnSnap = snapSettings.RotateOnSnap &&
                                            target.hasNormal &&
                                            (node.TransformationType & TransformationTypes.Rotation) != 0;
                        if (rotateOnSnap)
                        {
                            Vec3F localSurfaceNormal;
                            parentWorldToLocal.TransformNormal(target.normal, out localSurfaceNormal);
                            node.Rotation = TransformUtils.RotateToVector(
                                m_originalRotations[i],
                                localSurfaceNormal,
                                AxisSystemType.YIsUp);
                        }
                    }
                }
            }
            else
            {
                IGrid grid       = DesignView.Context.Cast <IGame>().Grid;
                bool  snapToGrid = Control.ModifierKeys == m_snapGridKey &&
                                   grid.Visible &&
                                   vc.Camera.ViewType == ViewTypes.Perspective;
                float gridHeight = grid.Height;
                // translate.
                for (int i = 0; i < NodeList.Count; i++)
                {
                    ITransformable node = NodeList[i];
                    Path <DomNode> path = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                    Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                    Matrix4F       parentWorldToLocal = new Matrix4F();
                    parentWorldToLocal.Invert(parentLocalToWorld);
                    Vec3F localTranslation;
                    parentWorldToLocal.TransformVector(translate, out localTranslation);
                    Vec3F trans = m_originalValues[i] + localTranslation;

                    if (snapToGrid)
                    {
                        if (grid.Snap)
                        {
                            trans = grid.SnapPoint(trans);
                        }
                        else
                        {
                            trans.Y = gridHeight;
                        }
                    }

                    node.Translation = trans;
                }
            }
        }
Exemple #7
0
        public static void Init()
        {
            if (s_inited)
            {
                return;
            }

            List <Vector3> sphereVerts   = new List <Vec3F>();
            List <Vector3> sphereNormals = new List <Vec3F>();
            List <uint>    sphereIndices = new List <uint>();

            GeometryHelper.CreateSphere(0.5f, FastSphereSlices, FastSphereStacks, sphereVerts
                                        , sphereNormals, null, sphereIndices);

            s_triLisVbId        = GameEngine.CreateVertexBuffer(sphereVerts.ToArray());
            s_triListIbid       = GameEngine.CreateIndexBuffer(sphereIndices.ToArray());
            s_sphereIndexCount  = (uint)sphereIndices.Count;
            s_sphereStartVertex = 0;
            s_sphereStartVertex = 0;

            List <Vec3F> conePos     = new List <Vec3F>();
            List <uint>  coneIndices = new List <uint>();
            List <Vec3F> coneNorms   = new List <Vec3F>();

            GeometryHelper.CreateCylinder(1.0f, 0.0f, 1.0f, 16, 1, conePos, coneNorms, coneIndices);

            s_coneIndexCount = (uint)coneIndices.Count;

            VertexPN[] conveVB = new VertexPN[conePos.Count];

            for (int i = 0; i < conveVB.Length; i++)
            {
                conveVB[i].Position = conePos[i];
                conveVB[i].Normal   = coneNorms[i];
            }

            s_coneVertId  = GameEngine.CreateVertexBuffer(conveVB);
            s_coneIndexId = GameEngine.CreateIndexBuffer(coneIndices.ToArray());

            List <Vector3> cubePos     = new List <Vector3>();
            List <Vector3> cubeNormals = new List <Vector3>();
            List <Vector2> cubeTex     = new List <Vector2>();
            List <uint>    cubeIndices = new List <uint>();

            GeometryHelper.CreateUnitCube(cubePos, cubeNormals, cubeTex, cubeIndices);
            VertexPN[] cubeVerts = new VertexPN[cubePos.Count];
            for (int i = 0; i < cubeVerts.Length; i++)
            {
                cubeVerts[i].Position = cubePos[i];
                cubeVerts[i].Normal   = cubeNormals[i];
            }
            s_cubeVertId     = GameEngine.CreateVertexBuffer(cubeVerts);
            s_cubeIndexId    = GameEngine.CreateIndexBuffer(cubeIndices.ToArray());
            s_cubeIndexCount = (uint)cubeIndices.Count;


            var linePos = new List <Vec3F>();

            linePos.Add(new Vector3(0, 0, 0));
            linePos.Add(new Vector3(1, 0, 0));

            linePos.Add(new Vector3(0, 0, 0));
            linePos.Add(new Vector3(0, 1, 0));

            linePos.Add(new Vector3(0, 0, 0));
            linePos.Add(new Vector3(0, 0, 1));

            linePos.Add(new Vector3(0, 0, 0));
            linePos.Add(new Vector3(-1, 0, 0));

            linePos.Add(new Vector3(0, 0, 0));
            linePos.Add(new Vector3(0, -1, 0));

            linePos.Add(new Vector3(0, 0, 0));
            linePos.Add(new Vector3(0, 0, -1));

            s_axisStartVertex = 0;
            s_axisVertexCount = (uint)linePos.Count;

            // rect pos;
            linePos.Add(new Vector3(1, 1, 0));
            linePos.Add(new Vector3(-1, 1, 0));

            linePos.Add(new Vector3(-1, 1, 0));
            linePos.Add(new Vector3(-1, -1, 0));

            linePos.Add(new Vector3(-1, -1, 0));
            linePos.Add(new Vector3(1, -1, 0));

            linePos.Add(new Vector3(1, -1, 0));
            linePos.Add(new Vector3(1, 1, 0));

            s_rectVertexCount = 8;
            s_rectStartVertex = (uint)linePos.Count - s_rectVertexCount;

            // unit square
            linePos.Add(new Vector3(0.5f, 0.5f, 0));
            linePos.Add(new Vector3(-0.5f, 0.5f, 0));

            linePos.Add(new Vector3(-0.5f, 0.5f, 0));
            linePos.Add(new Vector3(-0.5f, -0.5f, 0));

            linePos.Add(new Vector3(-0.5f, -0.5f, 0));
            linePos.Add(new Vector3(0.5f, -0.5f, 0));

            linePos.Add(new Vector3(0.5f, -0.5f, 0));
            linePos.Add(new Vector3(0.5f, 0.5f, 0));

            s_unitSquareVertexCount = 8;
            s_unitSquareStartVertex = (uint)linePos.Count - s_unitSquareVertexCount;

            s_linesVertId = GameEngine.CreateVertexBuffer(linePos.ToArray());

            List <Vec3F> circlePos = new List <Vec3F>();

            GeometryHelper.CreateCircle(1.0f, 32, circlePos);
            s_circleVertexCount = (uint)circlePos.Count;
            s_circleVerts       = GameEngine.CreateVertexBuffer(circlePos.ToArray());
            RenderFlag          = BasicRendererFlags.WireFrame;

            List <Vec3F> boxVerts   = new List <Vec3F>();
            List <uint>  boxIndices = new List <uint>();

            GeometryHelper.CreateUnitBox(boxVerts, boxIndices);
            s_boxVertsId      = GameEngine.CreateVertexBuffer(boxVerts.ToArray());
            s_boxIndicesId    = GameEngine.CreateIndexBuffer(boxIndices.ToArray());
            s_boxIndicesCount = (uint)boxIndices.Count;



            List <Vec3F> pivotVerts = new List <Vec3F>();

            GeometryHelper.CreateCircle(1.0f, 16, pivotVerts);
            GeometryHelper.CreateCircle(0.75f, 16, pivotVerts);
            GeometryHelper.CreateCircle(0.5f, 16, pivotVerts);
            GeometryHelper.CreateCircle(0.25f, 16, pivotVerts);
            s_pivotVerts       = GameEngine.CreateVertexBuffer(pivotVerts.ToArray());
            s_pivotVertexCount = (uint)pivotVerts.Count;


            s_captionFont = GameEngine.CreateFont("Arial", 14, FontStyle.BOLD);

            s_inited = true;
        }
Exemple #8
0
            public NativeViewControl()
            {
                ClientSize = new Size(16, 16);
                if (!GameEngine.IsInError)
                {
                    swapChainId = GameEngine.GetObjectTypeId("SwapChain");
                    SurfaceId   = GameEngine.CreateObject(swapChainId, this.Handle, IntPtr.Size);
                    SizePropId  = GameEngine.GetObjectPropertyId(swapChainId, "Size");
                    GameEngine.SetObjectProperty(swapChainId, SurfaceId, SizePropId, ClientSize);
                    BkgColorPropId = GameEngine.GetObjectPropertyId(swapChainId, "BkgColor");
                    GameEngine.SetObjectProperty(swapChainId, SurfaceId, BkgColorPropId, BackColor);
                }

                m_renderState                = new RenderState();
                m_renderState.RenderFlag     = GlobalRenderFlags.Solid | GlobalRenderFlags.Textured | GlobalRenderFlags.Lit;
                m_renderState.WireFrameColor = Color.DarkBlue;
                m_renderState.SelectionColor = Color.FromArgb(66, 255, 161);
                BackColor = SystemColors.ControlDark;


                #region Context menu
                GlobalRenderFlags[] flags = new GlobalRenderFlags[]
                {
                    GlobalRenderFlags.Solid,
                    GlobalRenderFlags.WireFrame,
                    GlobalRenderFlags.Textured,
                    GlobalRenderFlags.RenderBackFace,
                    GlobalRenderFlags.Lit
                };
                ContextMenuStrip cntx = new ContextMenuStrip();
                foreach (var flag in flags)
                {
                    ToolStripMenuItem item =
                        new ToolStripMenuItem(flag.ToString());
                    item.Tag    = flag;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        ToolStripMenuItem menu = (ToolStripMenuItem)sender;
                        RenderState.RenderFlag = RenderState.RenderFlag ^ (GlobalRenderFlags)menu.Tag;
                        this.Invalidate();
                    };

                    cntx.Items.Add(item);
                }



                cntx.Items.Add(new ToolStripSeparator());
                ToolStripMenuItem views = new ToolStripMenuItem("View");
                cntx.Items.Add(views);
                views.DropDownOpening += delegate
                {
                    foreach (ToolStripMenuItem item in views.DropDownItems)
                    {
                        item.Checked = (ViewType == (ViewTypes)item.Tag);
                    }
                };

                foreach (var val in Enum.GetValues(typeof(ViewTypes)))
                {
                    ViewTypes         viewtype = (ViewTypes)val;
                    ToolStripMenuItem item     = new ToolStripMenuItem(viewtype.ToString());
                    item.Tag    = viewtype;
                    item.Click += delegate(object sender, EventArgs e)
                    {
                        ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
                        this.ViewType = (ViewTypes)menuItem.Tag;
                    };

                    views.DropDownItems.Add(item);
                }


                cntx.Opening += delegate
                {
                    GlobalRenderFlags renderflags = RenderState.RenderFlag;
                    foreach (ToolStripItem item in cntx.Items)
                    {
                        if (item is ToolStripSeparator)
                        {
                            break;
                        }
                        ((ToolStripMenuItem)item).Checked = (renderflags & (GlobalRenderFlags)item.Tag) != 0;
                    }
                };

                this.ContextMenuStrip = cntx;
                #endregion
            }
Exemple #9
0
        unsafe internal static void PushAttribute(
            uint propertyId,
            Type clrType, int arrayLength,
            object data,
            IList <PropertyInitializer> properties,
            System.IO.UnmanagedMemoryStream stream)
        {
            Type elmentType = clrType.GetElementType();

            if (clrType.IsArray && elmentType.IsPrimitive)
            {
                if (elmentType == typeof(float))
                {
                    var count = Math.Min(arrayLength, ((float[])data).Length);
                    properties.Add(GameEngine.CreateInitializer(
                                       propertyId, stream.PositionPointer,
                                       elmentType, (uint)count, false));

                    fixed(float *d = (float[])data)
                    for (uint c = 0; c < count; ++c)
                    {
                        ((float *)stream.PositionPointer)[c] = d[c];
                    }
                    stream.Position += sizeof(float) * count;
                }
                else if (elmentType == typeof(int))
                {
                    var count = Math.Min(arrayLength, ((int[])data).Length);
                    properties.Add(GameEngine.CreateInitializer(
                                       propertyId, stream.PositionPointer,
                                       elmentType, (uint)count, false));

                    fixed(int *d = (int[])data)
                    for (uint c = 0; c < count; ++c)
                    {
                        ((int *)stream.PositionPointer)[c] = d[c];
                    }
                    stream.Position += sizeof(int) * count;
                }

                else if (elmentType == typeof(uint))
                {
                    var count = Math.Min(arrayLength, ((uint[])data).Length);
                    properties.Add(GameEngine.CreateInitializer(
                                       propertyId, stream.PositionPointer,
                                       elmentType, (uint)count, false));

                    fixed(uint *d = (uint[])data)
                    for (uint c = 0; c < count; ++c)
                    {
                        ((uint *)stream.PositionPointer)[c] = d[c];
                    }
                    stream.Position += sizeof(int) * count;
                }
                else
                {
                    System.Diagnostics.Debug.Assert(false);
                }
            }
            else
            {
                if (clrType == typeof(string))
                {
                    SetStringProperty(propertyId, (string)data, properties, stream);
                }

                else if (clrType == typeof(bool))
                {
                    uint d = Convert.ToUInt32((bool)data);
                    SetBasicProperty(propertyId, d, properties, stream);
                    *(uint *)stream.PositionPointer = d;
                    stream.Position += sizeof(uint);
                }

                else if (clrType == typeof(byte))
                {
                    SetBasicProperty(propertyId, (byte)data, properties, stream);
                    *(byte *)stream.PositionPointer = (byte)data;
                    stream.Position += sizeof(byte);
                }

                else if (clrType == typeof(sbyte))
                {
                    SetBasicProperty(propertyId, (sbyte)data, properties, stream);
                    *(sbyte *)stream.PositionPointer = (sbyte)data;
                    stream.Position += sizeof(sbyte);
                }

                else if (clrType == typeof(short))
                {
                    SetBasicProperty(propertyId, (short)data, properties, stream);
                    *(short *)stream.PositionPointer = (short)data;
                    stream.Position += sizeof(short);
                }

                else if (clrType == typeof(ushort))
                {
                    SetBasicProperty(propertyId, (ushort)data, properties, stream);
                    *(ushort *)stream.PositionPointer = (ushort)data;
                    stream.Position += sizeof(ushort);
                }

                else if (clrType == typeof(int))
                {
                    SetBasicProperty(propertyId, (int)data, properties, stream);
                    *(int *)stream.PositionPointer = (int)data;
                    stream.Position += sizeof(int);
                }

                else if (clrType == typeof(uint))
                {
                    SetBasicProperty(propertyId, (uint)data, properties, stream);
                    *(uint *)stream.PositionPointer = (uint)data;
                    stream.Position += sizeof(uint);
                }

                else if (clrType == typeof(long))
                {
                    SetBasicProperty(propertyId, (long)data, properties, stream);
                    *(long *)stream.PositionPointer = (long)data;
                    stream.Position += sizeof(long);
                }

                else if (clrType == typeof(ulong))
                {
                    SetBasicProperty(propertyId, (ulong)data, properties, stream);
                    *(ulong *)stream.PositionPointer = (ulong)data;
                    stream.Position += sizeof(ulong);
                }

                else if (clrType == typeof(float))
                {
                    SetBasicProperty(propertyId, (float)data, properties, stream);
                    *(float *)stream.PositionPointer = (float)data;
                    stream.Position += sizeof(float);
                }

                else if (clrType == typeof(double))
                {
                    SetBasicProperty(propertyId, (double)data, properties, stream);
                    *(double *)stream.PositionPointer = (double)data;
                    stream.Position += sizeof(double);
                }

                else if (clrType == typeof(System.Uri))
                {
                    if (data != null && !string.IsNullOrWhiteSpace(data.ToString()))
                    {
                        Uri    uri = (Uri)data;
                        string str = uri.LocalPath;
                        SetStringProperty(propertyId, str, properties, stream);
                    }
                }

                else if (clrType == typeof(DomNode))
                {
                    // this is a 'reference' to an object
                    DomNode             refNode   = (DomNode)data;
                    NativeObjectAdapter nativeGob = refNode.As <NativeObjectAdapter>();
                    if (nativeGob != null)
                    {
                        SetBasicProperty(propertyId, (ulong)nativeGob.InstanceId, properties, stream);
                        *(ulong *)stream.PositionPointer = (ulong)nativeGob.InstanceId;
                        stream.Position += sizeof(ulong);
                    }
                }
            }
        }
Exemple #10
0
 public void InvokeFunction(string fn, IntPtr arg, out IntPtr retval)
 {
     GameEngine.InvokeMemberFn(InstanceId, fn, arg, out retval);
 }
Exemple #11
0
        private void CreateNativeObject()
        {
            var node = DomNode;

            if (DomNode == null || m_instanceId != 0)
            {
                return;
            }

            var doc = node.GetRoot().As <NativeDocumentAdapter>();

            if (doc != null && doc.ManageNativeObjectLifeTime)
            {
                // The object might have a pre-assigned instance id.
                // If so, we should attempt to use that same id.
                // This is important if we want the id to persist between sessions
                //      --  For example, we must reference placement objects through
                //          a GUID value that remains constant. We don't want to create
                //          new temporary ids for placements every time we create them,
                //          when the GUID value is more reliable

                ulong existingId = 0;
                var   idField    = DomNode.Type.GetAttributeInfo("ID");
                if (idField != null)
                {
                    var id = DomNode.GetAttribute(idField);
                    if (id is UInt64)
                    {
                        existingId = (UInt64)id;
                    }
                    else
                    {
                        string stringId = id as string;
                        if (stringId != null && stringId.Length > 0)
                        {
                            if (!UInt64.TryParse(stringId, out existingId))
                            {
                                existingId = GUILayer.Utils.HashID(stringId);
                            }
                        }
                    }
                }

                using (var transfer = new NativePropertyTransfer())
                {
                    using (var stream = transfer.CreateStream())
                        foreach (AttributeInfo attribInfo in this.DomNode.Type.Attributes)
                        {
                            UpdateNativeProperty(DomNode, attribInfo, transfer.Properties, stream);
                        }

                    m_instanceId = GameEngine.CreateObject(doc.NativeDocumentId, existingId, TypeId, transfer.Properties);
                }

                if (m_instanceId != 0)
                {
                    m_documentId = doc.NativeDocumentId;
                    GameEngine.RegisterGob(m_documentId, m_instanceId, this);
                }
            }
        }
        protected override IEnumerable <object> Pick(MouseEventArgs e)
        {
            bool multiSelect = DragOverThreshold;

            Picking.HitRecord[] hits;
            if (multiSelect)
            {
                RectangleF rect    = MakeRect(FirstMousePoint, CurrentMousePoint);
                var        frustum = XLEBridgeUtils.Utils.MakeFrustumMatrix(Utils.AsCameraDesc(Camera), rect, ClientSize);
                hits = Picking.FrustumPick(
                    GameEngine.GetEngineDevice(),
                    Adapter.SceneManager, Adapter.TechniqueContext,
                    frustum, Utils.AsCameraDesc(Camera), ClientSize,
                    Picking.Flags.Objects | Picking.Flags.Helpers);
            }
            else
            {
                Ray3F rayW = GetWorldRay(CurrentMousePoint);
                hits = Picking.RayPick(
                    GameEngine.GetEngineDevice(),
                    Adapter.SceneManager, Adapter.TechniqueContext,
                    rayW, Utils.AsCameraDesc(Camera), ClientSize,
                    Picking.Flags.Terrain | Picking.Flags.Objects | Picking.Flags.Helpers);
            }

            if (hits == null)
            {
                return(new List <object>());
            }

            // create unique list of hits
            var uniqueHits = new List <DomNode>();

            var             nativeIdMapping = Globals.MEFContainer.GetExportedValue <INativeIdMapping>();
            HashSet <ulong> instanceSet     = new HashSet <ulong>();

            foreach (var hit in hits)
            {
                if (instanceSet.Add(hit.instanceId))
                {
                    var nobj = nativeIdMapping.GetAdapter(hit.documentId, hit.instanceId).As <DomNodeAdapter>();
                    if (nobj != null && nobj.DomNode != null)
                    {
                        uniqueHits.Add(nobj.DomNode);
                    }
                }
            }

            // build 'path' objects for each hit record.
            var paths = new List <AdaptablePath <object> >();

            foreach (var node in uniqueHits)
            {
                var hitPath = Util.AdaptDomPath(node);
                var obj     = DesignView.PickFilter.Filter(hitPath, e);
                if (obj != null)
                {
                    var path = obj as AdaptablePath <object> ?? Util.AdaptDomPath((DomNode)obj);
                    // Prevent the same object from being added multiple times...
                    if (paths.Where(x => x.Last == path.Last).FirstOrDefault() == null)
                    {
                        paths.Add(path);
                    }
                }
            }

            #if false
            if (multiSelect == false && paths.Count > 0 && firstHit != null)
            {
                var path = paths[0];
                ISelectionContext selection = DesignView.Context.As <ISelectionContext>();
                ILinear           linear    = path.As <ILinear>();
                if (linear != null &&
                    Control.ModifierKeys == System.Windows.Forms.Keys.Shift &&
                    selection.SelectionContains(path))
                {
                    ITransactionContext trans = DesignView.Context.As <ITransactionContext>();
                    trans.DoTransaction(
                        delegate
                    {
                        linear.InsertPoint(firstHit.index, firstHit.hitPt.X, firstHit.hitPt.Y, firstHit.hitPt.Z);
                    }, "insert control point".Localize()
                        );
                }
            }
            #endif

            return(paths);
        }
        private void RenderProperties(GUILayer.SimpleRenderingContext context, IEnumerable <object> objects, bool renderCaption, bool renderBound, bool renderPivot)
        {
            if (renderCaption || renderBound)
            {
                Util3D.SetRenderFlag(context, BasicRendererFlags.WireFrame);
                Matrix4F vp = Camera.ViewMatrix * Camera.ProjectionMatrix;
                foreach (object obj in objects)
                {
                    IBoundable bnode = obj.As <IBoundable>();
                    if (bnode == null || bnode.BoundingBox.IsEmpty || obj.Is <IGameObjectFolder>())
                    {
                        continue;
                    }

                    INameable      nnode = obj.As <INameable>();
                    ITransformable trans = obj.As <ITransformable>();

                    if (renderBound)
                    {
                        Util3D.DrawAABB(context, bnode.BoundingBox);
                    }
                    if (renderCaption && nnode != null)
                    {
                        Vec3F topCenter = bnode.BoundingBox.Center;
                        topCenter.Y = bnode.BoundingBox.Max.Y;
                        Point pt = Project(vp, topCenter);
                        GameEngine.DrawText2D(nnode.Name, Util3D.CaptionFont, pt.X, pt.Y, Color.White);
                    }
                }
            }

            if (renderPivot)
            {
                Util3D.SetRenderFlag(context, BasicRendererFlags.WireFrame | BasicRendererFlags.DisableDepthTest);

                // create few temp matrics to
                Matrix4F toWorld  = new Matrix4F();
                Matrix4F PV       = new Matrix4F();
                Matrix4F sc       = new Matrix4F();
                Matrix4F bl       = new Matrix4F();
                Matrix4F recXform = new Matrix4F();
                foreach (object obj in objects)
                {
                    ITransformable trans = obj.As <ITransformable>();
                    IBoundable     bnode = obj.As <IBoundable>();
                    if (trans == null || bnode == null || bnode.BoundingBox.IsEmpty || obj.Is <IGameObjectFolder>())
                    {
                        continue;
                    }

                    Path <DomNode> path = new Path <DomNode>(trans.Cast <DomNode>().GetPath());
                    toWorld.Set(Vec3F.ZeroVector);
                    TransformUtils.CalcPathTransform(toWorld, path, path.Count - 1);

                    // Offset by pivot
                    PV.Set(trans.Pivot);
                    toWorld.Mul(PV, toWorld);
                    Vec3F pos = toWorld.Translation;

                    const float pivotDiameter = 16; // in pixels
                    float       s             = Util.CalcAxisScale(Camera, pos, pivotDiameter, Height);
                    sc.Scale(s);
                    Util.CreateBillboard(bl, pos, Camera.WorldEye, Camera.Up, Camera.LookAt);
                    recXform = sc * bl;
                    Util3D.DrawPivot(context, recXform, Color.Yellow);
                }
            }
        }
Exemple #14
0
 public GameEngine()
 {
     s_inist = this;
     GameEngine.Init();
 }
Exemple #15
0
 public static void SetRenderState(RenderState renderState)
 {
     GameEngine.NativeSetRenderState(renderState.InstanceId);
 }