Example #1
0
        private static Scene CreateScene3()
        {
            Size resolution = new Size(640, 480);
            Point3D position = new Point3D(0, 0, 5000);
            double focus = 1000;
            SizeF projectionWindow = new SizeF(200, 150);
            Rotation rotation = new Rotation(-Math.PI * 0.25, 0, -Math.PI / 2.3);
            PerspectiveCamera camera = new PerspectiveCamera(position, rotation, projectionWindow, resolution, focus);

            Scene scene = new Scene();
            scene.Camera = camera;
            scene.InfinityColor = Color.Black;

            Material mS1 = new Material(Color.Green, 0.3, 0.3, 0.6, 0, 5);
            Material mS2 = new Material(Color.Red, 0.4, 0.4, 0, 0.4, 5);
            Material mS3 = new Material(Color.Yellow, 0.4, 0.3, 0.5, 0, 5);
            Material mS4 = new Material(Color.BlueViolet, 0.4, 0.3, 0.4, 0, 5);

            Material mC1 = new Material(Color.Black, 0.3, 0.3, 0.4, 0, 5);
            Material mC2 = new Material(Color.White, 0.3, 0.3, 0.4, 0, 5);

            Carpet carpet = new Carpet(new Point3D(0, 0, 0), new SizeF(5000, 5000), new Size(50, 50), mC1, mC2);
            double r = 100;
            double h = 2 * r * 0.866;
            double x = -h * 0.66 * 0.7;
            //шары в форме пирамиды
            Sphere sphere1 = new Sphere(new Point3D(x, x, r), r, mS1);
            Sphere sphere2 = new Sphere(new Point3D(x + h * 0.7 - r * 0.7, x + h * 0.7 + r * 0.7, r), r, mS2);
            Sphere sphere3 = new Sphere(new Point3D(x + h * 0.7 + r * 0.7, x + h * 0.7 - r * 0.7, r), r, mS3);
            Sphere sphere4 = new Sphere(new Point3D(x + h * 0.7 * 0.66, x + h * 0.7 * 0.66, 2.5 * r), r, mS4);

            scene.AddGraphicsObject(carpet);

            scene.AddGraphicsObject(sphere1);
            scene.AddGraphicsObject(sphere2);
            scene.AddGraphicsObject(sphere3);
            scene.AddGraphicsObject(sphere4);

            Light L1 = new Light(new Point3D(0, 0, 2000), Color.White);
            Light L2 = new Light(new Point3D(0, 2000, 3000), Color.White);
            Light L3 = new Light(new Point3D(2000, 0, 3000), Color.White);
            Light L4 = new Light(new Point3D(0, -2000, 3000), Color.White);
            Light L5 = new Light(new Point3D(-2000, 0, 3000), Color.White);
            //scene.AddLight(L1);
            scene.AddLight(L2);
            scene.AddLight(L3);
            scene.AddLight(L4);
            scene.AddLight(L5);

            return scene;
        }
Example #2
0
        private void SetCamera()
        {
            cameraRotation += (cameraTargetRotation - cameraRotation) * .3;

            PerspectiveCamera camera = (PerspectiveCamera)Screen3D.Camera;

            Matrix3D m = Matrix3D.Identity;

            m.OffsetX = currentX;
            m.OffsetY = .4;
            m.OffsetZ = currentZ;
            m.RotateAt(new Quaternion(new Vector3D(0, 1, 0), cameraRotation), new Point3D(m.OffsetX, m.OffsetY, m.OffsetZ));

            camera.Transform = new MatrixTransform3D(m);
        }
Example #3
0
        // Move the camera to the indicated position looking back at the origin.
        private void PositionCamera(float x, float y, float z, float yup)
        {
            hscroll.Value = 0;
            vscroll.Value = 0;
            PerspectiveCamera the_camera = viewCube.Camera as PerspectiveCamera;

            the_camera.Position      = new Point3D(x, y, z);
            the_camera.LookDirection = new Vector3D(-x, -y, -z);
            the_camera.UpDirection   = new Vector3D(0, yup, 0);

            Console.WriteLine(the_camera.Position.ToString());
            Console.WriteLine(the_camera.LookDirection.ToString());
            Console.WriteLine(the_camera.UpDirection.ToString());
            Console.WriteLine("**********");
        }
Example #4
0
        private void CreateScene(Wpf.Controls.Workshop3DX workshop3DX)
        {
            var camera = new PerspectiveCamera();

            camera.Position    = new Vector3(10.0f, 2.0f, 10.0f);
            camera.LookTarget  = new Vector3(0.0f, 1.0f, 0.0f);
            camera.FieldOfView = 25.0f;

            var scene = new Scene();

            scene.Camera = camera;

            workshop3DX.Scene = scene;
            workshop3DX.InvalidateProjection();
        }
        /// <summary>
        /// Sets the camera to view the 3D scene with the coordinates and view vector specified
        /// in the belonging textboxes
        /// </summary>
        /// <param name="sender">the object which triggered the event</param>
        /// <param name="e">the RoutedEventArgs</param>
        private void SetCamera_Click(object sender, RoutedEventArgs e)
        {
            PerspectiveCamera camera   = (PerspectiveCamera)mainViewport.Camera;
            Point3D           position = new Point3D(
                Convert.ToDouble(cameraPositionXTextBox.Text),
                Convert.ToDouble(cameraPositionYTextBox.Text),
                Convert.ToDouble(cameraPositionZTextBox.Text));
            Vector3D lookDirection = new Vector3D(
                Convert.ToDouble(lookAtXTextBox.Text),
                Convert.ToDouble(lookAtYTextBox.Text),
                Convert.ToDouble(lookAtZTextBox.Text));

            camera.Position      = position;
            camera.LookDirection = lookDirection;
        }
Example #6
0
        // Define the camera.
        private void DefineCamera(Viewport3D viewport)
        {
            // For the chapter header image.
            //Point3D position = new Point3D(0, 2, 3);
            Point3D position = new Point3D(1.5, 2, 3);

            Vector3D lookDirection = new Vector3D(
                -position.X, -position.Y, -position.Z);
            Vector3D          upDirection = new Vector3D(0, 1, 0);
            double            fieldOfView = 60;
            PerspectiveCamera camera      =
                new PerspectiveCamera(position, lookDirection, upDirection, fieldOfView);

            viewport.Camera = camera;
        }
Example #7
0
        public void RotateAlt(double dx, double dy)
        {
            PerspectiveCamera c = Camera;

            Point3D target = c.Position + c.LookDirection;

            RotateTwoAxes(dx, dy);

            if (Math.Abs(c.UpDirection.Length - 1) > 1e-8)
            {
                c.UpDirection.Normalize();
            }

            c.Position = target - c.LookDirection;
        }
Example #8
0
        public void TestImageCoverage()
        {
            HdrImage          image  = new HdrImage(4, 2);
            PerspectiveCamera camera = new PerspectiveCamera();
            ImageTracer       tracer = new ImageTracer(image, camera);

            tracer.fireAllRays((Ray r) => new Color(1f, 2f, 3f));
            for (int row = 0; row < image.height; row++)
            {
                for (int col = 0; col < image.width; col++)
                {
                    Assert.True(image.getPixel(col, row).isClose(new Color(1.0f, 2.0f, 3.0f)), $"TestImageCoverage failed - Assert row={row}, col={col}");
                }
            }
        } //end of function
Example #9
0
        public Pose3DView()
        {
            this.InitializeComponent();

            this.camera          = new PerspectiveCamera(new Point3D(0, 0, -3), new Vector3D(0, 0, 1), new Vector3D(0, 1, 0), 45);
            this.Viewport.Camera = this.camera;

            this.Viewport.Children.Add(new ModelVisual3D()
            {
                Content = new AmbientLight(Colors.White)
            });

            ////ConceptMatrix.Quaternion rootrot = Module.SkeletonViewModel.GetBone("Root").RootRotation;
            ////this.root.Transform = new RotateTransform3D(new QuaternionRotation3D(new Quaternion(rootrot.X, rootrot.Y, rootrot.Z, rootrot.W)));
        }
