Exemple #1
0
    void CreatSphereMesh()
    {
        MeshFilter meshFilter = GetMeshComponent();

        meshFilter.transform.position = GetMousePoint();
        meshFilter.mesh = SphereMesh.CreateSphere(0.05f, 20, 20, Color.red);
    }
Exemple #2
0
    private MeshInstance generate_joint_mesh()
    {
        MeshInstance j_mesh = new MeshInstance();

        // Create sphere
        SphereMesh m_mesh = new SphereMesh();

        m_mesh.Radius         = 0.05F;
        m_mesh.Height         = 0.1F;
        m_mesh.RadialSegments = 5;
        m_mesh.Rings          = 5;

        // Create material
        SpatialMaterial m_mat = new SpatialMaterial();

        m_mat.AlbedoColor     = new Color(0.26F, 0.32F, 0.92F);
        m_mat.EmissionEnabled = true;
        m_mat.Emission        = new Color(0.4F, 0.3F, 1.0F);
        m_mat.EmissionEnergy  = 3.0F;

        j_mesh.Mesh             = m_mesh;
        j_mesh.MaterialOverride = m_mat;

        return(j_mesh);
    }
Exemple #3
0
    void Update()
    {
        if (settingsChanged)
        {
            settingsChanged = false;
            if (mesh == null)
            {
                mesh = new Mesh();
            }
            else
            {
                mesh.Clear();
            }

            SphereMesh s = new SphereMesh(terrainResolution);
            mesh.vertices  = s.Vertices;
            mesh.triangles = s.Triangles;
            mesh.RecalculateBounds();
            mesh.RecalculateNormals();

            var g = GetOrCreateMeshObject("Mesh", mesh, material);
            if (generateCollider)
            {
                if (!g.GetComponent <MeshCollider> ())
                {
                    g.AddComponent <MeshCollider> ();
                }
                g.GetComponent <MeshCollider> ().sharedMesh = mesh;
            }
        }
    }
Exemple #4
0
    void CreatSphereMesh(Vector3 position)
    {
        MeshFilter meshFilter = GetMeshComponent();

        meshFilter.transform.position = position;
        meshFilter.mesh = SphereMesh.CreateSphere(0.05f, 20, 20, Color.red);
    }
 public TestSphereShooter(IXNAGame game, PhysicsEngine engine, ClientPhysicsQuadTreeNode root, ICamera shooterCamera)
 {
     this.game          = game;
     this.engine        = engine;
     this.root          = root;
     this.shooterCamera = shooterCamera;
     sphereMesh         = new SphereMesh(0.3f, 20, Color.Green);
 }
Exemple #6
0
        public void Initialize(float radius, Vector3 pos)
        {
            star = new SphereMesh(new Vector3(radius, radius, radius), 100, 100);

            position = pos;

            base.Initialize();
        }
    public SphereMesh SpawnSphereMesh(GameObject go, float radius)
    {
        int        subdivisions = 4;
        SphereMesh mesh         = go.AddComponent <SphereMesh>();

        mesh.material     = defaultMaterial;
        mesh.subdivisions = subdivisions;
        mesh.SetRadius(radius);
        return(mesh);
    }
Exemple #8
0
        public void Initialize(float planetRadius, Vector4 haze, float polarRadius, Vector3 pos)
        {
            planet = new SphereMesh(new Vector3(planetRadius, polarRadius, planetRadius), 100, 100);
            radius = planetRadius;

            hazeColor = haze;

            position = pos;

            base.Initialize();
        }
Exemple #9
0
        public SkySphere(string name, GraphicsDevice graphicsDevice)
            : base(name)
        {
            if (graphicsDevice == null)
            {
                throw new ArgumentNullException("graphicsDevice");
            }

            GraphicsDevice = graphicsDevice;

            sphereMesh = new SphereMesh(GraphicsDevice);
        }
    public AutoMesh SpawnMesh(ISphereShape shape, int subdivisions = 4)
    {
        // clamp division in [1, 6]
        subdivisions = Mathf.Clamp(subdivisions, 1, 6);
        GameObject go   = new GameObject();
        SphereMesh mesh = go.AddComponent <SphereMesh>();

        mesh.material     = defaultMaterial;
        mesh.subdivisions = subdivisions;
        mesh.SetRadius(shape.Radius);
        return(mesh);
    }
Exemple #11
0
    public void CreateLeaf()
    {
        SphereMesh mesh = new SphereMesh();

        mesh.Radius         = 0.4f;
        mesh.Height         = mesh.Radius * 2;
        mesh.RadialSegments = 8;
        mesh.Rings          = 4;
        MeshInstance meshInstance = new MeshInstance();

        meshInstance.Mesh = mesh;
        meshInstance.SetSurfaceMaterial(0, LeafMaterial);
        AddChild(meshInstance);
    }
        public void Initialize(float planetRadius, float atmosRadius, Vector4 haloColor, float polarRadius, Vector3 pos)
        {
            float atRadius = planetRadius + atmosRadius;
            float prRadius = polarRadius + atmosRadius;

            atmosphereMesh = new SphereMesh(new Vector3(atRadius, prRadius, atRadius), 100, 100);

            this.planetRadius = planetRadius;
            this.atmosRadius  = atmosRadius;

            position = pos;

            base.Initialize();
        }
Exemple #13
0
    public static void DrawSphere(Vector3 centre, float radius, Color col)
    {
        int resolution = 4;
        var sphereMesh = new SphereMesh(resolution);

        for (int i = 0; i < sphereMesh.Triangles.Length; i += 3)
        {
            var v1 = centre + sphereMesh.Vertices[sphereMesh.Triangles[i]] * radius;
            var v2 = centre + sphereMesh.Vertices[sphereMesh.Triangles[i + 1]] * radius;
            var v3 = centre + sphereMesh.Vertices[sphereMesh.Triangles[i + 2]] * radius;
            Debug.DrawLine(v1, v2, col);
            Debug.DrawLine(v2, v3, col);
            Debug.DrawLine(v3, v1, col);
        }
    }
Exemple #14
0
    public static void DrawSphere(Vector3 globalLocation, Spatial parent, float diameter = 0.05f)
    {
        MeshInstance sphere = new MeshInstance();
        SphereMesh   shape  = new SphereMesh();

        parent.AddChild(sphere);
        Transform placeholder = sphere.GlobalTransform;

        placeholder.origin     = globalLocation;
        sphere.GlobalTransform = placeholder;
        shape.Radius           = diameter / 2.0f;
        shape.Height           = diameter;
        sphere.Mesh            = shape;
        sphere.Visible         = true;
    }
Exemple #15
0
    public void InitializeCreature(float mass, float radius, float movementForceMag)
    {
        if (this.Initialized)
        {
            GD.Print("ERROR: Creature is already initialized. Can only be initialized once.");
            GetTree().Quit();
        }

        // calculate/set physical properties
        this.mass             = mass;
        this.radius           = radius;
        this.movementForceMag = movementForceMag;

        this.maxEnergy     = this.mass * 50;
        this.currentEnergy = this.maxEnergy;

        // make looks match physical properties
        SphereMesh mesh = new SphereMesh();

        ((MeshInstance)this.GetNode("MeshInstance")).Mesh = mesh;
        mesh.Radius = radius;
        mesh.Height = radius * 2;

        SpatialMaterial material   = new SpatialMaterial();
        float           brightness = (this.mass / 2.0f) * 1.0f;

        material.AlbedoColor = new Color(brightness, brightness, brightness);
        mesh.Material        = material;

        // create timers/connect signals
        replicationTimer_ = new Timer();
        this.AddChild(replicationTimer_);
        replicationTimer_.WaitTime = (float)GD.RandRange(7, 10);
        replicationTimer_.Connect("timeout", this, "OnReplicationTimerTimeout");
        replicationTimer_.Start();

        moveTimer_ = new Timer();
        this.AddChild(moveTimer_);
        moveTimer_.WaitTime = 1;
        moveTimer_.Connect("timeout", this, nameof(OnMoveTimerTimeout));
        moveTimer_.Start();

        this.Connect("body_entered", this, nameof(OnCollisionWithCreature));
        this.ContactMonitor   = true;
        this.ContactsReported = 10;

        this.initialized_ = true;
    }
