Exemplo n.º 1
0
        async void CreateScene()
        {
            // UI text
            var helloText = new Text(Context);

            helloText.Value = "Hello World from UrhoSharp";
            helloText.HorizontalAlignment = HorizontalAlignment.Center;
            helloText.VerticalAlignment   = VerticalAlignment.Top;
            helloText.SetColor(new Color(r: 0f, g: 1f, b: 1f));
            helloText.SetFont(font: ResourceCache.GetFont("Fonts/Font.ttf"), size: 30);
            UI.Root.AddChild(helloText);

            // 3D scene with Octree
            var scene = new Scene(Context);

            scene.CreateComponent <Octree>();

            // Box
            Node boxNode = scene.CreateChild(name: "Box node");

            boxNode.Position = new Vector3(x: 0, y: 0, z: 5);
            boxNode.SetScale(0f);
            boxNode.Rotation = new Quaternion(x: 60, y: 0, z: 30);

            StaticModel boxModel = boxNode.CreateComponent <StaticModel>();

            boxModel.Model = ResourceCache.GetModel("Models/Box.mdl");
            boxModel.SetMaterial(ResourceCache.GetMaterial("Materials/BoxMaterial.xml"));

            // Light
            Node lightNode = scene.CreateChild(name: "light");
            var  light     = lightNode.CreateComponent <Light>();

            light.Range      = 10;
            light.Brightness = 1.5f;

            // Camera
            Node   cameraNode = scene.CreateChild(name: "camera");
            Camera camera     = cameraNode.CreateComponent <Camera>();

            Matrix4 pro = new Matrix4();

            //camera.SetProjection()
            //set rects
            IntRect halfView  = new IntRect(0, 0, 1300, 2000);
            IntRect halfqView = new IntRect(1300, 0, 2600, 2000);

            // Viewport

            Renderer.SetViewport(0, new Viewport(Context, scene, camera, halfView, null));
            Renderer.SetViewport(1, new Viewport(Context, scene, camera, halfqView, null));
            // Do actions
            await boxNode.RunActionsAsync(new EaseBounceOut(new ScaleTo(duration: 1f, scale: 1)));

            await boxNode.RunActionsAsync(new RepeatForever(
                                              new RotateBy(duration: 1, deltaAngleX: 90, deltaAngleY: 0, deltaAngleZ: 0)));
        }
Exemplo n.º 2
0
 public override void ApplyMaterial(StaticModel model)
 {
     foreach (var geometryMaterial in materials)
     {
         if (!model.SetMaterial(geometryMaterial.Item1, geometryMaterial.Item2))
         {
             throw new
                   InvalidOperationException($"Setting material on the geometry {geometryMaterial.Item1} failed");
         }
     }
 }
Exemplo n.º 3
0
    public StaticModel CreateStaticModel(Node node, Model model, Material material)
    {
        StaticModel staticModel = node.CreateComponent <StaticModel>();

        staticModel.SetModel(model);
        staticModel.SetMaterial(material);
        staticModel.CastShadows = true;


        return(staticModel);
    }
Exemplo n.º 4
0
        public static void LoadMaterials(this IMaterialHostElement materialHostElement, StaticModel staticModel, Urho.Resources.ResourceCache resourceCache)
        {
            var materialGroups = materialHostElement.GetMaterialGroups();

            foreach (var materialGroup in materialGroups)
            {
                var material     = materialGroup.GetMaterial();
                var texture      = materialGroup.GetTexture();
                var videoTexture = materialGroup.GetVideo();
                var webTexture   = materialGroup.GetWeb();

                if (material != null)
                {
                    if (materialGroup.Id == -1)
                    {
                        staticModel.SetMaterial(Material.FromColor(material.Diffuse.ToColor()));
                    }
                    else
                    {
                        staticModel.SetMaterial((uint)materialGroup.Id, Material.FromColor(material.Diffuse.ToColor()));
                    }
                }

                if (texture != null)
                {
                    var fileExtension = texture.Source.FileExtension();
                    var hash          = texture.Source.ToMD5() + fileExtension;

                    var img = resourceCache.GetImage(hash);

                    if (materialGroup.Id == -1)
                    {
                        staticModel.SetMaterial(Material.FromImage(img));
                    }
                    else
                    {
                        staticModel.SetMaterial((uint)materialGroup.Id, Material.FromImage(img));
                    }
                }
            }
        }
Exemplo n.º 5
0
        private void CreateSphere()
        {
            SphereNode          = scene.CreateChild();
            SphereNode.Position = new Vector3(0, 0, 0);
            SphereNode.ScaleNode(2);
            sphere       = SphereNode.CreateComponent <StaticModel>();
            sphere.Model = CoreAssets.Models.Sphere;
            var mat = Material.FromColor(Color.White);

            mat.CullMode = CullMode.None;
            sphere.SetMaterial(mat);
        }