Example #10
0
 protected override void Init()
 {
     cursor           = new CursorIcon();
     Scene.Background = Colors.DodgerBlue;
     ide_camera       = new PerspectiveCamera()
     {
         Position    = new Vector4(0, 2f, 0),
         FieldOfView = (float)Math.PI / 3,
         Far         = 128f,
         Near        = 0.001f,
         Aspect      = 1.0f
     };
     Scene.Camera = ide_camera;
     Scene.ParentNode.Add(ide_camera);
 }
Example #11
0
        public GameObjectViewModel()
        {
            RootTemplateHelper = new RootTemplateHelper(this);

            EffectsManager = new DefaultEffectsManager();
            Camera         = new PerspectiveCamera()
            {
                FarPlaneDistance = 3000, FieldOfView = 75, CreateLeftHandSystem = true
            };
            var matrix = new System.Windows.Media.Media3D.MatrixTransform3D(new System.Windows.Media.Media3D.Matrix3D()).Value;

            matrix.Translate(new System.Windows.Media.Media3D.Vector3D(0, 0, 0));
            matrix.Rotate(new System.Windows.Media.Media3D.Quaternion(new System.Windows.Media.Media3D.Vector3D(0, 1, 0), 180));
            Transform = new System.Windows.Media.Media3D.MatrixTransform3D(matrix);
        }
        private void RenderAxisRotating(IViewport viewport, PerspectiveCamera camera, I2DRenderer im)
        {
            if (ActiveViewport.Viewport != viewport || !_mouseDownPoint.HasValue || !_mouseMovePoint.HasValue)
            {
                return;
            }

            var st = camera.WorldToScreen(_pivotPoint);
            var en = _mouseDownPoint.Value;

            im.AddLine(st.ToVector2(), en.ToVector2(), Color.Gray);

            en = _mouseMovePoint.Value;
            im.AddLine(st.ToVector2(), en.ToVector2(), Color.LightGray);
        }
        private void createCamera()
        {
            myPCamera          = new PerspectiveCamera();
            myPCamera.Position = new Point3D(0, 0, 200);
            //myPCamera.Position 获取或者设置在世界坐标上的位置//看的方向
            myPCamera.LookDirection = new Vector3D(0, 100, -1000);//摄影机看的方向
            //lookdirection 获取或设置 Vector3D 定义在世界坐标查找照相机方向
            myPCamera.UpDirection = new Vector3D(0, 1, -0);
            //updirection 获取或设置 Vector3D 定义照相机的向上方向。
            myPCamera.FieldOfView       = 45;//法向量摄影机上下颠倒,左转右转
            myPCamera.NearPlaneDistance = 0.1;
            myPCamera.FarPlaneDistance  = 11050;

            vp.Camera = myPCamera;
        }
Example #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Viewport3DX"/> class.
 /// </summary>
 public Viewport3DX()
 {
     Items.CollectionChanged += Items_CollectionChanged;
     this.DefaultStyleKey     = typeof(Viewport3DX);
     this.Loaded             += Viewport3DXLoaded;
     this.Unloaded           += Viewport3DX_Unloaded;
     cameraController         = new CameraController(this);
     InitCameraController();
     Camera = new PerspectiveCamera()
     {
         Position = new Vector3(0, 0, -10), LookDirection = new Vector3(0, 0, 10), UpDirection = new Vector3(0, 1, 0)
     };
     InputController = new InputController();
     SetupBindings();
 }
Example #15
0
            public override void Render(IViewport viewport, PerspectiveCamera camera, Graphics graphics)
            {
                const int size = 8;

                var spos = camera.WorldToScreen(Position);
                var rect = new Rectangle((int)spos.X - size / 2, (int)spos.Y - size / 2, size, size);

                var color = Color.FromArgb(255, GetColor());

                using (var brush = new SolidBrush(color))
                {
                    graphics.FillRectangle(brush, rect);
                    graphics.DrawRectangle(Pens.Black, rect);
                }
            }
Example #16
0
 public DressModel(string XAMLFile)
 {
     DressType            = DressTypes.Floral24;
     DressResource        = new ResourceDictionary();
     DressResource.Source = new Uri(XAMLFile, UriKind.RelativeOrAbsolute);
     DressGeometry        = new GeometryModel3D();
     DressCamera          = new PerspectiveCamera();
     DressTransform       = new Model3DGroup();
     DressViewport        = new Viewport3D();
     DressScene           = new Model3DGroup();
     DressVisual          = new ModelVisual3D();
     this.Width           = 151;
     this.Height          = 270;
     this.DressSizeRatio  = (this.Height / this.Width);
 }
Example #17
0
        // changing root

        private void ResetRootContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedTab != null)
            {
                if (SelectedGraph.DefaultRoot != SelectedGraph.Root)
                {
                    SelectedRadiusSlider.Value = 1;
                    SelectedAngleSlider.Value  = 1;
                    SelectedGraph.ResetRoot();
                    SelectedNode = SelectedGraph.Root;
                    PerspectiveCamera camera = SelectedViewport3D.Camera as PerspectiveCamera;
                    camera.LookDirection = new Point3D() - camera.Position;
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DirectionalLight DirLight1 = new DirectionalLight();

            DirLight1.Color     = Colors.White;
            DirLight1.Direction = new Vector3D(1, 1, 1);
            PerspectiveCamera Camera1 = new PerspectiveCamera();

            Camera1.FarPlaneDistance  = 8000;
            Camera1.NearPlaneDistance = 100;
            Camera1.FieldOfView       = 10;
            Camera1.Position          = new Point3D(160, 120, -1000);
            Camera1.LookDirection     = new Vector3D(0, 0, 1);
            Camera1.UpDirection       = new Vector3D(0, -1, 0);
            Model3DGroup modelGroup = new Model3DGroup();
            int          i          = 0;

            for (int y = 0; y < 240; y += s)
            {
                for (int x = 0; x < 320; x += s)
                {
                    points[i] = Triangle(x, y, s, new SolidColorBrush(Colors.White));
                    // points[i]=MCube(x,y);
                    points[i].Transform = new TranslateTransform3D(0, 0, 0);
                    modelGroup.Children.Add(points[i]);
                    i++;
                }
            }
            modelGroup.Children.Add(DirLight1);
            ModelVisual3D modelsVisual = new ModelVisual3D();

            modelsVisual.Content = modelGroup;
            Viewport3D myViewport = new Viewport3D();

            myViewport.IsHitTestVisible = false;
            myViewport.Camera           = Camera1;
            myViewport.Children.Add(modelsVisual);
            canvas1.Children.Add(myViewport);
            myViewport.Height = canvas1.Height;
            myViewport.Width  = canvas1.Width;
            Canvas.SetTop(myViewport, 0);
            Canvas.SetLeft(myViewport, 0);
            sensor = KinectSensor.KinectSensors[0];
            sensor.SkeletonStream.Enable();
            sensor.DepthStream.Enable(DepthImageFormat.Resolution320x240Fps30);
            sensor.DepthFrameReady += DepthFrameReady;
            sensor.Start();
        }
Example #19
0
        public void CreateScene(int width, int height, FloatColor color, bool useAntialiasing)
        {
            var renderTarget = new Framebuffer(width, height);

            renderTarget.Clear(color);
            var camera           = new PerspectiveCamera(renderTarget, new Vector3(0f, 0, -10), Vector3.Forward, Vector3.Up);
            var objects          = new List <IHittable>();
            var circuitryTexture = Texture.LoadFrom(@"_Resources/Textures/circuitry-albedo.png").ToInfo(3);
            var sunTexture       = Texture.LoadFrom(@"_Resources/Textures/sun.png").ToInfo();
            var modelTexture     = Texture.LoadFrom(@"_Resources/Textures/texel_density.png").ToInfo();
            var crystalTexture   = Texture.LoadFrom(@"_Resources/Textures/crystal.png").ToInfo();

            var circuitryMaterial = new PhongMaterial(FloatColor.White, 1f, 8, 50, 0.5f,
                                                      circuitryTexture);
            var sunMaterial = new PhongMaterial(FloatColor.White, 1f, 8, 50, 1f,
                                                sunTexture);
            var modelMaterial = new PhongMaterial(FloatColor.White, 1f, 8, 50, 1f,
                                                  modelTexture);
            var crystalMaterial = new PhongMaterial(FloatColor.White, 1f, 8, 50, 1f,
                                                    crystalTexture);

            var circuitry = new Sphere(new Vector3(2.5f, -1, 0), 0.5f, circuitryMaterial);
            var sun       = new Sphere(new Vector3(2.5f, -2.5f, 0), 0.75f, sunMaterial);
            var model     = Model.LoadFromFile("_Resources/Models/lowpolytree_unwrap.obj", modelMaterial, 1, Vector3.Down);
            var crystal   = Model.LoadFromFile("_Resources/Models/crystal.obj", crystalMaterial, 3, Vector3.Left * 2);

            objects.Add(circuitry);
            objects.Add(sun);
            objects.Add(model);
            objects.Add(crystal);

            Scene = new Scene(objects, camera,
                              new List <Light>
            {
                new PointLight {
                    Position = new Vector3(1, 2f, 0), Color = FloatColor.White
                },
                new PointLight {
                    Position = new Vector3(-2, 2f, 0), Color = FloatColor.Red
                },
                new PointLight {
                    Position = new Vector3(-4, 2f, -3), Color = FloatColor.White
                },
                new PointLight {
                    Position = new Vector3(-2, -1f, 0), Color = FloatColor.Green
                },
            }, FloatColor.Black);
        }
Example #20
0
        public void Rotate()
        {
            if (_isRotating)
            {
                ++_rotationRequests;
                return;
            }
            else
            {
                _isRotating = true;
            }

            if (_viewport != null)
            {
                // Find front rotation
                Viewport2DVisual3D  backContentSurface = _viewport.Children[1] as Viewport2DVisual3D;
                RotateTransform3D   backTransform      = backContentSurface.Transform as RotateTransform3D;
                AxisAngleRotation3D backRotation       = backTransform.Rotation as AxisAngleRotation3D;

                // Find back rotation
                Viewport2DVisual3D  frontContentSurface = _viewport.Children[2] as Viewport2DVisual3D;
                RotateTransform3D   frontTransform      = frontContentSurface.Transform as RotateTransform3D;
                AxisAngleRotation3D frontRotation       = frontTransform.Rotation as AxisAngleRotation3D;

                // Create a new camera each time, to avoid trying to animate a frozen instance.
                PerspectiveCamera camera = this.CreateCamera();
                _viewport.Camera = camera;

                // Create animations.
                DoubleAnimation rotationAnim = new DoubleAnimation
                {
                    Duration = new Duration(TimeSpan.FromMilliseconds(this.AnimationLength)),
                    By       = 180
                };
                Point3DAnimation cameraZoomAnim = new Point3DAnimation
                {
                    To          = new Point3D(0, 0, 2.5),
                    Duration    = new Duration(TimeSpan.FromMilliseconds(this.AnimationLength / 2)),
                    AutoReverse = true
                };
                cameraZoomAnim.Completed += this.OnRotationCompleted;

                // Start the animations.
                frontRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, rotationAnim);
                backRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, rotationAnim);
                camera.BeginAnimation(PerspectiveCamera.PositionProperty, cameraZoomAnim);
            }
        }