Exemple #16
0
        private Godot.Mesh CreateSphere(
            Link.Geometry.Sphere sphere,
            SpatialMaterial mat = null)
        {
            SphereMesh temp = new SphereMesh();

            if (mat != null)
            {
                temp.Material = mat;
            }

            temp.RadialSegments = 16;
            temp.Radius         = (float)sphere.radius;
            temp.Height         = (float)(sphere.radius * 2.0);

            return(temp);
        }
Exemple #17
0
        static void Init()
        {
            if (sphereMesh == null)
            {
                inactiveMeshes     = new Queue <Mesh> ();
                materialProperties = new MaterialPropertyBlock();
                drawList           = new List <VisualElement> ();

                // Generate and cache primitive meshes
                sphereMesh   = new Mesh();
                cylinderMesh = new Mesh();
                SphereMesh.GenerateMesh(sphereMesh);
                CylinderMesh.GenerateMesh(cylinderMesh);

                // Create materials
                materials = new Material[shaderPaths.Length];
                for (int i = 0; i < materials.Length; i++)
                {
                    materials[i] = new Material(Shader.Find(shaderPaths[i]));
                }
            }

            // New frame index, so clear out last frame's draw list
            if (lastFrameInputReceived != Time.frameCount)
            {
                lastFrameInputReceived = Time.frameCount;

                // Store all unique meshes in inactive queue to be recycled
                var usedMeshes = new HashSet <Mesh> ();
                // Don't recycle cached meshes
                usedMeshes.Add(sphereMesh);
                usedMeshes.Add(cylinderMesh);

                for (int i = 0; i < drawList.Count; i++)
                {
                    if (!usedMeshes.Contains(drawList[i].mesh))
                    {
                        usedMeshes.Add(drawList[i].mesh);
                        inactiveMeshes.Enqueue(drawList[i].mesh);
                    }
                }

                // Clear old draw list
                drawList.Clear();
            }
        }
Exemple #18
0
        private void drawSpherePrimitives()
        {
            TangentVertex[] vertices;
            short[]         sIndices;

            SphereMesh.CreateUnitSphereVerticesAndIndices(20, out vertices, out sIndices);
            int[] indices = new int[sIndices.Length];
            for (int i = 0; i < sIndices.Length; i++)
            {
                indices[i] = sIndices[i];
            }


            GraphicsDevice.VertexDeclaration = tangentVertexDeclaration;

            GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, sIndices,
                                                     0, sIndices.Length / 3);
        }
        public Window1()
        {
            InitializeComponent();
            model.Transform = new Transform3DGroup();

            MeshGeometry3D mesh1 = new CubeMesh().Geometry;
            MeshGeometry3D mesh2 = new SphereMesh().Geometry;

            mesh2 = WPF3DHelper.Translate(mesh2, new Vector3D(0, 0, 10));
            MeshGeometry3D mesh3;

            //mesh2.Positions.Add(new Point3D(20, 20, 0));
            //mesh2.Positions.Add(new Point3D(0, 20, 20));
            //mesh2.Positions.Add(new Point3D(20, 0, 20));

            //mesh2.TriangleIndices.Add(0);
            //mesh2.TriangleIndices.Add(1);
            //mesh2.TriangleIndices.Add(2);

            //List<MeshGeometry3D> list = new List<MeshGeometry3D>();
            //list.Add(mesh1);
            //list.Add(mesh2);
            mesh3 = WPF3DHelper.Combine(mesh2, mesh1);
            //mesh3 = WPF3DHelper.WPF3DHelper.Combine(list);

            mesh1 = WPF3DHelper.Translate(mesh1, new Vector3D(20, 20, 20));
            mesh2 = WPF3DHelper.Scale(mesh2, new Vector3D(-3, -3, -3), new Point3D(0, 20, 20));

            GeometryModel3D mGeometry1 = new GeometryModel3D(mesh1, new DiffuseMaterial(Brushes.Red));
            GeometryModel3D mGeometry2 = new GeometryModel3D(mesh2, new DiffuseMaterial(Brushes.Green));
            GeometryModel3D mGeometry3 = new GeometryModel3D(mesh3, new DiffuseMaterial(Brushes.Blue));

            //model.Children.Add(mGeometry);
            Model3DGroup group = new Model3DGroup();

            group.Children.Add(mGeometry1);
            group.Children.Add(mGeometry2);
            group.Children.Add(mGeometry3);

            model.Content = group;
        }
    private void CreateClosePerceptionMesh()
    {
        var material = new SpatialMaterial();

        material.FlagsTransparent = true;
        material.AlbedoColor      = new Color(1.0f, 0.0f, 0.0f, 0.02f);

        var mesh = new SphereMesh();

        mesh.Material = material;
        mesh.Radius   = closePerceptionRadius;
        mesh.Height   = closePerceptionRadius * 2.0f;

        var meshInstance = new MeshInstance();

        meshInstance.Mesh = mesh;
        meshInstance.SetName("closePerceptionBubbleMesh");
        meshInstance.SetVisible(false);

        this.AddChild(meshInstance);
    }
Exemple #21
0
        public void TestEditSphereMesh()
        {
            ClassForm <SphereMesh> form = null;



            var game = new XNAGame();
            var mesh = new SphereMesh();

            game.AddXNAObject(mesh);



            var         ev  = new AutoResetEvent(false);
            Application app = null;
            var         t   = new Thread(delegate()
            {
                app  = new Application();
                form = new ClassForm <SphereMesh>();

                form.DataContext = mesh;

                form.Show();
                ev.Set();
                app.Run();
            });

            t.SetApartmentState(ApartmentState.STA);
            t.Start();

            ev.WaitOne();
            game.UpdateEvent += delegate
            {
                form.WriteDataContext();
                form.ReadDataContext();
            };

            game.Run();
        }
Exemple #22
0
        public static GameObject CreateMesh(GeometryType type, bool receiveShadow = true, bool castShadow = true, bool collider = true)
        {
            Mesh mesh = null;

            if (type == GeometryType.Cube)
            {
                mesh = new CubeMesh();
            }
            else if (type == GeometryType.Sphere)
            {
                mesh = new SphereMesh(1, 64);
            }
            else
            {
                mesh = new CylinderMesh();
            }

            var gameObject = new GameObject($"Mesh_{type}");
            var renderer   = gameObject.AddComponent <MeshRenderer>();

            renderer.Mesh          = mesh;
            renderer.ReceiveShadow = receiveShadow;
            renderer.CastShadow    = castShadow;

            if (collider)
            {
                gameObject.AddComponent <BoxCollider>();
            }

            if (mesh != null && !mesh.Built)
            {
                mesh.Build();
            }

            return(gameObject);
        }