Exemplo n.º 6
0
        public void SetImage(byte[] arr)
        {
            //UIImage uiimage = UIImage.FromBundle("R0010015.JPG");
            //
            //var memoryBuffer = new MemoryBuffer(uiimage.AsJPEG().ToArray());

            var webClient = new WebClient()
            {
                Encoding = Encoding.UTF8
            };
            //
            //// NOTE: The image MUST be in power of 2 resolution (Ex: 512x512, 2048x1024, etc...)
            var memoryBuffer = new MemoryBuffer(webClient.DownloadData(new Uri("https://video.360cities.net/littleplanet-360-imagery/360Level43Lounge-8K-stable-noaudio-2048x1024.jpg")));

            image = new Image();
            //

            var memory = new MemoryBuffer(new MemoryStream(arr));

            //var isLoaded = image.Load(memory);
            var isLoaded = image.Load(memoryBuffer);

            if (!isLoaded)
            {
                throw new Exception();
            }

            // 3.6 TEXTURE
            //texture = new Texture2D();

            //

            var resize = image.Resize(2048, 1024);


            var isTextureLoaded = texture.SetData(image);

            //if (!isTextureLoaded)
            //{
            //    throw new Exception();
            //}

            // 3.8 - MATERIAL
            material.SetTexture(TextureUnit.Diffuse, texture);

            material.SetTechnique(0, CoreAssets.Techniques.DiffNormal, 0, 0);
            material.CullMode = CullMode.Cw;
            modelObject.SetMaterial(material);

            //Renderer.SetViewport(0, new Viewport(scene, camera, null));
        }
Exemplo n.º 7
0
 void SetHilight(bool hilight, StaticModel mesh, Color color)
 {
     for (uint i = 0; i < 5; i++)
     {
         var mat = mesh.GetMaterial(i);
         if (mat == null)
         {
             break;
         }
         var matCopy = mat.Clone(mat.Name + "_hilight");
         matCopy.SetShaderParameter("MatDiffColor", hilight ? color : Urho.Color.White);
         mesh.SetMaterial(i, matCopy);
     }
 }
Exemplo n.º 8
0
        public override void Init()
        {
            scene = new Scene
            {
                new Node("Camera", new vec3(0, 5, -10), glm.radians(30, 0, 0))
                {
                    new Camera
                    {
                        Fov = glm.radians(60)
                    },
                },
            };

            camera = scene.GetComponent <Camera>(true);

            KtxTextureReader texReader = new KtxTextureReader
            {
                Format = VkFormat.R16G16B16A16SFloat,
            };

            var cubeMap = texReader.Load("textures/hdr/uffizi_cube.ktx");

            {
                var model = Resources.Load <Model>("Models/cube.obj");
                var node  = scene.CreateChild("Sky");
                node.Scaling = new vec3(30.0f);
                var staticModel = node.AddComponent <StaticModel>();
                staticModel.SetModel(model);

                var mat = new Material("Shaders/Skybox.shader");
                mat.SetTexture("EnvMap", cubeMap);

                staticModel.SetMaterial(mat);
            }

            {
                material = new Material("Shaders/Reflect.shader");
                material.SetTexture("ReflMap", cubeMap);
                material.SetShaderParameter("lodBias", lodBias);

                var node = scene.CreateChild("Model");
                node.Scaling = new vec3(0.1f);

                staticModel = node.AddComponent <StaticModel>();
                SetModel(filenames[0]);
                staticModel.SetMaterial(material);
            }

            MainView.Attach(camera, scene, new ForwardHdrRenderer());
        }
Exemplo n.º 9
0
        private Node AddBox(ResourceCache resourceCache, Scene scene)
        {
            Node boxNode = scene.CreateChild(name: "Box node");

            boxNode.Position = new Vector3(x: 0, y: 0, z: 5);
            boxNode.SetScale(0f);
            boxNode.Rotation = new Quaternion(x: 60, y: 0, z: 30);

            StaticModel boxModel = boxNode.CreateComponent <StaticModel>();

            boxModel.Model = resourceCache.GetModel("Models/Box.mdl");
            boxModel.SetMaterial(resourceCache.GetMaterial("Materials/BoxMaterial.xml"));
            return(boxNode);
        }
Exemplo n.º 10
0
        /// <inheritdoc />
        public override void OnUpdate()
        {
            bool isOn = false;

            if (timeout > 0)
            {
                timeout -= Time.UnscaledDeltaTime;
                isOn     = timeout > 0;
            }

            if (ModelToControl)
            {
                ModelToControl.SetMaterial(0, isOn ? MaterialOn : MaterialOff);
            }
        }
Exemplo n.º 11
0
        public override unsafe void OnSurfaceAddedOrUpdated(SpatialMeshInfo surface, Model generatedModel)
        {
            bool        isNew       = false;
            StaticModel staticModel = null;
            Node        node        = environmentNode.GetChild(surface.SurfaceId, false);

            if (node != null)
            {
                isNew       = false;
                staticModel = node.GetComponent <StaticModel>();
            }
            else
            {
                isNew       = true;
                node        = environmentNode.CreateChild(surface.SurfaceId);
                staticModel = node.CreateComponent <StaticModel>();
            }

            node.Position     = surface.BoundsCenter;
            node.Rotation     = surface.BoundsRotation;
            staticModel.Model = generatedModel;

            if (isNew)
            {
                staticModel.SetMaterial(material);
            }

            var surfaceDto = new SurfaceDto
            {
                Id                = surface.SurfaceId,
                IndexData         = surface.IndexData,
                BoundsCenter      = new Vector3Dto(surface.BoundsCenter.X, surface.BoundsCenter.Y, surface.BoundsCenter.Z),
                BoundsOrientation = new Vector4Dto(surface.BoundsRotation.X,
                                                   surface.BoundsRotation.Y, surface.BoundsRotation.Z, surface.BoundsRotation.W),
                BoundsExtents = new Vector3Dto(surface.Extents.X, surface.Extents.Y, surface.Extents.Z)
            };

            var vertexData = surface.VertexData;

            surfaceDto.VertexData = new SpatialVertexDto[vertexData.Length];
            for (int i = 0; i < vertexData.Length; i++)
            {
                SpatialVertex vertexItem = vertexData[i];
                surfaceDto.VertexData[i] = *(SpatialVertexDto *)(void *)&vertexItem;
            }

            clientConnection.SendObject(surfaceDto.Id, surfaceDto);
        }