Example #21
0
        public override void Render(PerspectiveCamera cam)
        {
            GL.BindVertexArray(_gfx);

            int c = 0;

            // Loop through all avalable Textures
            // Tell the Shader Use Each Texture in its respective spot
            foreach (var tex in this._textures)
            {
                if (c == 1)
                {
                    tex.Value.Use(TextureUnit.Texture1);
                }
                else
                {
                    tex.Value.Use();
                }

                c++;
            }

            // Apply the Default Shader
            _default.Use();

            // Apply Global View Matrix
            _default.SetMatrix4("model", Matrix4.CreateTranslation(this.Transform.GetPosition()));
            _default.SetMatrix4("view", cam.GetViewMatrix());
            _default.SetMatrix4("projection", cam.GetProjectionMatrix());

            // Update View Matrix
            _default.SetVector3("viewPosition", cam.Position);

            _default.SetInt("material.diffuse", 0);
            _default.SetInt("material.specular", 1);
            _default.SetFloat("material.shine", 32.0f);

            _default.SetVector3("light.direction", _light_dir);
            _default.SetVector3("light.ambient", new Vector3(0.2f));
            _default.SetVector3("light.diffuse", new Vector3(0.5f));
            _default.SetVector3("light.specular", new Vector3(1.0f));


            GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            GL.BindVertexArray(_gfx);

            base.Render(cam);
        }
Example #22
0
        public MainViewModel()
        {
            Title = "Instancing Demo";

            // camera setup
            Camera = new PerspectiveCamera {
                Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0)
            };

            // setup lighting
            this.AmbientLightColor         = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            this.DirectionalLightColor     = (Color4)Color.White;
            this.DirectionalLightDirection = new Vector3(-2, -5, -2);

            // scene model3d
            var b1 = new MeshBuilder();

            b1.AddBox(new Vector3(0, 0, 0), 0.8, 0.8, 0.5, BoxFaces.All);
            Model = b1.ToMeshGeometry3D();

            var l1 = new LineBuilder();

            l1.AddBox(new Vector3(0, 0, 0), 0.8, 0.8, 0.5);
            Lines = l1.ToLineGeometry3D();

            int num       = 10;
            var instances = new List <Matrix>();

            for (int i = -num; i < num; i++)
            {
                for (int j = -num; j < num; j++)
                {
                    instances.Add(Matrix.Translation(new Vector3(i / 1.0f, j / 1.0f, 0f)));
                }
            }
            ModelInstances = instances;
            SubTitle       = "Number of Instances: " + instances.Count.ToString();

            // model trafo
            ModelTransform = Media3D.Transform3D.Identity;// new Media3D.RotateTransform3D(new Media3D.AxisAngleRotation3D(new Vector3D(0, 0, 1), 45));

            // model material
            ModelMaterial = PhongMaterials.Glass;

            RenderTechniquesManager = new DefaultRenderTechniquesManager();
            RenderTechnique         = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn];
            EffectsManager          = new DefaultEffectsManager(RenderTechniquesManager);
        }
        /// <summary>
        /// Rotates the control in 3D space in the direction specified by the RotationDirection property
        /// over the amount of time specified by the AnimationLength property.  Set the EasingMode property
        /// before calling this method to specify how the animated rotation should behave.
        /// </summary>
        public void Rotate()
        {
            if (!this.CanRotate)
            {
                throw new InvalidOperationException("You cannot call the Rotate method of ContentControl3D when CanRotate is set to false.");
            }

            if (_viewport == null)
            {
                throw new InvalidOperationException("The ContentControl3D's control template does not contain a Viewport3D whose name is PART_Viewport.");
            }

            if (_frontRotation == null)
            {
                throw new InvalidOperationException("The ContentControl3D's control template does not contain a Visual2DViewport3D with an AxisAngleRotation3D for the front side.");
            }

            if (_backRotation == null)
            {
                throw new InvalidOperationException("The ContentControl3D's control template does not contain a Visual2DViewport3D with an AxisAngleRotation3D for the back side.");
            }

            if (this.IsRotating)
            {
                return;
            }

            // Avoid trying to animate a frozen instance.
            if (_viewport.Camera.IsFrozen)
            {
                _viewport.Camera = this.CreateCamera();
            }

            PerspectiveCamera camera = _viewport.Camera as PerspectiveCamera;

            // Create the animations.
            DoubleAnimation frontAnimation, backAnimation;

            this.PrepareForRotation(out frontAnimation, out backAnimation);
            Point3DAnimation cameraZoomAnim = this.CreateCameraAnimation();

            // Start the animations.
            _frontRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, frontAnimation);
            _backRotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, backAnimation);
            camera.BeginAnimation(PerspectiveCamera.PositionProperty, cameraZoomAnim);

            this.IsRotating = true;
        }
        public void Update(PerspectiveCamera perspectiveCamera, Seconds elapsed)
        {
            for (var i = 0; i < this.ShadowMaps.Count; i++)
            {
                var shadowMapCascade = this.ShadowMaps[i];

                this.Frustum.ResetToViewVolume();
                this.Frustum.Transform(perspectiveCamera.InverseViewProjection);
                shadowMapCascade.GlobalShadowMatrix = CreateGlobalShadowMatrix(shadowMapCascade.SurfaceToLightVector, this.Frustum);

                for (var cascadeIndex = 0; cascadeIndex < shadowMapCascade.CascadeSplits.Length; cascadeIndex++)
                {
                    this.Frustum.ResetToViewVolume();
                    // Transform to world space
                    this.Frustum.Transform(perspectiveCamera.InverseViewProjection);

                    // Slice the frustum
                    var nearZ = cascadeIndex == 0 ? 0.0f : shadowMapCascade.CascadeDistances[cascadeIndex - 1];
                    var farZ  = shadowMapCascade.CascadeDistances[cascadeIndex];
                    this.Frustum.Slice(nearZ, farZ);

                    // Place a camera at the intersection of bounding sphere of the frustum and the ray
                    // from the frustum's center in the direction of the surface to light vector
                    shadowMapCascade.ShadowCameras[cascadeIndex].CoverFrustum(shadowMapCascade.SurfaceToLightVector, this.Frustum, shadowMapCascade.Resolution);

                    // ViewProjection matrix of the shadow camera that transforms to texture space [0, 1] instead of [-1, 1]
                    var shadowMatrix = shadowMapCascade.ShadowCameras[cascadeIndex].ViewProjection * TexScaleTransform;

                    // Store the split distance in terms of view space depth
                    var clipDistance = perspectiveCamera.FarPlane - perspectiveCamera.NearPlane;
                    shadowMapCascade.CascadeSplits[cascadeIndex] = perspectiveCamera.NearPlane + (farZ * clipDistance);

                    // Find scale and offset of this cascade in world space
                    var invCascadeMat = Matrix.Invert(shadowMatrix);
                    var cascadeCorner = ScaleToVector3(Vector4.Transform(Vector3.Zero, invCascadeMat));
                    cascadeCorner = ScaleToVector3(Vector4.Transform(cascadeCorner, shadowMapCascade.GlobalShadowMatrix));

                    // Do the same for the upper corner
                    var otherCorner = ScaleToVector3(Vector4.Transform(Vector3.One, invCascadeMat));
                    otherCorner = ScaleToVector3(Vector4.Transform(otherCorner, shadowMapCascade.GlobalShadowMatrix));

                    // Calculate the scale and offset
                    var cascadeScale = Vector3.One / (otherCorner - cascadeCorner);
                    shadowMapCascade.CascadeOffsets[cascadeIndex] = new Vector4(-cascadeCorner, 0.0f);
                    shadowMapCascade.CascadeScales[cascadeIndex]  = new Vector4(cascadeScale, 1.0f);
                }
            }
        }