Exemple #23
0
        void Initializtion()
        {
            //画星空
            {
                SphereMesh StarMesh = new SphereMesh();
                StarMesh.Slices = 8;
                StarMesh.Stacks = 4;
                StarMesh.Radius = 0.6;
                MeshGeometry3D Star = StarMesh.Geometry;

                var      Star3DGroup      = new Model3DGroup();
                Material specularMaterial = new SpecularMaterial(new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)), 1024);

                for (int i = 0; i < 1500; i++)
                {
                    //创建每个球体的GeometryModel并添加进显示窗口
                    MaterialGroup materialGroup = new MaterialGroup();

                    byte value = (byte)random.Next(150, 255);

                    DiffuseMaterial diffuseMaterial = new DiffuseMaterial(new SolidColorBrush(Color.FromRgb(value, value, value)));
                    materialGroup.Children.Add(diffuseMaterial);
                    materialGroup.Children.Add(specularMaterial);

                    var StarGeometryModel = new GeometryModel3D(Star, materialGroup);

                    Vector3D starPosition;

                    while (true)
                    {
                        double range = 300;
                        double x     = GetRandomInRange(range);
                        double y     = GetRandomInRange(range);
                        double z     = GetRandomInRange(range);

                        if (Math.Abs(x) < Length && Math.Abs(y) < Width * 2 && Math.Abs(z) < Height * 2)
                        {
                            continue;
                        }
                        else
                        {
                            starPosition = new Vector3D(x, y, z);
                            break;
                        }
                    }

                    StarGeometryModel.Transform = new TranslateTransform3D(starPosition);

                    Star3DGroup.Children.Add(StarGeometryModel);
                }

                //StarMesh.Slices = 8;
                //StarMesh.Stacks = 4;
                //StarMesh.Radius = 2;
                //Star = StarMesh.Geometry;

                //for (int i = 0; i < 500; i++)
                //{
                //    //创建每个球体的GeometryModel并添加进显示窗口
                //    MaterialGroup materialGroup = new MaterialGroup();

                //    byte value = (byte)random.Next(150, 255);

                //    DiffuseMaterial diffuseMaterial = new DiffuseMaterial(new SolidColorBrush(Color.FromRgb(value, value, value)));
                //    materialGroup.Children.Add(diffuseMaterial);
                //    materialGroup.Children.Add(specularMaterial);

                //    var StarGeometryModel = new GeometryModel3D(Star, materialGroup);

                //    Vector3D starPosition;

                //    while (true)
                //    {
                //        double range = 600;
                //        double x = GetRandomInRange(range);
                //        double y = GetRandomInRange(range);
                //        double z = GetRandomInRange(range);

                //        if (Math.Abs(x) < Length && Math.Abs(y) < Width * 1.5 && Math.Abs(z) < Height * 1.5)
                //        {
                //            continue;
                //        }
                //        else
                //        {
                //            starPosition = new Vector3D(x, y, z);
                //            break;
                //        }
                //    }

                //    StarGeometryModel.Transform = new TranslateTransform3D(starPosition);

                //    Star3DGroup.Children.Add(StarGeometryModel);
                //}

                {
                    ModelVisual3D starSetModel = new ModelVisual3D();
                    starSetModel.Content = Star3DGroup;
                    gameWindows.model.Children.Add(starSetModel);
                }
            }

            //画球台
            {
                BoxMesh boardMeshBase = new BoxMesh();

                boardMeshBase.Width  = Length;
                boardMeshBase.Height = Height;
                boardMeshBase.Depth  = Width;

                Geometry3D      boardMesh          = boardMeshBase.Geometry;
                GeometryModel3D boardGeometryModel = new GeometryModel3D(boardMesh, null);

                boardGeometryModel.Material = null;//材料

                ImageBrush imageBrush = new ImageBrush();
                imageBrush.ImageSource = new BitmapImage(new Uri("res/board.jpg", UriKind.Relative));
                //imageBrush.Viewbox = new Rect(0, 0, imageBrush.ImageSource.Width, imageBrush.ImageSource.Height);
                imageBrush.Viewbox = new Rect(0, 0, 100, 100);
                //imageBrush.TileMode = TileMode.FlipXY;
                imageBrush.TileMode     = TileMode.Tile;
                imageBrush.ViewboxUnits = BrushMappingMode.Absolute;
                imageBrush.Viewport     = new Rect(0, 0, 0.1, 0.1);

                MaterialGroup materialGroup = new MaterialGroup();
                //materialGroup.Children.Add(new SpecularMaterial(new SolidColorBrush(Colors.Gray), 1024));
                //materialGroup.Children.Add(new DiffuseMaterial(new SolidColorBrush(Colors.GreenYellow)));
                materialGroup.Children.Add(new DiffuseMaterial(imageBrush));

                boardGeometryModel.BackMaterial = materialGroup;

                ModelVisual3D moleculeSetModel = new ModelVisual3D();
                moleculeSetModel.Content = boardGeometryModel;
                gameWindows.model.Children.Add(moleculeSetModel);
            }

            gridMapOrigin = new Point3D(-0.5 * length, -0.5 * width, -0.5 * height);

            //画球体
            {
                SphereMesh sphereMesh = new SphereMesh();
                sphereMesh.Slices = 72 / 1;
                sphereMesh.Stacks = 36 / 1;
                sphereMesh.Radius = radius;
                MeshGeometry3D sphere = sphereMesh.Geometry;


                //用于保存所有小球的Model
                moleculeModel3DGroup = new Model3DGroup();

                Material material         = (Material)gameWindows.viewport.Resources["ER_Vector___Glossy_Yellow___MediumMR2"];
                Material specularMaterial = new SpecularMaterial(new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)), 1024);

                //定义二维数组,分别存放molelecule的数量,和x,y,z的坐标
                double[,] moleculePositionSet = new double[moleculeNum, 3];
                moleculePositionSet[0, 0]     = 50;
                moleculePositionSet[0, 1]     = 0;
                moleculePositionSet[0, 2]     = 0;
                //layer1 begin
                moleculePositionSet[1, 0] = 0.0000000001;
                moleculePositionSet[1, 1] = 0;
                moleculePositionSet[1, 2] = 0;
                //layer2
                moleculePositionSet[2, 0] = -8;
                moleculePositionSet[2, 1] = 4.8;
                moleculePositionSet[2, 2] = 0;
                moleculePositionSet[3, 0] = -8;
                moleculePositionSet[3, 1] = -2.4;
                moleculePositionSet[3, 2] = 4;
                moleculePositionSet[4, 0] = -8;
                moleculePositionSet[4, 1] = -2.4;
                moleculePositionSet[4, 2] = -4;
                //layer3
                moleculePositionSet[5, 0] = -16;
                moleculePositionSet[5, 1] = 9.6;
                moleculePositionSet[5, 2] = 0;
                moleculePositionSet[6, 0] = -16;
                moleculePositionSet[6, 1] = 2.4;
                moleculePositionSet[6, 2] = 4;
                moleculePositionSet[7, 0] = -16;
                moleculePositionSet[7, 1] = 2.4;
                moleculePositionSet[7, 2] = -4;

                moleculePositionSet[8, 0]  = -16;
                moleculePositionSet[8, 1]  = -4.8;
                moleculePositionSet[8, 2]  = 0;
                moleculePositionSet[9, 0]  = -16;
                moleculePositionSet[9, 1]  = -4.8;
                moleculePositionSet[9, 2]  = 8;
                moleculePositionSet[10, 0] = -16;
                moleculePositionSet[10, 1] = -4.8;
                moleculePositionSet[10, 2] = -8;

                //layer4 begin
                moleculePositionSet[11, 0] = -24;
                moleculePositionSet[11, 1] = 14.4;
                moleculePositionSet[11, 2] = 0;
                moleculePositionSet[12, 0] = -24;
                moleculePositionSet[12, 1] = 7.2;
                moleculePositionSet[12, 2] = 4;
                moleculePositionSet[13, 0] = -24;
                moleculePositionSet[13, 1] = 7.2;
                moleculePositionSet[13, 2] = -4;
                moleculePositionSet[14, 0] = -24;
                moleculePositionSet[14, 1] = 0;
                moleculePositionSet[14, 2] = 0;
                moleculePositionSet[15, 0] = -24;
                moleculePositionSet[15, 1] = 0;
                moleculePositionSet[15, 2] = 8;
                moleculePositionSet[16, 0] = -24;
                moleculePositionSet[16, 1] = 0;
                moleculePositionSet[16, 2] = -8;
                moleculePositionSet[17, 0] = -24;
                moleculePositionSet[17, 1] = -7.2;
                moleculePositionSet[17, 2] = 4;
                moleculePositionSet[18, 0] = -24;
                moleculePositionSet[18, 1] = -7.2;
                moleculePositionSet[18, 2] = -4;
                moleculePositionSet[19, 0] = -24;
                moleculePositionSet[19, 1] = -7.2;
                moleculePositionSet[19, 2] = 12;
                moleculePositionSet[20, 0] = -24;
                moleculePositionSet[20, 1] = -7.2;
                moleculePositionSet[20, 2] = -12;

                for (int i = 0; (i < moleculeNum); i++)
                {
                    //创建并初始化molecule的属性
                    Molecule molecule = new Molecule()
                    {
                        //position = new Point3D(GetRandomInRange(positionRange), GetRandomInRange(positionRange), GetRandomInRange(positionRange)),
                        position = new Point3D(moleculePositionSet[i, 0], moleculePositionSet[i, 1], moleculePositionSet[i, 2]),
                        //currentVelocity = new Vector3D(GetRandomInRange(velocityRange), GetRandomInRange(velocityRange), GetRandomInRange(velocityRange)),
                        mass   = 1,
                        radius = radius
                    };

                    //创建每个球体的GeometryModel并添加进显示窗口
                    MaterialGroup materialGroup = new MaterialGroup();

                    int R, G, B;

                    while (true)
                    {
                        R = random.Next(255);
                        G = random.Next(255);
                        B = random.Next(255);

                        if (R + G + B < 350)
                        {
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }

                    DiffuseMaterial diffuseMaterial = new DiffuseMaterial(new SolidColorBrush(Color.FromRgb((byte)R, (byte)G, (byte)B)));
                    materialGroup.Children.Add(diffuseMaterial);
                    materialGroup.Children.Add(specularMaterial);

                    molecule.MoleculeGeometryModel = new GeometryModel3D(sphere, materialGroup);
                    //molecule.MoleculeGeometryModel.BackMaterial = materialGroup;

                    molecule.MoleculeGeometryModel.Transform = new TranslateTransform3D(molecule.position.X, molecule.position.Y, molecule.position.Z);

                    moleculeModel3DGroup.Children.Add(molecule.MoleculeGeometryModel);

                    MoleculeSet.Add(molecule);
                }

                {
                    ModelVisual3D moleculeSetModel = new ModelVisual3D();
                    moleculeSetModel.Content = moleculeModel3DGroup;
                    gameWindows.model.Children.Add(moleculeSetModel);
                }

                //设置白球
                whiteBall = MoleculeSet[0];
                ((MaterialGroup)whiteBall.MoleculeGeometryModel.Material).Children[0] = new DiffuseMaterial(new SolidColorBrush(Color.FromRgb(255, 255, 255)));
                //Material specularMaterial = new SpecularMaterial(new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)), 1024);
                //DiffuseMaterial white= new DiffuseMaterial(new SolidColorBrush(Color.FromRgb(255,255,255)));
                //whiteBall.Add(white);
            }

            //画球棍
            stick.Length = 120;
            stick.Init(gameWindows.model, new Vector3D(whiteBall.position.X, whiteBall.position.Y, whiteBall.position.Z), shotDirection);
            stick.Visible = false;

            //初始化碰撞检测引擎
            CDE.InitCollisionDetectionEngine(MoleculeSet, gridMapOrigin, length, width, height, radius * 2);

            CDE.CollisionResponse += delegate(int index1, int index2)
            {
                gameWindows.PlayBallCollisionSound();
                gameWindows.myMediaElement.Stop();
                gameWindows.myMediaElement.Play();

                PhysicEngine.UpdateVelocityByCollide(MoleculeSet[index1].position, MoleculeSet[index2].position, ref MoleculeSet[index1].currentVelocity, ref MoleculeSet[index2].currentVelocity,
                                                     MoleculeSet[index1].mass, MoleculeSet[index2].mass, MoleculeSet[index1].radius, MoleculeSet[index2].radius);
            };

            CDE.CollideWithWall += delegate(int index)
            {
                Molecule m = MoleculeSet[index];

                if (m.position.X < gridMapOrigin.X + m.radius)
                {
                    m.position.X        = gridMapOrigin.X + m.radius;
                    m.currentVelocity.X = -m.currentVelocity.X;

                    if (BallInHole(m))
                    {
                        BallInHoleList.Add(m);
                        gameWindows.PlayBallCollisionWithWallSound();
                    }
                    else
                    {
                        gameWindows.PlayBallInHoleSound();
                    }
                }
                if (m.position.X > gridMapOrigin.X + length - m.radius)
                {
                    m.position.X        = gridMapOrigin.X + length - m.radius;
                    m.currentVelocity.X = -m.currentVelocity.X;

                    if (BallInHole(m))
                    {
                        BallInHoleList.Add(m);
                        gameWindows.PlayBallCollisionWithWallSound();
                    }
                    else
                    {
                        gameWindows.PlayBallInHoleSound();
                    }
                }

                if (m.position.Y < gridMapOrigin.Y + m.radius)
                {
                    m.position.Y        = gridMapOrigin.Y + m.radius;
                    m.currentVelocity.Y = -m.currentVelocity.Y;

                    if (BallInHole(m))
                    {
                        BallInHoleList.Add(m);
                        gameWindows.PlayBallCollisionWithWallSound();
                    }
                    else
                    {
                        gameWindows.PlayBallInHoleSound();
                    }
                }
                if (m.position.Y > gridMapOrigin.Y + width - m.radius)
                {
                    m.position.Y        = gridMapOrigin.Y + width - m.radius;
                    m.currentVelocity.Y = -m.currentVelocity.Y;

                    if (BallInHole(m))
                    {
                        BallInHoleList.Add(m);
                        gameWindows.PlayBallCollisionWithWallSound();
                    }
                    else
                    {
                        gameWindows.PlayBallInHoleSound();
                    }
                }

                if (m.position.Z < gridMapOrigin.Z + m.radius)
                {
                    m.position.Z        = gridMapOrigin.Z + m.radius;
                    m.currentVelocity.Z = -m.currentVelocity.Z;

                    if (BallInHole(m))
                    {
                        BallInHoleList.Add(m);
                        gameWindows.PlayBallCollisionWithWallSound();
                    }
                    else
                    {
                        gameWindows.PlayBallInHoleSound();
                    }
                }
                if (m.position.Z > gridMapOrigin.Z + height - m.radius)
                {
                    m.position.Z        = gridMapOrigin.Z + height - m.radius;
                    m.currentVelocity.Z = -m.currentVelocity.Z;

                    if (BallInHole(m))
                    {
                        BallInHoleList.Add(m);
                        gameWindows.PlayBallCollisionWithWallSound();
                    }
                    else
                    {
                        gameWindows.PlayBallInHoleSound();
                    }
                }
            };
        }
        public void TestOBJToRAMMeshConverterPerObjectVisualCool()
        {
            var textureFactory = new RAMTextureFactory();
            var c = new OBJToRAMMeshConverter(textureFactory);


            var importer = new ObjImporter();

            importer.AddMaterialFileStream("Town001.mtl", new FileStream("../GameData/Town/OBJ03/Town001.mtl", FileMode.Open));
            importer.ImportObjFile("../GameData/Town/OBJ03/Town001.obj");

            var meshes = c.CreateMeshesFromObjects(importer);

            var texturePool           = new TexturePool();
            var meshpartPool          = new MeshPartPool();
            var vertexDeclarationPool = new VertexDeclarationPool();

            var renderer = new SimpleMeshRenderer(texturePool, meshpartPool, vertexDeclarationPool);

            vertexDeclarationPool.SetVertexElements <TangentVertex>(TangentVertex.VertexElements);



            var spheres = new List <ClientPhysicsTestSphere>();
            var engine  = new PhysicsEngine();
            PhysicsDebugRendererXNA debugRenderer = null;

            var root = CreatePhysicsQuadtree(20, 5);

            var physicsElementFactoryXNA = new MeshPhysicsFactoryXNA(engine, root);
            var physicsElementFactory    = physicsElementFactoryXNA.Factory;

            var physicsElements = new List <MeshStaticPhysicsElement>();

            for (int i = 0; i < 0 * 100 + 1 * meshes.Count; i++)
            {
                var mesh = meshes[i];
                var el   = renderer.AddMesh(mesh);
                el.WorldMatrix = Matrix.CreateTranslation(Vector3.Right * 0 * 2 + Vector3.UnitZ * 0 * 2);

                var pEl = physicsElementFactory.CreateStaticElement(mesh, Matrix.Identity);
                physicsElements.Add(pEl);
            }
            var gameMeshes = new List <OBJParserTest.TestGameMesh>();

            var game = new XNAGame();

            game.IsFixedTimeStep                    = false;
            game.DrawFps                            = true;
            game.SpectaterCamera.FarClip            = 5000;
            game.Graphics1.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs e)
            {
                DisplayMode displayMode = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferFormat = displayMode.Format;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferWidth  = displayMode.Width;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferHeight = displayMode.Height;
                game.SpectaterCamera.AspectRatio = displayMode.Width / (float)displayMode.Height;
            };
            game.Graphics1.ToggleFullScreen();

            var barrelMesh = OBJParserTest.GetBarrelMesh(c);
            var crateMesh  = OBJParserTest.GetCrateMesh(c);

            var sphereMesh = new SphereMesh(0.3f, 20, Color.Green);
            var visualizer = new QuadTreeVisualizerXNA();

            game.AddXNAObject(physicsElementFactoryXNA);

            game.AddXNAObject(texturePool);
            game.AddXNAObject(meshpartPool);
            game.AddXNAObject(vertexDeclarationPool);
            game.AddXNAObject(renderer);


            game.InitializeEvent += delegate
            {
                engine.Initialize();
                debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene);
                debugRenderer.Initialize(game);
                sphereMesh.Initialize(game);

                for (int i = 0; i < meshes.Count; i++)
                {
                    var mesh = meshes[i];
                    var data = mesh.GetCollisionData();

                    /*if (data.TriangleMesh != null)
                     *  physicsElementFactory.MeshPhysicsPool.PreloadTriangleMesh(engine.Scene, data.TriangleMesh);*/
                }
            };

            bool showPhysics = true;

            game.DrawEvent += delegate
            {
                if (game.Keyboard.IsKeyPressed(Keys.P))
                {
                    showPhysics = !showPhysics;
                }
                if (showPhysics)
                {
                    debugRenderer.Render(game);
                }

                /*visualizer.RenderNodeGroundBoundig(game, root,
                 *  delegate(ClientPhysicsQuadTreeNode node, out Color col)
                 *  {
                 *      col = Color.Green;
                 *
                 *      return node.PhysicsObjects.Count == 0;
                 *  });
                 *
                 * visualizer.RenderNodeGroundBoundig(game, root,
                 * delegate(ClientPhysicsQuadTreeNode node, out Color col)
                 * {
                 *     col = Color.Orange;
                 *
                 *     return node.PhysicsObjects.Count > 0;
                 * });*/

                for (int i = 0; i < physicsElements.Count; i++)
                {
                    var el = physicsElements[i];
                    //game.LineManager3D.AddBox(BoundingBox.CreateFromSphere( el.BoundingSphere), Color.Orange);
                }
                for (int i = 0; i < spheres.Count; i++)
                {
                    sphereMesh.WorldMatrix = Matrix.CreateTranslation(spheres[i].Center);
                    sphereMesh.Render(game);
                }
            };
            game.UpdateEvent += delegate
            {
                engine.Update(game.Elapsed);
                sphereMesh.Update(game);
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F))
                {
                    var pEl = physicsElementFactory.CreateDynamicElement(crateMesh,
                                                                         Matrix.CreateTranslation(
                                                                             game.SpectaterCamera.CameraPosition +
                                                                             game.SpectaterCamera.CameraDirection));
                    pEl.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 30;

                    var rEl = renderer.AddMesh(crateMesh);


                    gameMeshes.Add(new OBJParserTest.TestGameMesh(rEl, pEl));
                }
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.E))
                {
                    var pEl = physicsElementFactory.CreateDynamicElement(barrelMesh,
                                                                         Matrix.CreateTranslation(
                                                                             game.SpectaterCamera.CameraPosition +
                                                                             game.SpectaterCamera.CameraDirection));
                    pEl.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 30;

                    var rEl = renderer.AddMesh(barrelMesh);


                    gameMeshes.Add(new OBJParserTest.TestGameMesh(rEl, pEl));
                }


                for (int i = 0; i < gameMeshes.Count; i++)
                {
                    var m = gameMeshes[i];
                    m.RenderElement.WorldMatrix = m.PhysicsElement.World;
                }
            };

            game.Run();
        }
        public void TestSphereMesh()
        {
            XNAGame game = new XNAGame();

            List <SphereMesh> meshes = new List <SphereMesh>();


            TangentVertex[] vertices;
            short[]         indices;
            SphereMesh.CreateUnitSphereVerticesAndIndices(4, out vertices, out indices);

            bool wireframe = false;

            game.InitializeEvent +=
                delegate
            {
                SphereMesh mesh;
                mesh = new SphereMesh(1, 4, Color.Green);
                mesh.Initialize(game);
                meshes.Add(mesh);

                mesh             = new SphereMesh(1, 5, Color.PowderBlue);
                mesh.WorldMatrix = Matrix.CreateTranslation(3, 0, 0);
                mesh.Initialize(game);
                meshes.Add(mesh);

                mesh             = new SphereMesh(1, 12, Color.Yellow);
                mesh.WorldMatrix = Matrix.CreateTranslation(6, 0, 0);
                mesh.Initialize(game);
                meshes.Add(mesh);

                mesh             = new SphereMesh(1, 30, Color.Turquoise);
                mesh.WorldMatrix = Matrix.CreateTranslation(9, 0, 0);
                mesh.Initialize(game);
                meshes.Add(mesh);

                mesh             = new SphereMesh(40, 100, Color.Red);
                mesh.WorldMatrix = Matrix.CreateTranslation(0, 0, -60);
                mesh.Initialize(game);
                meshes.Add(mesh);


                mesh             = new SphereMesh(40, 13, Color.Red);
                mesh.WorldMatrix = Matrix.CreateTranslation(100, 0, -60);
                mesh.Initialize(game);
                meshes.Add(mesh);
            };
            game.UpdateEvent +=
                delegate
            {
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.W))
                {
                    wireframe = !wireframe;
                }
            };

            game.DrawEvent +=
                delegate
            {
                game.LineManager3D.AddAABB(meshes[1].BoundingBox, Matrix.Identity, Color.Red);

                int i;
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.R))
                {
                    for (i = 0; i < meshes.Count; i++)
                    {
                        meshes[i].ReloadShader(game);
                    }
                }
                game.GraphicsDevice.RenderState.FillMode = FillMode.Solid;
                game.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;

                if (!wireframe)
                {
                    for (i = 1; i < meshes.Count; i++)
                    {
                        meshes[i].Render(game);
                    }
                }


                i = 0;
                meshes[i].Color = Color.LightGreen;
                meshes[i].Render(game);

                game.GraphicsDevice.RenderState.CullMode = CullMode.CullClockwiseFace;
                meshes[i].Color = Color.Red;
                meshes[i].Render(game);

                game.GraphicsDevice.RenderState.FillMode = FillMode.WireFrame;
                game.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;

                meshes[i].Color = Color.Black;
                meshes[i].Render(game);

                if (wireframe)
                {
                    for (i = 1; i < meshes.Count; i++)
                    {
                        meshes[i].Render(game);
                    }
                }
                for (i = 0; i < vertices.Length; i++)
                {
                    game.LineManager3D.AddCenteredBox(vertices[i].pos, 0.05f, Color.Red);
                }
            };

            game.Run();
        }
        public void TestOBJToRAMMeshConverterPerObjectVisual()
        {
            var c = new OBJToRAMMeshConverter(new RAMTextureFactory());


            var importer = new ObjImporter();

            importer.AddMaterialFileStream("Town001.mtl", new FileStream(TestFiles.TownMtl, FileMode.Open));
            importer.ImportObjFile(TestFiles.TownObj);

            var meshes = c.CreateMeshesFromObjects(importer);

            var texturePool           = new TexturePool();
            var meshpartPool          = new MeshPartPool();
            var vertexDeclarationPool = new VertexDeclarationPool();

            var renderer = new SimpleMeshRenderer(texturePool, meshpartPool, vertexDeclarationPool);

            vertexDeclarationPool.SetVertexElements <TangentVertex>(TangentVertex.VertexElements);



            var spheres = new List <ClientPhysicsTestSphere>();
            var engine  = new PhysicsEngine();
            PhysicsDebugRendererXNA debugRenderer = null;

            var builder = new MeshPhysicsActorBuilder(new MeshPhysicsPool());

            TheWizards.Client.ClientPhysicsQuadTreeNode root;

            int numNodes = 20;

            root = new ClientPhysicsQuadTreeNode(
                new BoundingBox(
                    new Vector3(-numNodes * numNodes / 2f, -100, -numNodes * numNodes / 2f),
                    new Vector3(numNodes * numNodes / 2f, 100, numNodes * numNodes / 2f)));

            QuadTree.Split(root, 5);

            var physicsElementFactoryXNA = new MeshPhysicsFactoryXNA(engine, root);
            var physicsElementFactory    = physicsElementFactoryXNA.Factory;

            var physicsElements = new List <MeshStaticPhysicsElement>();

            for (int i = 0; i < 0 * 100 + 1 * meshes.Count; i++)
            {
                var mesh = meshes[i];
                var el   = renderer.AddMesh(mesh);
                el.WorldMatrix = Matrix.CreateTranslation(Vector3.Right * 0 * 2 + Vector3.UnitZ * 0 * 2);

                var pEl = physicsElementFactory.CreateStaticElement(mesh, Matrix.Identity);
                physicsElements.Add(pEl);
            }

            var game = new XNAGame();

            game.IsFixedTimeStep                    = false;
            game.DrawFps                            = true;
            game.SpectaterCamera.FarClip            = 5000;
            game.Graphics1.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs e)
            {
                DisplayMode displayMode = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferFormat = displayMode.Format;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferWidth  = displayMode.Width;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferHeight = displayMode.Height;
                game.SpectaterCamera.AspectRatio = displayMode.Width / (float)displayMode.Height;
            };
            game.Graphics1.ToggleFullScreen();

            var sphereMesh = new SphereMesh(0.3f, 20, Color.Green);
            var visualizer = new QuadTreeVisualizerXNA();

            game.AddXNAObject(physicsElementFactoryXNA);

            game.AddXNAObject(texturePool);
            game.AddXNAObject(meshpartPool);
            game.AddXNAObject(vertexDeclarationPool);
            game.AddXNAObject(renderer);


            game.InitializeEvent += delegate
            {
                engine.Initialize();
                debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene);
                debugRenderer.Initialize(game);
                sphereMesh.Initialize(game);
            };

            bool showPhysics = true;

            game.DrawEvent += delegate
            {
                if (game.Keyboard.IsKeyPressed(Keys.P))
                {
                    showPhysics = !showPhysics;
                }
                if (showPhysics)
                {
                    debugRenderer.Render(game);
                }
                visualizer.RenderNodeGroundBoundig(game, root,
                                                   delegate(ClientPhysicsQuadTreeNode node, out Color col)
                {
                    col = Color.Green;

                    return(node.PhysicsObjects.Count == 0);
                });

                visualizer.RenderNodeGroundBoundig(game, root,
                                                   delegate(ClientPhysicsQuadTreeNode node, out Color col)
                {
                    col = Color.Orange;

                    return(node.PhysicsObjects.Count > 0);
                });

                for (int i = 0; i < physicsElements.Count; i++)
                {
                    var el = physicsElements[i];
                    //game.LineManager3D.AddBox(BoundingBox.CreateFromSphere( el.BoundingSphere), Color.Orange);
                }
                for (int i = 0; i < spheres.Count; i++)
                {
                    sphereMesh.WorldMatrix = Matrix.CreateTranslation(spheres[i].Center);
                    sphereMesh.Render(game);
                }
            };
            game.UpdateEvent += delegate
            {
                engine.Update(game.Elapsed);
                sphereMesh.Update(game);
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F))
                {
                    var iSphere = new ClientPhysicsTestSphere(engine.Scene,
                                                              game.SpectaterCamera.CameraPosition + game.SpectaterCamera.CameraDirection
                                                              , 0.3f);

                    iSphere.InitDynamic();
                    iSphere.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 10;

                    spheres.Add(iSphere);
                }



                for (int i = 0; i < spheres.Count; i++)
                {
                    spheres[i].Update(root, game);
                }
            };

            game.Run();
        }
        private AxisManipulationHelper CreateHandle(AxisManipulationHelperType amhType, AxisType axisType, Prefab prefab, Material idleMaterial, Material grabbedMaterial, Material focusedMaterial, Quaternion orientation, AxisManipulationHelper[] relatedHandlers)
        {
            // Entity name suffix
            var suffix = $"{amhType}_{axisType}";

            // Handle root
            var handle = new Entity($"handle_{suffix}")
                         .AddComponent(new Transform3D()
            {
                LocalScale = Vector3.One * this.HandleScale,
            });

            this.rigRootEntity.AddChild(handle);

            if (prefab != null)
            {
                // Instantiate prefab
                var prefabInstance = prefab.Instantiate();

                var prefabTransform = prefabInstance.FindComponent <Transform3D>();
                prefabTransform.LocalOrientation = orientation;

                handle.AddChild(prefabInstance);
            }
            else
            {
                // Generate default look for the handle
                Vector3   position = Vector3.Zero;
                Vector3   size     = Vector3.One;
                Component mesh     = null;
                Component collider = null;

                switch (amhType)
                {
                case AxisManipulationHelperType.Center:
                    var sphereDiameter = 1f;

                    mesh = new SphereMesh()
                    {
                        Diameter = sphereDiameter,
                    };
                    collider = new SphereCollider3D()
                    {
                        Margin = 0.0001f,
                        Radius = sphereDiameter,
                    };
                    break;

                case AxisManipulationHelperType.Axis:
                    var axisLength    = 4f;
                    var axisThickness = 0.5f;

                    size = new Vector3(axisLength, axisThickness, axisThickness);

                    mesh     = new CubeMesh();
                    collider = new BoxCollider3D()
                    {
                        Margin = 0.0001f,
                        Size   = size + Vector3.One,
                        Offset = Vector3.UnitX,
                    };

                    position = 0.5f * Vector3.UnitX * (axisLength + 2f);
                    break;

                case AxisManipulationHelperType.Plane:
                    var planeLength    = 2f;
                    var planeThickness = 0.25f;

                    size = new Vector3(planeLength, planeThickness, planeLength);

                    mesh     = new CubeMesh();
                    collider = new BoxCollider3D()
                    {
                        Margin = 0.0001f,
                        Size   = size + Vector3.One,
                        Offset = Vector3.UnitX + Vector3.UnitZ,
                    };

                    position = 0.5f * Vector3.Normalize(Vector3.UnitX + Vector3.UnitZ) * (planeLength + 2f);
                    break;
                }

                // Collider entity
                var handleCollider = new Entity($"collider_{suffix}")
                                     .AddComponent(new Transform3D()
                {
                    LocalPosition    = Vector3.Transform(position, orientation),
                    LocalOrientation = orientation,
                })
                                     .AddComponent(collider)
                                     .AddComponent(new StaticBody3D()
                {
                    CollisionCategories = this.CollisionCategory,
                    IsSensor            = true,
                })
                                     .AddComponent(new NearInteractionGrabbable());

                // Visual entity
                var handleVisual = new Entity($"visuals_{suffix}")
                                   .AddComponent(new Transform3D()
                {
                    LocalScale = size,
                })
                                   .AddComponent(mesh)
                                   .AddComponent(new MeshRenderer())
                                   .AddComponent(new MaterialComponent());

                // Build hierarchy
                handle.AddChild(handleCollider);
                handleCollider.AddChild(handleVisual);
            }

            // Apply material
            var materialComponents = handle.FindComponentsInChildren <MaterialComponent>().ToArray();

            this.ApplyMaterialToAllComponents(materialComponents, idleMaterial);

            // Register helper object
            var helperTargetEntity = handle.FindComponentInChildren <NearInteractionGrabbable>()?.Owner;

            if (helperTargetEntity == null)
            {
                throw new Exception($"The handle entity needs to have a {nameof(NearInteractionGrabbable)} component.");
            }

            var handleHelper = new AxisManipulationHelper()
            {
                Type               = amhType,
                AxisType           = axisType,
                BaseEntity         = handle,
                MaterialComponents = materialComponents,
                IdleMaterial       = idleMaterial,
                GrabbedMaterial    = grabbedMaterial,
                FocusedMaterial    = focusedMaterial,
                RelatedHandles     = relatedHandlers,
            };

            this.helpers.Add(helperTargetEntity, handleHelper);

            return(handleHelper);
        }