Exemplo n.º 12
0
        Component GetCircleComponent(string label, Color clr)
        {
            List <VertexBuffer.PositionNormal> circleVertices = new List <VertexBuffer.PositionNormal>();

            for (int i = 0; i <= DIVISIONS; i++)
            {
                circleVertices.Add(new VertexBuffer.PositionNormal
                {
                    Position = circlePoints[i]
                });
            }

            var circleBuffer = new VertexBuffer(Application.CurrentContext, false);

            circleBuffer.SetSize((uint)circleVertices.Count, ElementMask.Position | ElementMask.Normal, false);
            circleBuffer.SetData(circleVertices.ToArray());

            var circleGeometry = new Geometry();

            circleGeometry.SetVertexBuffer(0, circleBuffer);
            circleGeometry.SetDrawRange(PrimitiveType.LineStrip, 0, 0, 0, (uint)circleVertices.Count, true);

            Model circleModel = new Model();

            circleModel.NumGeometries = 1;
            circleModel.SetGeometry(0, 0, circleGeometry);
            circleModel.BoundingBox = new BoundingBox(new Vector3(-10, -10, -10), new Vector3(10, 10, 10));

            Node        circleNode = Node.CreateChild(label);
            StaticModel circle     = circleNode.CreateComponent <StaticModel>();

            circle.Model = circleModel;

            Material lineMaterial = Material.FromColor(clr);

            lineMaterial.SetTechnique(0, CoreAssets.Techniques.NoTextureUnlit, 1, 1);
            lineMaterial.LineAntiAlias = true;
            circle.SetMaterial(lineMaterial);

            Node ballNode = circle.Node.CreateChild();
            var  ball     = ballNode.CreateComponent <Sphere>();

            ball.Color        = clr;
            ballNode.Scale    = new Vector3(0.15f, 0.15f, 0.15f);
            ballNode.Position = circlePoints[12];

            return(circle);
        }
Exemplo n.º 13
0
        public override void OnAttachedToNode(Node node)
        {
            base.OnAttachedToNode(node);

            bladeNode = node.CreateChild();
            bladeNode.SetScale(0);
            bladeModel       = bladeNode.CreateComponent <StaticModel>();
            bladeModel.Model = CoreAssets.Models.Box;
            bladeModel.SetMaterial(Material.FromColor(Color.White));

            var glowNode = bladeNode.CreateChild();

            glowNode.Scale    = new Vector3(3f, 3f, 1f);
            glowNode.Position = new Vector3(0.02f, 0, 0.02f);
            glowModel         = glowNode.CreateComponent <Box>();
        }
Exemplo n.º 14
0
        Node CreateMushroom(Vector3 pos)
        {
            var cache = GetSubsystem <ResourceCache>();

            Node mushroomNode = scene.CreateChild("Mushroom");

            mushroomNode.Position = pos;
            mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
            mushroomNode.SetScale(2.0f + NextRandom(0.5f));
            StaticModel mushroomObject = mushroomNode.CreateComponent <StaticModel>();

            mushroomObject.Model = (cache.Get <Model>("Models/Mushroom.mdl"));
            mushroomObject.SetMaterial(cache.Get <Material>("Materials/Mushroom.xml"));
            mushroomObject.CastShadows = true;

            return(mushroomNode);
        }
Exemplo n.º 15
0
        public override void OnSurfaceAddedOrUpdated(SpatialMeshInfo surface, Model generatedModel)
        {
            bool        isNew       = false;
            StaticModel staticModel = null;
            Node        node        = environmentNode.GetChild(surface.SurfaceId, false);

            if (node != null)
            {
                isNew       = false;
                staticModel = node.GetComponent <StaticModel>();
            }
            else
            {
                isNew       = true;
                node        = environmentNode.CreateChild(surface.SurfaceId);
                staticModel = node.CreateComponent <StaticModel>();
            }

            node.Position     = surface.BoundsCenter;
            node.Rotation     = surface.BoundsRotation;
            staticModel.Model = generatedModel;

            Material mat;
            Color    startColor;
            Color    endColor = new Color(0.8f, 0.8f, 0.8f);

            if (isNew)
            {
                startColor = Color.Blue;
                mat        = Material.FromColor(endColor);
                staticModel.SetMaterial(mat);
            }
            else
            {
                startColor = Color.Red;
                mat        = staticModel.GetMaterial(0);
            }

            mat.FillMode = wireframe ? FillMode.Wireframe : FillMode.Solid;
            var specColorAnimation = new ValueAnimation();

            specColorAnimation.SetKeyFrame(0.0f, startColor);
            specColorAnimation.SetKeyFrame(1.5f, endColor);
            mat.SetShaderParameterAnimation("MatDiffColor", specColorAnimation, WrapMode.Once, 1.0f);
        }
Exemplo n.º 16
0
        void CreateMushroom(Vector3 pos)
        {
            Node mushroomNode = scene.CreateChild("Mushroom");

            mushroomNode.Position = (pos);
            mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
            mushroomNode.SetScale(2.0f + NextRandom(0.5f));
            StaticModel mushroomObject = mushroomNode.CreateComponent <StaticModel>();

            mushroomObject.Model = (ResourceCache.GetModel("Models/Mushroom.mdl"));
            mushroomObject.SetMaterial(ResourceCache.GetMaterial("Materials/Mushroom.xml"));
            mushroomObject.CastShadows = true;
            // Create the navigation obstacle
            Obstacle obstacle = mushroomNode.CreateComponent <Obstacle>();

            obstacle.Radius = mushroomNode.Scale.X;
            obstacle.Height = mushroomNode.Scale.Y;
        }