Example #25
0
        protected override void MouseDown(MapViewport viewport, PerspectiveCamera camera, ViewportEvent e)
        {
            if (e.Button != MouseButtons.Left)
            {
                return;
            }

            e.Handled = true;

            // First, get the ray that is cast from the clicked point along the viewport frustrum
            var(start, end) = camera.CastRayFromScreen(new Vector3(e.X, e.Y, 0));
            var ray = new Line(start, end);

            // Grab all the elements that intersect with the ray
            var hits = Selection.Where(x => x.Copy.BoundingBox.IntersectsWith(ray));

            // Sort the list of intersecting elements by distance from ray origin
            var clickedFace = hits
                              .SelectMany(x => x.Copy.Faces.Select(f => new { Solid = x, Face = f }))
                              .Select(x => new { Item = x, Intersection = GetIntersectionPoint(x.Face, ray) })
                              .Where(x => x.Intersection != null)
                              .OrderBy(x => (x.Intersection.Value - ray.Start).Length())
                              .Select(x => x.Item)
                              .FirstOrDefault();


            var faces = new List <SolidFace>();

            if (clickedFace != null)
            {
                if (KeyboardState.Shift)
                {
                    faces.AddRange(clickedFace.Solid.Copy.Faces.Select(x => new SolidFace(clickedFace.Solid, x)));
                }
                else
                {
                    faces.Add(new SolidFace(clickedFace.Solid, clickedFace.Face));
                }
            }

            if (!KeyboardState.Ctrl)
            {
                ClearSelection();
            }
            _selectedFaces.AddRange(faces);

            Invalidate();
        }
        async void InitializeAsync()
        {
            var camera = new PerspectiveCamera();

            camera.FarPlaneDistance  = 500;
            camera.NearPlaneDistance = 1;
            camera.Position          = new Point3D(-5, -10, 5);
            camera.LookDirection     = new Vector3D(1, 2, -1);
            camera.UpDirection       = new Vector3D(0, 0, 1);
            mainViewport.Camera      = camera;
            mainViewport.BuildScene  = viewPort =>
            {
                //viewPort.Children.Add(new ModelVisual3D { Content = new DirectionalLight(Colors.White, new Vector3D(-1, -2, -4)) });
                //viewPort.Children.Add(new ModelVisual3D { Content = new DirectionalLight(Colors.White, new Vector3D(1, 2, 4)) });
                viewPort.Children.Add(new ModelVisual3D {
                    Content = new AmbientLight(Colors.White)
                });
                viewPort.Children.Add(new ModelVisual3D
                {
                    Content = new Func <GeometryModel3D>(() =>
                    {
                        var mesh = new MeshGeometry3D();
                        foreach (var p in new[] { new Point3D(-1, -1, 0), new Point3D(1, -1, 0), new Point3D(-1, 1, 0), new Point3D(1, 1, 0) })
                        {
                            mesh.Positions.Add(p);
                        }
                        foreach (var i in new[] { 0, 1, 3, 0, 3, 2, 0, 2, 3, 0, 3, 1 })
                        {
                            mesh.TriangleIndices.Add(i);
                        }
                        for (int i = 0; i < mesh.TriangleIndices.Count; i++)
                        {
                            mesh.Normals.Add(new Vector3D(0, 0, i * 2 < mesh.TriangleIndices.Count ? 1 : -1));
                        }
                        mesh.Freeze();
                        var brush = new SolidColorBrush(Colors.LightYellow)
                        {
                            Opacity = 0.5
                        };
                        var model = new GeometryModel3D(mesh, new DiffuseMaterial(brush));
                        model.Freeze();
                        return(model);
                    })()
                });
            };
            mainViewport.OnMessage = s => labelInfo.Content = s;
            await mainViewport.Load("");
        }
Example #27
0
        public void HandleInput(PerspectiveCamera camera, KeyboardInput keyboard, MouseInput mouse)
        {
            if (mouse.JustPressed(MouseButtons.Left))
            {
                this.selecting = true;
                this.SelectionSystem.StartSelection(camera, mouse.Position);

                Debug.WriteLine("Selection started");
            }
            else if (this.selecting && !mouse.Hold(MouseButtons.Left))
            {
                this.selecting = false;
                var selected = new List <Entity>();
                this.SelectionSystem.EndSelection(camera, mouse.Position, selected);

                foreach (var entity in selected)
                {
                    Debug.WriteLine($"Selected {entity}");
                    this.selectedFighter = this.fighters.IndexOf(entity);
                }

                Debug.WriteLine("Selection finished");
            }


            if (mouse.Click(MouseButtons.Right))
            {
                var mouseWorldPosition = camera.Pick(mouse.Position, 0.0f);
                if (mouseWorldPosition.HasValue && this.selectedFighter < this.fighters.Count)
                {
                    var entity = this.fighters[this.selectedFighter];

                    if (this.FlightPlans.TryGet(entity, out var flightPlan))
                    {
                        var finalManeuver = (LerpManeuver)flightPlan.Maneuvers.Last();
                        ManeuverPlanner.PlanMoveTo(flightPlan.Maneuvers, finalManeuver.TargetPosition, finalManeuver.TargetYaw, finalManeuver.TargetPitch, mouseWorldPosition.Value, this.linearAcceleration, this.angularAcceleration);
                    }
                    else
                    {
                        var pose      = this.Containers.Get <ComponentContainer <Pose> >().Get(entity);
                        var maneuvers = new Queue <IManeuver>();
                        ManeuverPlanner.PlanMoveTo(maneuvers, pose.Position, pose.Yaw, pose.Pitch, mouseWorldPosition.Value, this.linearAcceleration, this.angularAcceleration);

                        this.Factories.Get <FlightPlanFactory>().Construct(entity, maneuvers);
                    }
                }
            }
        }