Exemple #28
0
        override protected void OnLoad(System.EventArgs e)
        {
            lastMouseState = OpenTK.Input.Mouse.GetState();

            Texture angrySquirrelTexture, angryTurtleTexture, angryDilloTexture;

            Texture[] worldTextures;
            Mesh      squirrelMesh, turtleMesh, dilloMesh;

            RectangleMesh[] worldMeshes;

            float aspectRatio = ClientSize.Width / (float)(ClientSize.Height);

            projectionMatrix.set(Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 1000));

            cameraOnFrame = delegate(Matrix4f mvMatrix) {
                float   radius = 40, y = 20, timeRatio = 0.5f;
                Vector3 pos = new Vector3(
                    (float)Math.Sin(time.Value * timeRatio) * radius,
                    y,
                    (float)Math.Cos(time.Value * timeRatio) * radius);
                mvMatrix.set(Matrix4.LookAt(pos, new Vector3(0, y * 0.5f * (1.5f + (float)Math.Sin(time.Value * timeRatio)), 0), new Vector3(0, 1, 0)));
            };
            cameraOnFrame(modelviewMatrix);
            cameraOnFrame = null; // enable/disable

            ambientColor.set(0.4f, 0.4f, 0.4f);
            lightColor.set(1.0f, 1.0f, 1.0f);
            lightDirUnit.set(0.5f, 1.0f, 0.5f);
            //lightDirUnit.set( 0.1f, 5.0f, 0.1f );
            lightDirUnit.normalize();
            //texture = new Texture( "E:\\drop\\logo-dark.jpg" );
            angrySquirrelTexture = new Texture("gfx/angry-squirrel.png");
            angryTurtleTexture   = new Texture("gfx/angry-turtle.png");
            angryDilloTexture    = new Texture("gfx/angry-armadillo.png");

            worldTextures = new Texture[] {
                new Texture("gfx/drzewka-1.png"),
                new Texture("gfx/drzewka-3.png"),
                new Texture("gfx/sky.png"),
                new Texture("gfx/grass.png"),
                new Texture("gfx/drzewka-2.png"),
                new Texture("gfx/drzewka-4.png")
            };

            CreateShaders();

            squirrelMesh         = new SphereMesh(BALL_RADIUS, 20, 20, true);
            squirrelMesh.Texture = angrySquirrelTexture;

            /*
             * squirrelMesh.UpdateAction = delegate( Mesh model ) {
             *  Matrix4f transform = model.Transform;
             *  transform.setScaleAndRotation( Matrix4.CreateRotationZ( time.Value ) );
             *  //transform.setTranslationY( BALL_RADIUS + JUMP_HEIGHT * 0.5f * (1 + (float) Math.Sin( time.Value )) ); // hover
             *  //transform.setTranslationY( BALL_RADIUS + JUMP_HEIGHT * (float) Math.Abs( Math.Sin( time.Value ) ) ); // hover
             * };
             * squirrelMesh.UpdateAction( squirrelMesh );
             */
            //sm.writeOBJ();
            meshes.Add(squirrelMesh);

            turtleMesh         = new SphereMesh(BALL_RADIUS * 5, 10, 10, true);
            turtleMesh.Texture = angryTurtleTexture;

            /*
             * turtleMesh.UpdateAction = delegate( Mesh model ) {
             *  Matrix4f transform = model.Transform;
             *  transform.setScaleAndRotation( Matrix4.CreateRotationX( -time.Value ) );
             * };
             * turtleMesh.UpdateAction( turtleMesh );
             */
            meshes.Add(turtleMesh);

            dilloMesh         = new SphereMesh(BALL_RADIUS * 2, 20, 20, true);
            dilloMesh.Texture = angryDilloTexture;

            /*
             * dilloMesh.UpdateAction = delegate( Mesh model ) {
             *  Matrix4f transform = model.Transform;
             *  transform.setScaleAndRotation( Matrix4.CreateRotationX( -time.Value ) );
             * };
             * dilloMesh.UpdateAction( dilloMesh );
             */
            meshes.Add(dilloMesh);

            float boxX = 100, boxY = 50, boxZ = 100, shiftX = 0.5f * boxX, shiftY = 0.5f * boxY, shiftZ = 0.5f * boxZ;

            worldMeshes = new RectangleMesh[] {
                new RectangleMesh(Vector3f.OZ, boxX, boxY),
                new RectangleMesh(Vector3f.OZ, boxX, -boxY),
                new RectangleMesh(Vector3f.OY, boxX, boxZ),
                new RectangleMesh(Vector3f.OY, -boxX, boxZ),
                new RectangleMesh(Vector3f.OZ, -boxX, boxY),
                new RectangleMesh(Vector3f.OZ, boxX, boxY)
            };
            for (int i = worldMeshes.Length - 1; i >= 0; i--)
            {
                Mesh m = worldMeshes[i];
                m.Texture = worldTextures[i];
                meshes.Add(m);
            }
            Matrix4f trans;

            trans = worldMeshes[0].Transform;
            trans.setZero();
            trans.Data[2]  = 1;
            trans.Data[5]  = 1;
            trans.Data[8]  = 1;
            trans.Data[15] = 1;
            trans.setTranslation(shiftX, shiftY, 0);
            trans = worldMeshes[1].Transform;
            trans.setZero();
            trans.Data[2]  = -1;
            trans.Data[5]  = -1;
            trans.Data[8]  = -1;
            trans.Data[15] = 1;
            worldMeshes[1].Transform.setTranslation(-shiftX, shiftY, 0);
            worldMeshes[2].Transform.setTranslation(0, boxY, 0);
            worldMeshes[3].Transform.setTranslation(0, 0, 0);
            worldMeshes[4].Transform.setTranslation(0, shiftY, shiftZ);
            worldMeshes[5].Transform.setTranslation(0, shiftY, -shiftZ);

            foreach (Mesh m in meshes)
            {
                m.init();
            }

            //bodyManager.Gravity.setZero();
            /*SphereBody*/
            squirrelBody = new SphereBody(1, BALL_RADIUS);
            squirrelBody.Transform.setTranslation(40, 40, 40);
            squirrelBody.RotationSpeed = 1f;
            /*SphereBody*/
            turtleBody = new SphereBody(25, BALL_RADIUS * 5);
            turtleBody.Transform.setTranslation(0, 20, 0);
            //turtleBody.Velocity.Y = 5;
            turtleBody.RotationSpeed = 1f;
            /*SphereBody*/
            dilloBody = new SphereBody(25, BALL_RADIUS * 2);
            //dilloBody.Transform.setTranslation( -20, 100, -30 );
            dilloBody.Transform.setTranslation(0, 30, 0);
            //dilloBody.Velocity.Y = -5;
            dilloBody.RotationSpeed = 1f;
            Vector3f fixPoint = new Vector3f(0, 42, 9);

            /*
             * // spring - vertical harmonic oscillator
             * dilloBody.Forces.Add( delegate( Body obj ) {
             *  Vector3f disp = obj.Transform.getDisplacement( fixPoint );
             *  float k = 20.0f;
             *  disp.scale( k );
             *  obj.applyForce( disp );
             * } );
             */

            // springy pendulum - 3D harmonic oscillator
            dilloBody.Forces.Add(delegate(Body obj) {
                Vector3f disp = obj.Transform.getDisplacement(fixPoint);
                float k       = 10.0f, l = 15.0f;
                disp.scale(k * (disp.length() - l));
                obj.applyForce(disp);
            });

            planeBodies = new PlaneBody[] {
                new PlaneBody(new Plane3f(new Vector3f(0, 1, 0), 0)),
                new PlaneBody(new Plane3f(new Vector3f(0, -1, 0), boxY)),
                new PlaneBody(new Plane3f(new Vector3f(1, 0, 0), shiftX)),
                new PlaneBody(new Plane3f(new Vector3f(-1, 0, 0), shiftX)),
                new PlaneBody(new Plane3f(new Vector3f(0, 0, 1), shiftZ)),
                new PlaneBody(new Plane3f(new Vector3f(0, 0, -1), shiftZ))
            };

            foreach (PlaneBody pb in planeBodies)
            {
                pb.Friction = 0.1f;
                bodyManager.addBody(pb);
            }
            bodyManager.addBody(squirrelBody, squirrelMesh);
            bodyManager.addBody(turtleBody, turtleMesh);
            bodyManager.addBody(dilloBody, dilloMesh);

            VSync = VSyncMode.On;
        }