Exemplo n.º 17
0
        private void LoadGeo()
        {
            if (TheCluster.GetStatus() == Cluster.Statuses.GeometryBound)
            {
                lock (Locker)
                    TryLoad = false;
            }

            if (TheCluster.GeoValid() && LoadLimiter.CanLoad(TheCluster.Origin))
            {
                lock (Locker)
                    TryLoad = false;

                var geos = TheCluster.Geometry.BindToUrhoGeo();

                GeoModel = Node.CreateComponent <StaticModel>();

                var meshGroup = new Model();
                int index     = 0;
                meshGroup.NumGeometries = (uint)geos.Count;

                foreach (var geo in geos)
                {
                    meshGroup.SetGeometry((uint)index, 0, geo.Item1);
                    meshGroup.SetGeometryCenter((uint)index, Vector3.Zero);
                    index++;
                }

                meshGroup.BoundingBox = new BoundingBox(new Vector3(0, 0, 0), new Vector3(Cluster.HVSize, Cluster.DSize, Cluster.HVSize));
                GeoModel.Model        = meshGroup;

                index = 0;
                foreach (var geo in geos)
                {
                    GeoModel.SetMaterial((uint)index, World.Info.Textures[geo.Item2].RuntimeMat);
                    index++;
                }
                GeoModel.CastShadows = true;

                TheCluster.FinalizeBind();
            }
        }
Exemplo n.º 18
0
        private void Render()
        {
            Scene scene = new Scene();

            scene.CreateComponent <Octree>();

            _node = scene.InstantiateXml(
                source: ResourceCache.GetFile(_scenePath),
                position: new Vector3(0, 0, 5),
                rotation: new Quaternion(defaultX, defaultY, defaultZ));

            Node lightNode  = scene.CreateChild(name: "Light");
            Node cameraNode = scene.CreateChild(name: "Camera");

            //model
            _node.Scale = new Vector3(1.5f, 2.5f, 4f);

            //model
            StaticModel modelObject = _node.CreateComponent <StaticModel>();

            modelObject.Model = ResourceCache.GetModel(_modelPath);
            modelObject.SetMaterial(Material.FromImage(ResourceCache.GetImage(_texturesPath)));

            //light
            lightNode.SetScale(30);
            lightNode.SetDirection(new Vector3(0, 0, 1));
            lightNode.Position = new Vector3(0, 4, -12);
            lightNode.CreateComponent <Light>().LightType = LightType.Directional;

            //camera
            cameraNode.Position = new Vector3(0, 0, -16);
            Camera camera = cameraNode.CreateComponent <Camera>();

            //viewport
            Renderer.SetViewport(0, new Viewport(scene, camera, null));

            //background color
            Renderer.GetViewport(0).SetClearColor(new Color()
            {
                R = 0.247f, G = 0.247f, B = 0.247f
            });
        }
Exemplo n.º 19
0
        protected Node CreateFloor()
        {
            var cache = ResourceCache;
            // Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
            // plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
            // (100 x 100 world units)
            // Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y
            Node floorNode = Scene.CreateChild("Floor");

            floorNode.Position = new Vector3(0.0f, -0.5f, 0.0f);
            floorNode.Scale    = new Vector3(500.0f, 1.0f, 500.0f);
            StaticModel floorObject = floorNode.CreateComponent <StaticModel>();

            floorObject.Model = cache.GetModel("Models/Box.mdl");
            var m = cache.GetMaterial("Materials/StoneTiled.xml");

            floorObject.SetMaterial(m);

            return(floorNode);
        }
Exemplo n.º 20
0
 public void SetMaterial(PulsarMaterial material)
 {
     if (material != null)
     {
         _model.SetMaterial(material.Material);
         if (_baseEntity != null)
         {
             Component existingComponent = _baseEntity.Components.ToList().Find(component => component.Equals(material));
             if (existingComponent == null)
             {
                 _baseEntity.AddComponent(material);
             }
             else
             {
                 //if in select mode, the Gizmo handles the temporary material which will need updating
                 GizmoHelper.UpdateTemporaryMaterialStore(_model.Node, material.Material);
             }
         }
     }
 }
Exemplo n.º 21
0
    private void ReplaceTexture()
    {
        StaticModel model = Node.GetComponent<StaticModel>(true);
        if (model != null)
        {
            ResourceCache cache = GetSubsystem<ResourceCache>();
            Texture2D texture = cache.GetResource<Texture2D>(texturePath);
            Material material = model.GetMaterial(0);
            if (texture != null && material != null)
            {
                if (instanceMaterial)
                {
                    Material materialClone = material.Clone();
                    model.SetMaterial(0, materialClone);
                    material = materialClone;
                }

                material.SetTexture(TextureUnit.TU_DIFFUSE, texture);
            }
        }
    }
Exemplo n.º 22
0
        void Create3DObject()
        {
            // Scene
            var scene = new Scene();

            scene.CreateComponent <Octree>();

            // Node (Rotation and Position)
            Node node = scene.CreateChild("room");

            node.Position = new Vector3(0, 0, 0);
            //node.Rotation = new Quaternion(10, 60, 10);
            node.SetScale(1f);

            // Model
            StaticModel modelObject = node.CreateComponent <StaticModel>();

            modelObject.Model = ResourceCache.GetModel("Models/Sphere.mdl");

            var zoneNode = scene.CreateChild("Zone");
            var zone     = zoneNode.CreateComponent <Zone>();

            zone.SetBoundingBox(new BoundingBox(-300.0f, 300.0f));
            zone.AmbientColor = new Color(1f, 1f, 1f);

            var material = new Material();

            material.SetTechnique(0, CoreAssets.Techniques.DiffNormal, 0, 0);
            material.CullMode = CullMode.Cw;
            modelObject.SetMaterial(material);

            // Camera
            Node   cameraNode = scene.CreateChild(name: "camera");
            Camera camera     = cameraNode.CreateComponent <Camera>();

            camera.Fov = 75.8f;

            // Viewport
            Renderer.SetViewport(0, new Viewport(scene, camera, null));
        }