Example #28
0
        /// <summary>
        /// RenderKinectPointsTriangle - renders kinect point cloud data using triangle meshes
        /// </summary>
        /// <returns>rendered point cloud model</returns>

        public GeometryModel3D[] RenderKinectPointsTriangle()
        {
            DirectionalLight  DirLight1    = new DirectionalLight();
            PerspectiveCamera Camera1      = new PerspectiveCamera();
            Model3DGroup      modelGroup   = new Model3DGroup();
            ModelVisual3D     modelsVisual = new ModelVisual3D();
            Viewport3D        myViewport   = new Viewport3D();

            //directional light
            DirLight1.Color     = Colors.White;
            DirLight1.Direction = new Vector3D(1, 1, 1);

            //camera specification
            Camera1.FarPlaneDistance  = 8000;
            Camera1.NearPlaneDistance = 100;
            Camera1.FieldOfView       = 10;
            Camera1.Position          = new Point3D(160, 120, -1000);
            Camera1.LookDirection     = new Vector3D(0, 0, 1);
            Camera1.UpDirection       = new Vector3D(0, -1, 0);

            //create triangle mesh
            int i = 0;

            for (int y = 0; y < 480; y += s)
            {
                for (int x = 0; x < 640; x += s)
                {
                    pts[i]           = Triangle(x, y, s);
                    pts[i].Transform = new TranslateTransform3D(0, 0, 0);
                    modelGroup.Children.Add(pts[i]);
                    i++;
                }
            }

            modelGroup.Children.Add(DirLight1);
            modelsVisual.Content        = modelGroup;
            myViewport.IsHitTestVisible = false;
            myViewport.Camera           = Camera1;
            myViewport.Children.Add(modelsVisual);
            viewportCanvas.Children.Add(myViewport);

            myViewport.Height = viewportCanvas.Height;
            myViewport.Width  = viewportCanvas.Width;
            Canvas.SetTop(myViewport, 0);
            Canvas.SetLeft(myViewport, 0);

            return(pts);
        }
Example #29
0
        private bool SetPerspectiveView(View3D bcfView, PerspectiveCamera camera)
        {
            var result = false;

            try
            {
                var zoom        = camera.FieldOfView;
                var direction   = RevitUtils.GetRevitXYZ(camera.CameraDirection);
                var upVector    = RevitUtils.GetRevitXYZ(camera.CameraUpVector);
                var viewPoint   = RevitUtils.GetRevitXYZ(camera.CameraViewPoint);
                var orientation = RevitUtils.ConvertBasePoint(ActiveDoc, viewPoint, direction, upVector, true);


                using (var trans = new Transaction(ActiveDoc))
                {
                    trans.Start("Set Orientation");
                    try
                    {
                        if (bcfView.CanResetCameraTarget())
                        {
                            bcfView.ResetCameraTarget();
                        }
                        bcfView.SetOrientation(orientation);
                        if (bcfView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                        {
                            var m_farClip = bcfView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                            m_farClip.Set(0);
                        }

                        bcfView.CropBoxActive  = true;
                        bcfView.CropBoxVisible = true;

                        trans.Commit();
                    }
                    catch (Exception)
                    {
                        trans.RollBack();
                    }
                }
                result = true;
            }
            catch (Exception)
            {
                // ignored
            }

            return(result);
        }
Example #30
0
        private void DoPostLoadInit()
        {
            // Viewport initialization - Adjust the camera
            PerspectiveCamera camera = _viewport.Camera as PerspectiveCamera;

            if (UseReflection)
            {
                camera.Position      = new Point3D(0, 0.5, 4);
                camera.LookDirection = new Vector3D(0, 0, -4);
            }
            else
            {
                camera.Position      = new Point3D(0, 0, 4);
                camera.LookDirection = new Vector3D(0, 0, -4);
            }
        }
        private static void OnCameraChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ElementFlow ef = d as ElementFlow;

            PerspectiveCamera camera = e.NewValue as PerspectiveCamera;

            if (camera == null)
            {
                throw new ArgumentNullException("e", "The Camera cannot be null");
            }

            if (ef.IsLoaded)
            {
                ef.Viewport.Camera = camera;
            }
        }
Example #32
0
        public MainViewModel()
        {
            Title = "Instancing Demo";            

            // camera setup
            Camera = new PerspectiveCamera { Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0) };

            // setup lighting            
            this.AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            this.DirectionalLightColor = (Color4)Color.White;
            this.DirectionalLightDirection = new Vector3(-2, -5, -2);

            // scene model3d
            var b1 = new MeshBuilder(); 
            b1.AddBox(new Vector3(0, 0, 0), 0.8, 0.8, 0.5, BoxFaces.All);
            Model = b1.ToMeshGeometry3D();

            var l1 = new LineBuilder();
            l1.AddBox(new Vector3(0, 0, 0), 0.8, 0.8, 0.5);
            Lines = l1.ToLineGeometry3D();   

            int num = 10;
            var instances = new List<Matrix>();
            for (int i = -num; i < num; i++)
            {
                for (int j = -num; j < num; j++)
                {
                    instances.Add(Matrix.Translation(new Vector3(i / 1.0f, j / 1.0f, 0f)));
                }
            }
            ModelInstances = instances;
            SubTitle = "Number of Instances: " + instances.Count.ToString();

            // model trafo
            ModelTransform = Media3D.Transform3D.Identity;// new Media3D.RotateTransform3D(new Media3D.AxisAngleRotation3D(new Vector3D(0, 0, 1), 45));

            // model material
            ModelMaterial = PhongMaterials.Glass;

            RenderTechniquesManager = new DefaultRenderTechniquesManager();
            RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn];
            EffectsManager = new DefaultEffectsManager(RenderTechniquesManager);
        }
 public BehindViewBehavior(PerspectiveCamera camera, Dancer leadDancer)
 {
     _camera = camera;
     _leadDancer = leadDancer;
 }
Example #34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Viewport3DX" /> class.
        /// </summary>
        public Viewport3DX()
        {
            this.perspectiveCamera = new PerspectiveCamera();
            this.orthographicCamera = new OrthographicCamera();
            this.perspectiveCamera.Reset();
            this.orthographicCamera.Reset();

            this.Camera = this.Orthographic ? (ProjectionCamera)this.orthographicCamera : this.perspectiveCamera;

            //this.Children = new Element3DCollection();

            this.rotateHandler = new RotateHandler(this);
            this.panHandler = new PanHandler(this);
            this.zoomHandler = new ZoomHandler(this);
            this.changeFieldOfViewHandler = new ZoomHandler(this, true);
            this.zoomRectangleHandler = new ZoomRectangleHandler(this);

            this.CommandBindings.Add(new CommandBinding(ViewportCommands.ZoomExtents, this.ZoomExtentsHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.SetTarget, this.SetTargetHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.Reset, this.ResetHandler));

            this.CommandBindings.Add(new CommandBinding(ViewportCommands.Zoom, this.zoomHandler.Execute));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.Pan, this.panHandler.Execute));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.Rotate, this.rotateHandler.Execute));
            this.CommandBindings.Add(
                new CommandBinding(ViewportCommands.ChangeFieldOfView, this.changeFieldOfViewHandler.Execute));
            this.CommandBindings.Add(
                new CommandBinding(ViewportCommands.ZoomRectangle, this.zoomRectangleHandler.Execute));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.BottomView, this.BottomViewHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.TopView, this.TopViewHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.FrontView, this.FrontViewHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.BackView, this.BackViewHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.LeftView, this.LeftViewHandler));
            this.CommandBindings.Add(new CommandBinding(ViewportCommands.RightView, this.RightViewHandler));

            this.SetDefaultGestures();

            this.fpsWatch.Start();

            this.renderingEventListener = new RenderingEventListener(this.OnCompositionTargetRendering);

            this.Loaded += this.ControlLoaded;
            this.Unloaded += this.ControlUnloaded;
        }