Exemple #29
0
        public void TestSnapPointToPoint()
        {
            XNAGame game = new XNAGame();

            SnapInformation inf1 = new SnapInformation();
            SnapInformation inf2 = new SnapInformation();

            SnapPoint p1 = new SnapPoint();

            p1.Position = new Vector3(1.7f, 1, 1);
            p1.Normal   = new Vector3(0, 0, 1);
            p1.Normal.Normalize();
            p1.Up = new Vector3(0, -1, 0);
            p1.Up.Normalize();

            SnapPoint p2 = new SnapPoint();

            p2.Position = new Vector3(1, 1, 1);
            p2.Normal   = new Vector3(1, 0, 0);
            p2.Normal.Normalize();
            p2.Up = new Vector3(0, -1, 0);
            p2.Up.Normalize();

            SnapPoint p3 = new SnapPoint();

            p3.Position = new Vector3(2, 0, 2);
            p3.Normal   = new Vector3(1, 1, 0);
            p3.Normal.Normalize();
            p3.Up = new Vector3(1, -1, 0);
            p3.Up.Normalize();

            SnapType type = new SnapType("t1");

            p1.SnapType = type;
            p2.SnapType = type;

            inf1.addSnapObject(p1);
            inf1.addSnapObject(p3);
            inf2.addSnapObject(p2);

            SnapEngineClass snapEngine = new SnapEngineClass();

            snapEngine.addSnapInformation(inf1);
            snapEngine.addSnapInformation(inf2);

            SphereMesh sphere1 = new SphereMesh(0.2f, 24, Color.Green);
            SphereMesh sphere2 = new SphereMesh(0.2f, 24, Color.Yellow);
            SphereMesh sphere3 = new SphereMesh(0.2f, 24, Color.Green);

            sphere1.WorldMatrix = Matrix.CreateTranslation(p1.Position);
            sphere2.WorldMatrix = Matrix.CreateTranslation(p2.Position);
            sphere3.WorldMatrix = Matrix.CreateTranslation(p3.Position);

            game.AddXNAObject(sphere1);
            game.AddXNAObject(sphere2);
            game.AddXNAObject(sphere3);

            game.DrawEvent += delegate
            {
                game.LineManager3D.AddLine(p1.Position, p1.Position + 0.5f * p1.Normal, Color.Red);
                game.LineManager3D.AddLine(p1.Position, p1.Position + 0.5f * p1.Up, Color.Yellow);

                game.LineManager3D.AddLine(p3.Position, p3.Position + 0.5f * p3.Normal, Color.Red);
                game.LineManager3D.AddLine(p3.Position, p3.Position + 0.5f * p3.Up, Color.Yellow);

                game.LineManager3D.AddLine(p2.Position, p2.Position + 0.5f * p2.Normal, Color.Red);
                game.LineManager3D.AddLine(p2.Position, p2.Position + 0.5f * p2.Up, Color.Yellow);
            };
            game.UpdateEvent += delegate
            {
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.Enter))
                {
                    snapEngine.SnapTo(inf1, inf2);
                    sphere1.WorldMatrix = Matrix.CreateTranslation(p1.Position);
                    sphere2.WorldMatrix = Matrix.CreateTranslation(p2.Position);
                    sphere3.WorldMatrix = Matrix.CreateTranslation(p3.Position);
                }
            };

            game.Run();
        }