Exemplo n.º 23
0
        public override void OnSurfaceAddedOrUpdated(string surfaceId, DateTimeOffset lastUpdateTimeUtc,
                                                     SpatialVertex[] vertexData, short[] indexData,
                                                     Vector3 boundsCenter, Quaternion boundsRotation)
        {
            var         isNew       = false;
            StaticModel staticModel = null;
            var         node        = _environmentNode.GetChild(surfaceId, false);

            if (node != null)
            {
                isNew       = false;
                staticModel = node.GetComponent <StaticModel>();
            }
            else
            {
                isNew       = true;
                node        = _environmentNode.CreateChild(surfaceId);
                staticModel = node.CreateComponent <StaticModel>();
            }

            node.Position = boundsCenter;
            node.Rotation = boundsRotation;
            var model = CreateModelFromVertexData(vertexData, indexData);

            staticModel.Model = model;

            if (isNew)
            {
                staticModel.SetMaterial(_spatialMaterial);
            }

            var rigidBody = node.CreateComponent <RigidBody>();

            rigidBody.RollingFriction = 0.5f;
            rigidBody.Friction        = 0.5f;
            var collisionShape = node.CreateComponent <CollisionShape>();

            collisionShape.SetTriangleMesh(model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
        }
Exemplo n.º 24
0
        public override void OnSurfaceAddedOrUpdated(SpatialMeshInfo surface, Model generatedModel)
        {
            bool        isNew       = false;
            StaticModel staticModel = null;
            Node        node        = environmentNode.GetChild(surface.SurfaceId, false);

            if (node != null)
            {
                isNew       = false;
                staticModel = node.GetComponent <StaticModel>();
            }
            else
            {
                isNew       = true;
                node        = environmentNode.CreateChild(surface.SurfaceId);
                staticModel = node.CreateComponent <StaticModel>();
            }

            node.Position     = surface.BoundsCenter;
            node.Rotation     = surface.BoundsRotation;
            staticModel.Model = generatedModel;

            if (isNew)
            {
                staticModel.SetMaterial(spatialMaterial);
                var rigidBody = node.CreateComponent <RigidBody>();
                rigidBody.RollingFriction = 0.5f;
                rigidBody.Friction        = 0.5f;
                var collisionShape = node.CreateComponent <CollisionShape>();
                collisionShape.SetTriangleMesh(generatedModel, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
            }
            else
            {
                //Update Collision shape
            }
        }
Exemplo n.º 25
0
        void CreateMovingBarrels(DynamicNavigationMesh navMesh)
        {
            Node        barrel = scene.CreateChild("Barrel");
            StaticModel model  = barrel.CreateComponent <StaticModel>();

            model.Model = ResourceCache.GetModel("Models/Cylinder.mdl");
            Material material = ResourceCache.GetMaterial("Materials/StoneTiled.xml");

            model.SetMaterial(material);
            material.SetTexture(TextureUnit.Diffuse, ResourceCache.GetTexture2D("Textures/TerrainDetail2.dds"));
            model.CastShadows = true;
            for (int i = 0; i < 20; ++i)
            {
                Node  clone = barrel.Clone(CreateMode.Replicated);
                float size  = 0.5f + NextRandom(1.0f);
                clone.Scale    = new Vector3(size / 1.5f, size * 2.0f, size / 1.5f);
                clone.Position = navMesh.FindNearestPoint(new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f), Vector3.One);
                CrowdAgent agent = clone.CreateComponent <CrowdAgent>();
                agent.Radius            = clone.Scale.X * 0.5f;
                agent.Height            = size;
                agent.NavigationQuality = NavigationQuality.Low;
            }
            barrel.Remove();
        }
Exemplo n.º 26
0
        void InitWheel(string name, Vector3 offset, out Node wheelNode, out uint wheelNodeId)
        {
            var cache = GetSubsystem <ResourceCache>();

            // Note: do not parent the wheel to the hull scene node. Instead create it on the root level and let the physics
            // constraint keep it together
            wheelNode          = Scene.CreateChild(name);
            wheelNode.Position = Node.LocalToWorld(offset);
            wheelNode.Rotation = Node.Rotation * (offset.X >= 0.0 ? new Quaternion(0.0f, 0.0f, -90.0f) : new Quaternion(0.0f, 0.0f, 90.0f));
            wheelNode.Scale    = new Vector3(0.8f, 0.5f, 0.8f);
            // Remember the ID for serialization
            wheelNodeId = wheelNode.ID;

            StaticModel    wheelObject     = wheelNode.CreateComponent <StaticModel>();
            RigidBody      wheelBody       = wheelNode.CreateComponent <RigidBody>();
            CollisionShape wheelShape      = wheelNode.CreateComponent <CollisionShape>();
            Constraint     wheelConstraint = wheelNode.CreateComponent <Constraint>();

            wheelObject.Model = (cache.Get <Model>("Models/Cylinder.mdl"));
            wheelObject.SetMaterial(cache.Get <Material>("Materials/Stone.xml"));
            wheelObject.CastShadows = true;
            wheelShape.SetSphere(1.0f, Vector3.Zero, Quaternion.Identity);
            wheelBody.Friction             = (1.0f);
            wheelBody.Mass                 = 1.0f;
            wheelBody.LinearDamping        = 0.2f;  // Some air resistance
            wheelBody.AngularDamping       = 0.75f; // Could also use rolling friction
            wheelBody.CollisionLayer       = 1;
            wheelConstraint.ConstraintType = ConstraintType.CONSTRAINT_HINGE;
            wheelConstraint.OtherBody      = GetComponent <RigidBody>();                              // Connect to the hull body
            wheelConstraint.SetWorldPosition(wheelNode.Position);                                     // Set constraint's both ends at wheel's location
            wheelConstraint.SetAxis(Vector3.UnitY);                                                   // Wheel rotates around its local Y-axis
            wheelConstraint.SetOtherAxis(offset.X >= 0.0 ? Vector3.UnitX : new Vector3(-1f, 0f, 0f)); // Wheel's hull axis points either left or right
            wheelConstraint.LowLimit         = new Vector2(-180.0f, 0.0f);                            // Let the wheel rotate freely around the axis
            wheelConstraint.HighLimit        = new Vector2(180.0f, 0.0f);
            wheelConstraint.DisableCollision = true;                                                  // Let the wheel intersect the vehicle hull
        }
Exemplo n.º 27
0
        void CreateScene()
        {
            var cache = GetSubsystem <ResourceCache>();

            scene = new Scene();

            // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
            // Also create a DebugRenderer component so that we can draw debug geometry
            scene.CreateComponent <Octree>();
            scene.CreateComponent <DebugRenderer>();

            // Create scene node & StaticModel component for showing a static plane
            Node planeNode = scene.CreateChild("Plane");

            planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
            StaticModel planeObject = planeNode.CreateComponent <StaticModel>();

            planeObject.Model = (cache.Get <Model>("Models/Plane.mdl"));
            planeObject.SetMaterial(cache.Get <Material>("Materials/StoneTiled.xml"));

            // Create a Zone component for ambient lighting & fog control
            Node zoneNode = scene.CreateChild("Zone");
            Zone zone     = zoneNode.CreateComponent <Zone>();

            zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
            zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
            zone.FogColor     = new Color(0.5f, 0.5f, 0.7f);
            zone.FogStart     = 100.0f;
            zone.FogEnd       = 300.0f;

            // Create a directional light to the world. Enable cascaded shadows on it
            Node lightNode = scene.CreateChild("DirectionalLight");

            lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
            Light light = lightNode.CreateComponent <Light>();

            light.LightType   = LightType.LIGHT_DIRECTIONAL;
            light.CastShadows = true;
            light.ShadowBias  = new BiasParameters(0.00025f, 0.5f);
            // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
            light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);

            // Create randomly sized boxes. If boxes are big enough, make them occluders
            const uint numBoxes = 20;
            Node       boxGroup = scene.CreateChild("Boxes");

            for (uint i = 0; i < numBoxes; ++i)
            {
                Node  boxNode = boxGroup.CreateChild("Box");
                float size    = 1.0f + NextRandom(10.0f);
                boxNode.Position = (new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f));
                boxNode.SetScale(size);
                StaticModel boxObject = boxNode.CreateComponent <StaticModel>();
                boxObject.Model = (cache.Get <Model>("Models/Box.mdl"));
                boxObject.SetMaterial(cache.Get <Material>("Materials/Stone.xml"));
                boxObject.CastShadows = true;
                if (size >= 3.0f)
                {
                    boxObject.Occluder = true;
                }
            }

            // Create a DynamicNavigationMesh component to the scene root
            DynamicNavigationMesh navMesh = scene.CreateComponent <DynamicNavigationMesh>();

            // Set the agent height large enough to exclude the layers under boxes
            navMesh.AgentHeight            = 10.0f;
            navMesh.CellHeight             = 0.05f;
            navMesh.DrawObstacles          = true;
            navMesh.DrawOffMeshConnections = true;
            // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
            // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
            scene.CreateComponent <Navigable>();
            // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
            // in the scene and still update the mesh correctly
            navMesh.Padding = new Vector3(0.0f, 10.0f, 0.0f);
            // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
            // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
            // it will use renderable geometry instead
            navMesh.Build();

            // Create an off-mesh connection to each box to make them climbable (tiny boxes are skipped). A connection is built from 2 nodes.
            // Note that OffMeshConnections must be added before building the navMesh, but as we are adding Obstacles next, tiles will be automatically rebuilt.
            // Creating connections post-build here allows us to use FindNearestPoint() to procedurally set accurate positions for the connection
            CreateBoxOffMeshConnections(navMesh, boxGroup);

            // Create some mushrooms
            const uint numMushrooms = 100;

            for (uint i = 0; i < numMushrooms; ++i)
            {
                CreateMushroom(new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
            }


            // Create a CrowdManager component to the scene root
            crowdManager = scene.CreateComponent <CrowdManager>();
            var parameters = crowdManager.GetObstacleAvoidanceParams(0);

            // Set the params to "High (66)" setting
            parameters.VelBias       = 0.5f;
            parameters.AdaptiveDivs  = 7;
            parameters.AdaptiveRings = 3;
            parameters.AdaptiveDepth = 3;
            crowdManager.SetObstacleAvoidanceParams(0, parameters);

            // Create some movable barrels. We create them as crowd agents, as for moving entities it is less expensive and more convenient than using obstacles
            CreateMovingBarrels(navMesh);

            // Create Jack node that will follow the path
            SpawnJack(new Vector3(-5.0f, 0.0f, 20.0f), scene.CreateChild("Jacks"));

            // Create the camera. Limit far clip distance to match the fog
            CameraNode = new Node();
            Camera camera = CameraNode.CreateComponent <Camera>();

            camera.FarClip = 300.0f;

            // Set an initial position for the camera scene node above the plane
            CameraNode.Position = new Vector3(0.0f, 50.0f, 0.0f);
            Pitch = 80.0f;
            CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0.0f);
        }