Example #35
0
 public TrackballControls(PerspectiveCamera camera)
 {
     // TODO: Complete member initialization
     this.camera = camera;
 }
Example #36
0
        private void Visinfo_Save_Click(object sender, RoutedEventArgs e)
        {
            var m = new VisualizationInfo();
            var c = new Component();
            c.IfcGuid = "1gF16zAF1DSPP1$Ex04e4k";
            c.OriginatingSystem = "DDS-CAD";

            m.Components.Add(c);

            var p = new PerspectiveCamera();
            p.CameraViewPoint.X = -732.062499964083;
            p.CameraViewPoint.Y = -1152.1249999640554;
            p.CameraViewPoint.Z = 1452.1249999640554;

            p.CameraDirection.X = 0.57735026918962573;
            p.CameraDirection.Y = 0.57735026918962573;
            p.CameraDirection.Z = -0.57735026918962573;

            p.CameraUpVector.X = 0.40824829046386307;
            p.CameraUpVector.Y = 0.40824829046386307;
            p.CameraUpVector.Z = 0.81649658092772615;

            p.FieldOfView = 99.121698557632413;

            m.PerspectiveCamera = p;
            m.OrthogonalCamera = null;

            m.Lines = null;
            m.ClippingPlanes = null;

            m.SaveToFile(Filename(@"viewpoint.generated.bcfv"));
        }
Example #37
0
        static IRender GetRender(int quantity)
        {
            List<ICamera> camersList = new List<ICamera>();

            for(int i = 0; i < quantity; i++)
            {
                Size resolution = new Size(640, 480);
                Point3D position = new Point3D(0, 0, 5000);
                double focus = 1000;
                SizeF projectionWindow = new SizeF(200, 150);
                double aroundOZ = -(Math.PI * 2.0) * (((double)i) / quantity);
                Rotation rotation = new Rotation(aroundOZ, 0, -Math.PI / 2.3);
                PerspectiveCamera camera = new PerspectiveCamera(position, rotation, projectionWindow, resolution, focus);
                camersList.Add(camera);
            }
            return new EOculusRender(CreateScene3(), new Size(800, 600), camersList.GetEnumerator());
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
			#region += Launched chrome.app.window
			// X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServerAppWindow\ChromeTCPServerAppWindow\Application.cs
			dynamic self = Native.self;
			dynamic self_chrome = self.chrome;
			object self_chrome_socket = self_chrome.socket;

			if (self_chrome_socket != null)
			{

				ChromeTCPServer.TheServerWithAppWindow.Invoke(AppSource.Text);

				return;
			}
			#endregion

			// would a device be able to stream photos from one device
			// into other over rtc?



			// should the first frame of the async app to be loaded
			// be a load progress screen to prepare the service worker?

			// this project is the first
			// template for hybrid vr apps.
			// it is based on webview/javascript/threejs for android

			// will future C# allow virtual code inheritance?
			// for now lets do copy n paste?

			body.style.margin = "0px";
            body.style.overflow = IStyle.OverflowEnum.hidden;
            body.Clear();



            // https://github.com/turban/photosphere/blob/gh-pages/stolanuten.html

            var scene = new THREE.Scene();


            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(1920, 1080);
            // the thing you attach to dom
            renderer.domElement.AttachToDocument();


            var sphere = new Mesh(
                new SphereGeometry(100, 20, 20),
                new MeshBasicMaterial(
                    new
                    {
                        map = THREE.ImageUtils.loadTexture(new WebGLTurbanPhotosphere.HTML.Images.FromAssets.stolanuten().src)
                    }
                )
            );
            sphere.scale.x = -1;
            sphere.AttachTo(scene);

            var camera = new PerspectiveCamera(75, window.aspect, 1, 1000);
            camera.position.x = 0.1;

            var lon0 = -45.0;
            var lon1 = 0.0;

            var lon = new sum(
                 () => lon0,
                 () => lon1
             );

            var lat0 = 0.0;
            var lat1 = 0.0;

            // or could we do it with byref or pointers?
            var lat = new sum(
                () => lat0,
                () => lat1
            );

            var phi = 0.0;
            var theta = 0.0;

            var camera_rotation_z = 0.0;


            //var controls = new THREE.OrbitControls(camera, renderer.domElement);



            var effect = new THREE.OculusRiftEffect(
 renderer, new
 {
     worldScale = 100,

     //HMD
 }
 );
            effect.setSize(1920, 1080);


            window.onframe +=
                delegate
                {
                    phi = THREE.Math.degToRad(90 - lat);
                    theta = THREE.Math.degToRad(lon);

                    var target = new THREE.Vector3(0, 0, 0);
                    target.x = 500 * Math.Sin(phi) * Math.Cos(theta);
                    target.y = 500 * Math.Cos(phi);
                    target.z = 500 * Math.Sin(phi) * Math.Sin(theta);

                    camera.lookAt(target);
                    camera.rotation.z += camera_rotation_z;

                    //renderer.render(scene, camera);
                    effect.render(scene, camera);
                };



            new { }.With(
                 async delegate
                 {
                     retry:

                     var s = (double)Native.window.Width / 1920.0;


                     Native.document.body.style.transform = "scale(" + s + ")";
                     Native.document.body.style.transformOrigin = "0% 0%";

                     await Native.window.async.onresize;
                     goto retry;
                 }
               );




            // we still have to add the layman acceleratomerer thingy
            // later we could connect the component to the chromevr api?
            // https://github.com/turban/photosphere


            // is the roslyn build ready for android/java?
            // no, we did fix the while break for jsc rewrrite mode
            // by not for java.
            // lets rebuild scriptcorelib with non roslyn to bypass the issue for now.


            var compassHeadingOffset = 0.0;
            var compassHeadingInitialized = 0;

            #region compassHeading
            // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeading\TestCompassHeading\Application.cs
            Native.window.ondeviceorientation +=
              dataValues =>
              {
                  // Convert degrees to radians
                  var alphaRad = dataValues.alpha * (Math.PI / 180);
                  var betaRad = dataValues.beta * (Math.PI / 180);
                  var gammaRad = dataValues.gamma * (Math.PI / 180);

                  // Calculate equation components
                  var cA = Math.Cos(alphaRad);
                  var sA = Math.Sin(alphaRad);
                  var cB = Math.Cos(betaRad);
                  var sB = Math.Sin(betaRad);
                  var cG = Math.Cos(gammaRad);
                  var sG = Math.Sin(gammaRad);

                  // Calculate A, B, C rotation components
                  var rA = -cA * sG - sA * sB * cG;
                  var rB = -sA * sG + cA * sB * cG;
                  var rC = -cB * cG;

                  // Calculate compass heading
                  var compassHeading = Math.Atan(rA / rB);

                  // Convert from half unit circle to whole unit circle
                  if (rB < 0)
                  {
                      compassHeading += Math.PI;
                  }
                  else if (rA < 0)
                  {
                      compassHeading += 2 * Math.PI;
                  }

                  /*
                  Alternative calculation (replacing lines 99-107 above):

                    var compassHeading = Math.atan2(rA, rB);

                    if(rA < 0) {
                      compassHeading += 2 * Math.PI;
                    }
                  */

                  // Convert radians to degrees
                  compassHeading *= 180 / Math.PI;

                  // Compass heading can only be derived if returned values are 'absolute'

                  // X:\jsc.svn\examples\javascript\android\Test\TestCompassHeadingWithReset\TestCompassHeadingWithReset\Application.cs

                  //Native.document.body.innerText = new { compassHeading }.ToString();
                  if (compassHeadingInitialized > 0)
                  {
                      lon1 = compassHeading - compassHeadingOffset;
                  }
                  else
                  {
                      compassHeadingOffset = compassHeading;
                      compassHeadingInitialized++;
                  }

              };
            #endregion

            #region gamma
            Native.window.ondeviceorientation +=
                //e => Native.body.innerText = new { e.alpha, e.beta, e.gamma }.ToString();
                //e => lon = e.gamma;
                e =>
                {
                    lat1 = e.gamma;

                    // after servicing a running instance would be nice
                    // either by patching or just re running the whole iteration in the backgrou
                    camera_rotation_z = e.beta * 0.02;
                };
            #endregion



            #region camera rotation
            var old = new { clientX = 0, clientY = 0 };

            Native.document.body.ontouchstart +=
                e =>
                {
                    var n = new { e.touches[0].clientX, e.touches[0].clientY };
                    old = n;
                };

            Native.document.body.ontouchmove +=
                    e =>
                    {
                        var n = new { e.touches[0].clientX, e.touches[0].clientY };

                        e.preventDefault();

                        lon0 += (n.clientX - old.clientX) * 0.2;
                        lat0 -= (n.clientY - old.clientY) * 0.2;

                        old = n;
                    };


            Native.document.body.onmousemove +=
                e =>
                {
                    e.preventDefault();

                    if (Native.document.pointerLockElement == Native.document.body)
                    {
                        lon0 += e.movementX * 0.1;
                        lat0 -= e.movementY * 0.1;

                        //Console.WriteLine(new { lon, lat, e.movementX, e.movementY });
                    }
                };


            Native.document.body.onmouseup +=
              e =>
              {
                  //drag = false;
                  e.preventDefault();
              };

            Native.document.body.onmousedown +=
                e =>
                {
                    //e.CaptureMouse();

                    //drag = true;
                    e.preventDefault();
                    Native.document.body.requestPointerLock();

                };


            Native.document.body.ondblclick +=
                e =>
                {
                    e.preventDefault();

                    Console.WriteLine("requestPointerLock");
                };

            #endregion

            Native.body.onmousewheel +=
                e =>
                {

                    camera_rotation_z += 0.1 * e.WheelDirection; ;

                };






            #region nonroslyn
            //           System.InvalidOperationException: internal compiler error at method
            //assembly: C:\util\jsc\bin\ScriptCoreLib.dll at
            //type: ScriptCoreLib.Shared.BCLImplementation.System.Linq.__OrderedEnumerable`1+<>c__DisplayClass0, ScriptCoreLib, Version=4.6.0.0, Culture=neutral, PublicKeyToken=null
            //method: <GetEnumerator>b__1
            //Java : Opcode not implemented: brtrue.s at ScriptCoreLib.Shared.BCLImplementation.System.Linq.__OrderedEnumerable`1+<>c__DisplayClass0.<GetEnumerator>b__1
            //   at jsc.Script.CompilerBase.BreakToDebugger(String e) in X:\jsc.internal.git\compiler\jsc\Languages\CompilerBase.cs:line 267
            //  at jsc.Script.CompilerBase.Break(String e) in X:\jsc.internal.git\compiler\jsc\Languages\CompilerBase.cs:line 227

            //           BCL needs another method, please define it.
            //Cannot call type without script attribute :
            //System.Threading.Monitor for Void Enter(System.Object, Boolean ByRef)
            //               used at
            //VRTurbanPhotosphere.Activities.ApplicationWebServiceActivity +<> c__DisplayClass24.< CreateServer > b__29 at offset 0018.
            //     If the use of this method is intended, an implementation should be provided with the attribute[Script(Implements = typeof(...)] set.You may have mistyped it.

            // compiler/android server/ needs to be non roslyn too
            // as we seem to not correctly detect the new lock IL?

            // ding didly doo.
            // other libs need to be also non roslyn.

            //            -compile:
            //    [javac]
            //        Compiling 727 source files to V:\bin\classes
            //[javac] V:\src\ScriptCoreLib\Extensions\LinqExtensions.java:38: error: bad operand types for binary operator '>'
            //    [javac]         if (((e > null)))
            //    [javac]                 ^

            // moving code from "Y:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Extensions\LinqExtensions.cs"

            //            -compile:
            //    [javac]
            //        Compiling 780 source files to V:\bin\classes
            //[javac] V:\src\ScriptCoreLib\Ultra\WebService\InternalGlobalExtensions___c__DisplayClass0.java:94: error: incompatible types
            //[javac]         for (num3 = 0; num3; num3++)
            //    [javac]                        ^
            //    [javac]
            //        required: boolean
            //[javac] found:    int

            //            -compile:
            //    [javac]
            //        Compiling 773 source files to V:\bin\classes
            //[javac] V:\src\ScriptCoreLib\Ultra\WebService\InternalGlobalExtensions___c__DisplayClass0.java:94: error: incompatible types
            //[javac]         for (num3 = 0; num3; num3++)
            //    [javac]                        ^



            //            -compile:
            //    [javac]
            //        Compiling 775 source files to V:\bin\classes
            //[javac] V:\src\ScriptCoreLib\Ultra\WebService\InternalGlobalExtensions___c__DisplayClass0.java:94: error: incompatible types
            //[javac]         for (num3 = 0; num3; num3++)
            //    [javac]                        ^
            //    [javac]
            //        required: boolean
            //[javac] found:    int
            #endregion

            //-compile:
            //    [javac] Compiling 727 source files to T:\bin\classes
            //    [javac] T:\src\ScriptCoreLib\Android\CoreAndroidWebServiceActivity.java:64: error: bad operand types for binary operator '>'
            //    [javac]         if (((this.__04000090__ActivityResult > null)))
            //    [javac]                                               ^
            //    [javac]   first type:  __Action_3<Integer,Integer,Intent>
            //    [javac]   second type: <null>

            // still on roslyn compiler?

        }
Example #39
0
 internal void add(PerspectiveCamera camera)
 {
     throw new NotImplementedException();
 }
Example #40
0
        public MainViewModel()
        {
            // titles
            Title = "Simple Demo";
            SubTitle = "WPF & SharpDX";

            // camera setup
            Camera = new PerspectiveCamera { 
                Position = new Point3D(3, 3, 5), 
                LookDirection = new Vector3D(-3, -3, -5), 
                UpDirection = new Vector3D(0, 1, 0),
                FarPlaneDistance = 5000000
            };

            // default render technique
            RenderTechniquesManager = new DefaultRenderTechniquesManager();
            RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn];
            EffectsManager = new DefaultEffectsManager(RenderTechniquesManager);

            // setup lighting            
            AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            DirectionalLightColor = Color.White;
            DirectionalLightDirection = new Vector3(-2, -5, -2);

            // floor plane grid
            Grid = LineBuilder.GenerateGrid();
            GridColor = SharpDX.Color.Black;
            GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5);

            // scene model3d
            var b1 = new MeshBuilder();            
            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All);
           
            var meshGeometry = b1.ToMeshGeometry3D();
            meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4()));
            Model = meshGeometry;

            // lines model3d
            var e1 = new LineBuilder();
            e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2);
            Lines = e1.ToLineGeometry3D();

            // model trafos
            Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            RedMaterial = PhongMaterials.Red;
            GreenMaterial = PhongMaterials.Green;
            BlueMaterial = PhongMaterials.Blue;
            //var diffColor = this.RedMaterial.DiffuseColor;
            //diffColor.Alpha = 0.5f;
            //this.RedMaterial.DiffuseColor = diffColor;   

            Points = new PointGeometry3D();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            for (int x = 0; x < 10; x++)
            {
                for (int y = 0; y < 10; y++)
                {
                    for (int z = 0; z < 10; z++)
                    {
                        ptIdx.Add(ptPos.Count);
                        ptPos.Add(new Vector3(x, y, z));
                    }
                }
            }

            Points.Positions = ptPos;
            Points.Indices = ptIdx;

            Text = new BillboardText3D();

            for (var i = 0; i < 50; i++)
            {
                for (var j = 0; j < 50; j++)
                {
                    Text.TextInfo.Add(new TextInfo("Hello World", new Vector3(i,j,0)));
                }
            }
        }