Exemplo n.º 28
0
        void CreateScene()
        {
            var cache = ResourceCache;

            scene = new Scene();

            // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
            // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
            // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
            // optimizing manner
            scene.CreateComponent <Octree>();

            // Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
            // plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
            // (100 x 100 world units)
            Node planeNode = scene.CreateChild("Plane");

            planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
            StaticModel planeObject = planeNode.CreateComponent <StaticModel>();

            planeObject.Model = (cache.GetModel("Models/Plane.mdl"));
            planeObject.SetMaterial(cache.GetMaterial("Materials/StoneTiled.xml"));

            // Create a point light to the world so that we can see something.
            Node  lightNode = scene.CreateChild("PointLight");
            Light light     = lightNode.CreateComponent <Light>();

            light.LightType = LightType.Point;
            light.Range     = (10.0f);

            // Create light animation
            ObjectAnimation lightAnimation = new ObjectAnimation();

            // Create light position animation
            ValueAnimation positionAnimation = new ValueAnimation();

            // Use spline interpolation method
            positionAnimation.InterpolationMethod = InterpMethod.Spline;
            // Set spline tension
            positionAnimation.SplineTension = 0.7f;

            positionAnimation.SetKeyFrame(0.0f, new Vector3(-30.0f, 5.0f, -30.0f));
            positionAnimation.SetKeyFrame(1.0f, new Vector3(30.0f, 5.0f, -30.0f));
            positionAnimation.SetKeyFrame(2.0f, new Vector3(30.0f, 5.0f, 30.0f));
            positionAnimation.SetKeyFrame(3.0f, new Vector3(-30.0f, 5.0f, 30.0f));
            positionAnimation.SetKeyFrame(4.0f, new Vector3(-30.0f, 5.0f, -30.0f));
            // Set position animation
            lightAnimation.AddAttributeAnimation("Position", positionAnimation, WrapMode.Loop, 1f);

            // Create text animation
            ValueAnimation textAnimation = new ValueAnimation();

            textAnimation.SetKeyFrame(0.0f, "WHITE");
            textAnimation.SetKeyFrame(1.0f, "RED");
            textAnimation.SetKeyFrame(2.0f, "YELLOW");
            textAnimation.SetKeyFrame(3.0f, "GREEN");
            textAnimation.SetKeyFrame(4.0f, "WHITE");
            var uiElement = UI.Root.GetChild("animatingText", false);

            uiElement.SetAttributeAnimation("Text", textAnimation, WrapMode.Loop, 1f);

            // Create light color animation
            ValueAnimation colorAnimation = new ValueAnimation();

            colorAnimation.SetKeyFrame(0.0f, Color.White);
            colorAnimation.SetKeyFrame(1.0f, Color.Red);
            colorAnimation.SetKeyFrame(2.0f, Color.Yellow);
            colorAnimation.SetKeyFrame(3.0f, Color.Green);
            colorAnimation.SetKeyFrame(4.0f, Color.White);
            // Set Light component's color animation
            lightAnimation.AddAttributeAnimation("@Light/Color", colorAnimation, WrapMode.Loop, 1f);

            // Apply light animation to light node
            lightNode.ObjectAnimation = lightAnimation;

            // Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
            // quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
            // LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
            // see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
            // same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
            // scene.
            const uint numObjects = 200;

            for (uint i = 0; i < numObjects; ++i)
            {
                Node mushroomNode = scene.CreateChild("Mushroom");
                mushroomNode.Position = (new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
                mushroomNode.Rotation = new Quaternion(0.0f, NextRandom(360.0f), 0.0f);
                mushroomNode.SetScale(0.5f + NextRandom(2.0f));
                StaticModel mushroomObject = mushroomNode.CreateComponent <StaticModel>();
                mushroomObject.Model = (cache.GetModel("Models/Mushroom.mdl"));
                mushroomObject.SetMaterial(cache.GetMaterial("Materials/Mushroom.xml"));
            }

            // Create a scene node for the camera, which we will move around
            // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
            CameraNode = scene.CreateChild("Camera");
            CameraNode.CreateComponent <Camera>();

            // Set an initial position for the camera scene node above the plane
            CameraNode.Position = (new Vector3(0.0f, 5.0f, 0.0f));
        }
        private async Task CreateScene()
        {
            // 1 - SCENE
            var scene = new Scene();

            scene.CreateComponent <Octree>();

            // 2 - NODE
            Node node = scene.CreateChild("room");

            node.Position = new Vector3(0, 0, 0);
            node.Rotation = new Quaternion(0, 0, 0);
            node.SetScale(2f);

            // 3 - MODEL OBJECT
            StaticModel modelObject = node.CreateComponent <StaticModel>();

            modelObject.Model = ResourceCache.GetModel("Models/Sphere.mdl");

            // 3.2 - ZONE
            var zoneNode = scene.CreateChild("zone");
            var zone     = zoneNode.CreateComponent <Zone>();

            zone.SetBoundingBox(new BoundingBox(-300.0f, 300.0f));
            zone.AmbientColor = new Color(1f, 1f, 1f);

            // 3.5 - DOWNLOAD IMAGE
            var webClient = new WebClient()
            {
                Encoding = Encoding.UTF8
            };

            // NOTE: The image MUST be in power of 2 resolution (Ex: 512x512, 2048x1024, etc...)
            var memoryBuffer = new MemoryBuffer(webClient.DownloadData(new Uri("https://video.360cities.net/littleplanet-360-imagery/360Level43Lounge-8K-stable-noaudio-2048x1024.jpg")));

            var image    = new Image();
            var isLoaded = image.Load(memoryBuffer);

            if (!isLoaded)
            {
                throw new Exception();
            }

            // 3.6 TEXTURE
            var texture         = new Texture2D();
            var isTextureLoaded = texture.SetData(image);

            if (!isTextureLoaded)
            {
                throw new Exception();
            }

            // 3.8 - MATERIAL
            var material = new Material();

            material.SetTexture(TextureUnit.Diffuse, texture);
            material.SetTechnique(0, CoreAssets.Techniques.DiffNormal, 0, 0);
            material.CullMode = CullMode.Cw;
            modelObject.SetMaterial(material);

            // 4 - LIGHTS
            Node light = scene.CreateChild(name: "light");

            light.SetDirection(new Vector3(0f, -0f, 0f));
            light.CreateComponent <Light>();

            // 5 - CAMERA
            cameraNode = scene.CreateChild(name: "camera");
            cameraNode.LookAt(new Vector3(0, 1, 2), new Vector3(0, 1, 0));
            Camera camera = cameraNode.CreateComponent <Camera>();

            camera.Fov = 50;

            // 6 - VIEWPORT
            Renderer.SetViewport(0, new Viewport(scene, camera, null));

            // 7 - ACTIONS
            //await node.RunActionsAsync(new RepeatForever(new RotateBy(duration: 4f, deltaAngleX: 0, deltaAngleY: 40, deltaAngleZ: 0)));
            IsSceneLoaded = true;
        }
Exemplo n.º 30
0
        void CreateScene()
        {
            var cache = GetSubsystem <ResourceCache>();

            scene = new Scene();

            // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
            // Also create a DebugRenderer component so that we can draw debug geometry
            scene.CreateComponent <Octree>();
            scene.CreateComponent <DebugRenderer>();

            // Create scene node & StaticModel component for showing a static plane
            Node planeNode = scene.CreateChild("Plane");

            planeNode.Scale = new Vector3(100.0f, 1.0f, 100.0f);
            StaticModel planeObject = planeNode.CreateComponent <StaticModel>();

            planeObject.Model = cache.Get <Model>("Models/Plane.mdl");
            planeObject.SetMaterial(cache.Get <Material>("Materials/StoneTiled.xml"));

            // Create a Zone component for ambient lighting & fog control
            Node zoneNode = scene.CreateChild("Zone");
            Zone zone     = zoneNode.CreateComponent <Zone>();

            zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f));
            zone.AmbientColor = new Color(0.15f, 0.15f, 0.15f);
            zone.FogColor     = new Color(0.5f, 0.5f, 0.7f);
            zone.FogStart     = 100.0f;
            zone.FogEnd       = 300.0f;

            // Create a directional light to the world. Enable cascaded shadows on it
            Node lightNode = scene.CreateChild("DirectionalLight");

            lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f));
            Light light = lightNode.CreateComponent <Light>();

            light.LightType   = LightType.LIGHT_DIRECTIONAL;
            light.CastShadows = true;
            light.ShadowBias  = new BiasParameters(0.00025f, 0.5f);
            // Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
            light.ShadowCascade = new CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);

            // Create some mushrooms
            const uint numMushrooms = 100;

            for (uint i = 0; i < numMushrooms; ++i)
            {
                CreateMushroom(new Vector3(NextRandom(90.0f) - 45.0f, 0.0f, NextRandom(90.0f) - 45.0f));
            }

            // Create randomly sized boxes. If boxes are big enough, make them occluders
            const uint numBoxes = 20;

            for (uint i = 0; i < numBoxes; ++i)
            {
                Node  boxNode = scene.CreateChild("Box");
                float size    = 1.0f + NextRandom(10.0f);
                boxNode.Position = new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f);
                boxNode.SetScale(size);
                StaticModel boxObject = boxNode.CreateComponent <StaticModel>();
                boxObject.Model = cache.Get <Model>("Models/Box.mdl");
                boxObject.SetMaterial(cache.Get <Material>("Materials/Stone.xml"));
                boxObject.CastShadows = true;
                if (size >= 3.0f)
                {
                    boxObject.Occluder = true;
                }
            }

            // Create Jack node that will follow the path
            jackNode          = scene.CreateChild("Jack");
            jackNode.Position = new Vector3(-5.0f, 0.0f, 20.0f);
            AnimatedModel modelObject = jackNode.CreateComponent <AnimatedModel>();

            modelObject.Model = cache.Get <Model>("Models/Jack.mdl");
            modelObject.SetMaterial(cache.Get <Material>("Materials/Jack.xml"));
            modelObject.CastShadows = true;

            // Create a NavigationMesh component to the scene root
            NavigationMesh navMesh = scene.CreateComponent <NavigationMesh>();

            // Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
            // navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
            scene.CreateComponent <Navigable>();
            // Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
            // in the scene and still update the mesh correctly
            navMesh.Padding = new Vector3(0.0f, 10.0f, 0.0f);
            // Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
            // physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
            // it will use renderable geometry instead
            navMesh.Build();

            // Create the camera. Limit far clip distance to match the fog
            CameraNode = scene.CreateChild("Camera");
            Camera camera = CameraNode.CreateComponent <Camera>();

            camera.FarClip = 300.0f;

            // Set an initial position for the camera scene node above the plane
            CameraNode.Position = new Vector3(0.0f, 5.0f, 0.0f);
        }