Example #41
0
        public MainViewModel()
        {
            // titles
            Title = "Simple Demo";
            SubTitle = "WPF & SharpDX";

            // camera setup
            Camera = new PerspectiveCamera { 
                Position = new Point3D(3, 3, 5), 
                LookDirection = new Vector3D(-3, -3, -5), 
                UpDirection = new Vector3D(0, 1, 0),
                FarPlaneDistance = 5000000
            };

            // Create a custom render techniques manager that 
            // only supports Phong and Blinn
            RenderTechniquesManager = new CustomRenderTechniquesManager();
            RenderTechnique = RenderTechniquesManager.RenderTechniques["RenderCustom"];
            EffectsManager = new CustomEffectsManager(RenderTechniquesManager);

            // setup lighting            
            AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            DirectionalLightColor = Color.White;
            DirectionalLightDirection = new Vector3(-2, -5, -2);

            // floor plane grid
            Grid = LineBuilder.GenerateGrid();
            GridColor = Color.Black;
            GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5);

            // scene model3d
            var b1 = new MeshBuilder();            
            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All);
           
            var meshGeometry = b1.ToMeshGeometry3D();
            meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4()));
            Model = meshGeometry;

            // lines model3d
            var e1 = new LineBuilder();
            e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2);
            Lines = e1.ToLineGeometry3D();

            // model transform
            Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            RedMaterial = PhongMaterials.Red;
            GreenMaterial = PhongMaterials.Green;
            BlueMaterial = PhongMaterials.Blue;

            Points = new PointGeometry3D();
            var ptPos = new Vector3Collection();
            var ptIdx = new IntCollection();

            Text = new BillboardText3D();

            for (int x = -5; x <= 5; x++)
            {
                for (int y = -5; y <= 5; y++)
                {
                    ptIdx.Add(ptPos.Count);
                    ptPos.Add(new Vector3(x, -1, y));
                    Text.TextInfo.Add(new TextInfo(string.Format("{0}:{1}", x, y), new Vector3(x, -1, y)));
                }
            }

            Points.Positions = ptPos;
            Points.Indices = ptIdx;
        }
 /// <summary>
 /// Creates a default perspective camera.
 /// </summary>
 /// <returns>A perspective camera.</returns>
 public static PerspectiveCamera CreateDefaultCamera()
 {
     var camera = new PerspectiveCamera();
     Reset(camera);
     return camera;
 }
Example #43
0
        public MainViewModel(Viewport3DX view)
        {
            this.view = view;            

            // ----------------------------------------------
            // set windows text
            Title = "Lighting Demo (WPF & SharpDX)";
            SubTitle = string.Format("Model: {0}, Number Lights: {1}", RenderTechnique, Light3D.LightCount);

            // ----------------------------------------------
            // camera setup
            Camera = new PerspectiveCamera { Position = new Point3D(8, 9, 7), LookDirection = new Vector3D(-5, -12, -5), UpDirection = new Vector3D(0, 1, 0) };

            // ----------------------------------------------
            // setup scene
            AmbientLightColor = new Color4(0.2f, 0.2f, 0.2f, 1.0f);

            Light1Color = (Color4)Color.White;
            Light2Color = (Color4)Color.Red;
            Light3Color = (Color4)Color.LightYellow;
            Light4Color = (Color4)Color.LightBlue;

            Light2Attenuation = new Vector3(1.0f, 0.5f, 0.10f);
            Light3Attenuation = new Vector3(1.0f, 0.1f, 0.05f);
            Light4Attenuation = new Vector3(1.0f, 0.2f, 0.0f);

            Light1Direction = new Vector3(0, -10, -10);
            Light1Transform = new Media3D.TranslateTransform3D(-Light1Direction.ToVector3D());
            Light1DirectionTransform = CreateAnimatedTransform2(-Light1Direction.ToVector3D(), new Vector3D(0, 1, -1), 24);
            //Light1DirectionTransform = Media3D.Transform3D.Identity;// CreateAnimatedTransform(new Vector3D(0, 1, 0), new Vector3D(1, 0, 1), 8);
            
            Light2Transform = CreateAnimatedTransform1(new Vector3D(-4, 0, 0), new Vector3D(0, 0, 1), 3);
            Light3Transform = CreateAnimatedTransform1(new Vector3D(0, 0, 4), new Vector3D(0, 1, 0), 5);
            Light4Transform = new Media3D.TranslateTransform3D(new Vector3D(0, 5, 0));
            Light4DirectionTransform = CreateAnimatedTransform1(new Vector3D(0, 1, 0), new Vector3D(1, 0, 1), 4);

            // ----------------------------------------------
            // light model3d
            var sphere = new MeshBuilder();
            sphere.AddSphere(new Vector3(0, 0, 0), 0.2);
            Sphere = sphere.ToMeshGeometry3D();
            LightModelMaterial = new PhongMaterial
            {
                AmbientColor = Color.Gray,
                DiffuseColor = Color.Gray,
                EmissiveColor = Color.Yellow,
                SpecularColor = Color.Black,
            };

            // ----------------------------------------------
            // scene model3d
            var b1 = new MeshBuilder(true, true, true);
            b1.AddSphere(new Vector3(0.25f, 0.25f, 0.25f), 0.75, 64, 64);
            b1.AddBox(-new Vector3(0.25f, 0.25f, 0.25f), 1, 1, 1, BoxFaces.All);
            b1.AddBox(-new Vector3(5.0f, 0.0f, 0.0f), 1, 1, 1, BoxFaces.All);
            b1.AddSphere(new Vector3(5f, 0f, 0f), 0.75, 64, 64);
            b1.AddCylinder(new Vector3(0f, -3f, -5f), new Vector3(0f, 3f, -5f), 1.2, 64);

            Model = b1.ToMeshGeometry3D();
            ModelTransform = new Media3D.TranslateTransform3D(0, 0, 0);
            ModelMaterial = PhongMaterials.Chrome;
            //ModelMaterial.TextureMap = new BitmapImage(new System.Uri(@"TextureCheckerboard2.jpg", System.UriKind.RelativeOrAbsolute));
            ModelMaterial.NormalMap = new BitmapImage(new System.Uri(@"TextureCheckerboard2_dot3.jpg", System.UriKind.RelativeOrAbsolute));
            //odelMaterial.NormalMap = new BitmapImage(new System.Uri(@"TextureNoise1_dot3.jpg", System.UriKind.RelativeOrAbsolute));


            // ----------------------------------------------
            // floor model3d
            var b2 = new MeshBuilder(true, true, true);
            b2.AddBox(new Vector3(0.0f, -5.0f, 0.0f), 15, 0.1, 15, BoxFaces.All);
            b2.AddSphere(new Vector3(-5.0f, -5.0f, 5.0f), 4, 64, 64);
            b2.AddCone(new Vector3(6f, -9f, -6f), new Vector3(6f, -1f, -6f), 4f, true, 64);
            Floor = b2.ToMeshGeometry3D();
            FloorTransform = new Media3D.TranslateTransform3D(0, 0, 0);
            FloorMaterial = new PhongMaterial
            {
                AmbientColor = Color.Gray,
                DiffuseColor = new Color4(0.75f, 0.75f, 0.75f, 1.0f), // Colors.LightGray,
                SpecularColor = Color.White,
                SpecularShininess = 100f,
                DiffuseMap = new BitmapImage(new System.Uri(@"TextureCheckerboard2.jpg", System.UriKind.RelativeOrAbsolute)),
                NormalMap = new BitmapImage(new System.Uri(@"TextureCheckerboard2_dot3.jpg", System.UriKind.RelativeOrAbsolute)),
            };
        }
Example #44
0
 public RenderPass(Scene scene, PerspectiveCamera camera)
 {
 }
Example #45
0
 private void BindCameras(object sender, EventArgs<IActor> args)
 {
     string name = args.Item.Name.Split('.')[0];
     PerspectiveCamera droneCamera = new PerspectiveCamera(name + CameraIdentifier, 0.1f, 128.0f, xna.MathHelper.PiOver4);
     SceneNode nodeCamera = _scene.RootNode.CreateChildSceneNode();
     _cameras.Add(droneCamera.Name, droneCamera);
     nodeCamera.AttachEntity(droneCamera);
     nodeCamera.AttachController(new SmoothController(args.Item));
 }
 public GameOverCameraBehavior(PerspectiveCamera camera, CongaLine congaLine)
 {
     _camera = camera;
     _congaLine = congaLine;
 }
Example #47
0
 internal void render(Scene scene, PerspectiveCamera camera)
 {
     throw new NotImplementedException();
 }