public void Render(float4x4 camMtx)
 {
     _rc.ModelView = camMtx*float4x4.CreateTranslation(0,0,0) * float4x4.Scale(40,15,40);
     _rc.SetShader(MoreShaders.GetSkyboxShader(_rc));
     _iTex = _rc.CreateTexture(imgData);
     _rc.Render(_syboxMesh);
 }
 public void AddChildShape(float4x4 localTransform, ISphereShapeImp shape)
 {
     Debug.WriteLine("AddSphere");
     var btChildShape = new SphereShape(shape.Radius);
     var btLocalTransform = Translater.Float4X4ToBtMatrix(localTransform);
     BtCompoundShape.AddChildShape(btLocalTransform, btChildShape);
 }
Exemple #3
0
        public static void AngleMatrix (float3 angles, ref float4x4 matrix)
        {
            float angle;
            float sr, sp, sy, cr, cp, cy;

            angle = angles[2];
            sy = (float)Math.Sin(angle);
            cy = (float)Math.Cos(angle);
            angle = angles[1];
            sp = (float)Math.Sin(angle);
            cp = (float)Math.Cos(angle);
            angle = angles[0];
            sr = (float)Math.Sin(angle);
            cr = (float)Math.Cos(angle);

            // matrix = (Z * Y) * X
            //matrix[0,0] = cp * cy;
            //matrix[1][0] = cp * sy;
            //matrix[2][0] = -sp;
            //matrix[0][1] = sr * sp * cy + cr * -sy;
            //matrix[1][1] = sr * sp * sy + cr * cy;
            //matrix[2][1] = sr * cp;
            //matrix[0][2] = (cr * sp * cy + -sr * -sy);
            //matrix[1][2] = (cr * sp * sy + -sr * cy);
            //matrix[2][2] = cr * cp;
            //matrix[0][3] = 0.0;
            //matrix[1][3] = 0.0;
            //matrix[2][3] = 0.0;

        }
 public void AddChildShape(float4x4 localTransform, ICylinderShapeImp shape)
 {
     var btHalfExtents = Translater.Float3ToBtVector3(shape.HalfExtents);
     var btChildShape = new CylinderShape(btHalfExtents);
     var btLocalTransform = Translater.Float4X4ToBtMatrix(localTransform);
     BtCompoundShape.AddChildShape(btLocalTransform, btChildShape);
 }
Exemple #5
0
 public static void VectorRotate(float3 in1, float4x4 in2, ref float3 vout)
 {
     
     //vout[0] = in1 * in2[0];// DotProduct(in1, in2[0]);
     //vout[1] = in1 * in2[1];// DotProduct(in1, in2[1]);
     //vout[2] = in1 * in2[2];// DotProduct(in1, in2[2]);
 }
        public void WeaponInput(float4x4 mtxcam)
        {
            //Schießen wenn Magazin != 0
            if (Input.Instance.IsButton(MouseButtons.Left))
            //if (Input.Instance.IsKeyUp(KeyCodes.Space))
            {

                if (_click)
               {
                   if (Magazin > 0)
                   {
                       Shoot(mtxcam);
                       Magazin--;
                   }
               }
                _click = false;
            }
            else
            {
                _click = true;
            }

            //Nachladen
            if (Input.Instance.IsButton(MouseButtons.Right))
            {
                Magazin = 10;
            }
        }
 public void AddChildShape(float4x4 localTransform, IBoxShapeImp shape)
 {
     Debug.WriteLine("AddBox");
     var btHalfExtents = Translater.Float3ToBtVector3(shape.HalfExtents);
     var btChildShape = new BoxShape(btHalfExtents);
     var btLocalTransform = Translater.Float4X4ToBtMatrix(localTransform);
     BtCompoundShape.AddChildShape(btLocalTransform, btChildShape);
 }
Exemple #8
0
 public void CheckCameraPosition(int blocksCount)
 {
     if(blocksCount > 3)
     {
         yOffset += speed;
         mtxOffset = float4x4.CreateTranslation(0, yOffset, 0);
     }
 }
 public Matrix Float4X4ToBtMatrix(float4x4 float4X4)
 {
     var retval = new Matrix();
     retval.set_Rows(0, new Vector4(float4X4.M11, float4X4.M12, float4X4.M13, float4X4.M14));
     retval.set_Rows(1, new Vector4(float4X4.M21, float4X4.M22, float4X4.M23, float4X4.M24));
     retval.set_Rows(2, new Vector4(float4X4.M31, float4X4.M32, float4X4.M33, float4X4.M34));
     retval.set_Rows(3, new Vector4(float4X4.M41, float4X4.M42, float4X4.M43, float4X4.M44));
     return retval;
 }
 public float4x4 BtMatrixToFloat4X4(Matrix btMatrix)
 {
     var retval = new float4x4(btMatrix.M11, btMatrix.M12, btMatrix.M13, btMatrix.M14,
         btMatrix.M21, btMatrix.M22, btMatrix.M23, btMatrix.M24,
         btMatrix.M31, btMatrix.M32, btMatrix.M33, btMatrix.M34,
         btMatrix.M41, btMatrix.M42, btMatrix.M43, btMatrix.M44
         );
     return retval;
 }
 public void AdjustModelScaleOffset()
 {
     AABBf? box = null;
     if (_sr == null || (box = _sr.GetAABB()) == null)
     {
         _modelScaleOffset = float4x4.Identity;
     }
     var bbox = ((AABBf) box);
     float scale = Math.Max(Math.Max(bbox.Size.x, bbox.Size.y), bbox.Size.z);
     _modelScaleOffset = float4x4.CreateScale(200.0f/scale)*float4x4.CreateTranslation(-bbox.Center);
 }
 public void CompoundShape()
 {
     var compShape = _world.AddCompoundShape(true);
     var box = _world.AddBoxShape(25);
     var sphere = _world.AddBoxShape(25);
     var matrixBox = float4x4.Identity;
     var matrixSphere = new float4x4(1, 0, 0, 2, 0, 1, 0, 2, 0, 0, 1, 2, 0, 0, 0, 1);
     compShape.AddChildShape(matrixBox, box);
     compShape.AddChildShape(matrixSphere, sphere);
     var rb = _world.AddRigidBody(1, new float3(0, 150, 0), float3.Zero, compShape);
     _numRB++;
 }
        public GameWorld(RenderContext rc)
        {
            _rc = rc;

            _currentGameState = (int)GameState.StartScreen;

            _camMatrix = float4x4.CreateTranslation(0, -400, 0);

            _gui = new GUI(rc, this);

            _player = new Player("Assets/rocket3.protobuf.model", rc);
            _player.SetShader("Assets/rocket3.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(5, 5));
            _player.SetCorrectionMatrix(float4x4.CreateRotationX((float)-Math.PI / 2) * float4x4.CreateTranslation(-30, 0, 0) * float4x4.Scale(0.5f));

            _room = new GameEntity("Assets/spacebox.obj.model", rc, 150, 1600, -1700);
            _room.SetShader(new float4(1, 1, 1, 1), "Assets/toon_room_7_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _room.SetCorrectionMatrix(float4x4.Scale(13, 8, 19));

            _furniture.Add(new GameEntity("Assets/rocket3.protobuf.model", rc, -1900, 0, -5000));
            _furniture[0].SetShader("Assets/rocket3.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[0].SetCorrectionMatrix(float4x4.Scale(5));

            _furniture.Add(new GameEntity("Assets/chair.protobuf.model", rc, 1600, 0, -4100, 0, 2.6f));
            _furniture[1].SetShader("Assets/chair.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[1].SetCorrectionMatrix(float4x4.Scale(29));

            _furniture.Add(new GameEntity("Assets/desk.protobuf.model", rc, 1500, 0, -4950));
            _furniture[2].SetShader("Assets/desk.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[2].SetCorrectionMatrix(float4x4.Scale(5));

            _furniture.Add(new GameEntity("Assets/bed.protobuf.model", rc, 1800, 0, 800));
            _furniture[3].SetShader("Assets/bed.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[3].SetCorrectionMatrix(float4x4.Scale(13));

            _furniture.Add(new GameEntity("Assets/drawer.protobuf.model", rc, -700, 0, 1850, 0, (float)Math.PI));
            _furniture[4].SetShader("Assets/drawer.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[4].SetCorrectionMatrix(float4x4.Scale(14));

            _furniture.Add(new GameEntity("Assets/football.obj.model", rc, -1200, 0, 1000));
            _furniture[5].SetShader("Assets/football.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[5].SetCorrectionMatrix(float4x4.Scale(4));

            _furniture.Add(new GameEntity("Assets/book.protobuf.model", rc, 500, 1030, -4950, 0, 1));
            _furniture[6].SetShader("Assets/book.png", "Assets/toon_generic_4_tex.png", new float4(0, 0, 0, 1), new float2(15, 15));
            _furniture[6].SetCorrectionMatrix(float4x4.Scale(35));

            _targets.Add(new Target("Assets/cube.obj.model", rc, 1500, 1500, -4950, (float)Math.PI / 4, (float)Math.PI / 4, (float)Math.PI / 4));
            _targets[0].SetCorrectionMatrix(float4x4.Scale(0.5f));
            _targets.Add(new Target("Assets/cube.obj.model", rc, -1200, 800, 1000, (float)Math.PI / 4, (float)Math.PI / 4, (float)Math.PI / 4));
            _targets[1].SetCorrectionMatrix(float4x4.Scale(0.5f));

            _maxScore = _targets.Count;
        }
 private void Shoot(float4x4 mtxcam)
 {
     var start = mtxcam.Column3.xyz;
     start.y += 0.1f;
     RigidBody tomatoRb = _world.AddRigidBody(1, start, float3.Zero, _sphereCollider);
     Tomato tomato = new Tomato(RC, tomatoRb.Position, float3.Zero, new float3(0.02f, 0.02f, 0.02f), _srTomato, tomatoRb, _game, _world);
     _game.LevelObjects.Add(tomato);
     float3 one = new float3(0, 0, 1);
     float3 to;
     float3.TransformVector(ref one, ref mtxcam, out to);
     float impuls = 70;
     tomatoRb.ApplyCentralImpulse = to * impuls;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Transformation"/> class. No SceneEntity will be set.
 /// </summary>
 public Transformation()
 {
     _hasParent = false;
        _transformMatrix = float4x4.Identity;
     _globalMatrix = _transformMatrix;
     _quaternion = Quaternion.Identity;
     _globalQuaternion = Quaternion.Identity;
        _globalScale = new float3(1,1,1);
        _localScale = new float3(1,1,1);
        _matrixDirty = false;
        _quaternionDirty = false;
        _eulerDirty = false;
 }
        public GameObject(RenderContext rc, float3 position, float3 rotation, float3 scaleFactor, SceneRenderer sc)
        {
            SceneRenderer = sc;
            _rc = rc;

            _scale = scaleFactor;
            ObjectMtx = float4x4.CreateRotationX(rotation.x)
                     *float4x4.CreateRotationY(rotation.y)
                     *float4x4.CreateRotationZ(rotation.z)
                     *float4x4.CreateTranslation(position);

            Rotation = rotation;
            Tag = "GameObject";
        }
 public AABBf? GetAABB()
 {
     AABBf? ret = null;
     _AABBXForm = float4x4.Identity;
     foreach (var soc in _sc.Children)
     {
         AABBf? nodeBox = VisitNodeAABB(soc);
         if (nodeBox != null)
         {
             if (ret == null)
             {
                 ret = nodeBox;
             }
             else
             {
                 ret = AABBf.Union((AABBf)ret, (AABBf)nodeBox);
             }
         }
     }
     return ret;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Transformation" /> class. Sets a SceneEntity for Transform.
 /// This is the recommended Constructor.
 /// </summary>
 /// <param name="entity">The SceneEntity that will be set in Transform.</param>
 public Transformation(SceneEntity entity)
 {
     if (entity.parent == null)
        {
        _hasParent = false;
        }
        else
        {
        _hasParent = true;
        }
        SceneEntity = entity;
        _transformMatrix = float4x4.Identity;
        _globalMatrix = _transformMatrix;
        _quaternion = Quaternion.Identity;
        _globalQuaternion = Quaternion.Identity;
        _globalScale = new float3(1,1,1);
        _localScale = new float3(1, 1, 1);
        // _entity = entity;
        _matrixDirty = false;
        _quaternionDirty = false;
        _eulerDirty = false;
 }
        /// <summary>
        /// Rotates the object on the X-Axis.
        /// This method is applied using a basic LINQ/Lambda expression.
        /// </summary>
        /// <param name="alpha">a float value representing an angle.</param>
        /// <param name="geo">Geometry geo. The geometry object you want to do the translations on.</param>
        /// <returns>bool - true if the operation succeeded.</returns>
        public static bool RotateX(float alpha, ref Geometry geo)
        {
            try
            {
                double cos = System.Math.Cos((double)alpha);
                double sin = System.Math.Sin((double)alpha);

                float4x4 transfMatrix = new float4x4(
                        new float4(1f, 0f, 0f, 0f),
                        new float4(0f, (float)cos, (float)sin, 0f),
                        new float4(0f, (float)-sin, (float)cos, 0f),
                        new float4(0f, 0f, 0f, 1f)
                    );

                geo._LvertexVal = geo._LvertexVal.Select(tmpVertValue => transfMatrix * tmpVertValue).ToList();

                return true;
            }
            catch (Exception)
            {
                return false;
                throw;
            }
        }
        public GameEntity(String meshPath, RenderContext rc, float posX = 0, float posY = 0, float posZ = 0, float angX = 0, float angY = 0, float angZ = 0)
        {
            if (meshPath.Contains("protobuf"))
            {
                _ser = new FuseeSerializer();
                using (var file = File.OpenRead(meshPath))
                {
                    _mesh = _ser.Deserialize(file, null, typeof(Mesh)) as Mesh;
                }
            }
            else
            {
                _mesh = MeshReader.LoadMesh(meshPath);
            }

            _rc = rc;

            Position = float4x4.CreateRotationX(angX) *
                        float4x4.CreateRotationY(angY) *
                        float4x4.CreateRotationZ(angZ) *
                        float4x4.CreateTranslation(posX, posY, posZ);

            SetShader(_color);
        }
        public IGeneric6DofConstraintImp AddGeneric6DofConstraint(IRigidBodyImp rigidBodyA, IRigidBodyImp rigidBodyB, float4x4 frameInA, float4x4 frameInB, bool useReferenceFrameA = false)
        {
            var rigidBodyAImp = (RigidBodyImp)rigidBodyA;
            var btRigidBodyA = rigidBodyAImp._rbi;
            var rigidBodyBImp = (RigidBodyImp)rigidBodyB;
            var btRigidBodyB = rigidBodyAImp._rbi;

            Matrix matrixA = Translater.Float4X4ToBtMatrix(frameInA);
            Matrix matrixB = Translater.Float4X4ToBtMatrix(frameInB);

            var btGeneric6DofConstraint = new Generic6DofConstraint(btRigidBodyA, btRigidBodyB, matrixA, matrixB, useReferenceFrameA);
            BtWorld.AddConstraint(btGeneric6DofConstraint);

            var retval = new Generic6DofConstraintImp();
            retval._g6dofci = btGeneric6DofConstraint;
            btGeneric6DofConstraint.UserObject = retval;
            return retval;
        }
        void Control_MouseUp( object sender, MouseEventArgs e )
        {
            m_ButtonsDown = MouseButtons.None;	// Remove all buttons

            // Update the mouse and camera states when button is released
            m_ButtonDownTransform = CameraTransform;
            m_ButtonDownTargetObjectMatrix = TargetObjectMatrix;
            m_ButtonDownMousePosition = ComputeNormalizedScreenPosition( e.X, e.Y, (float) m_Control.Width / m_Control.Height );
            m_ButtonDownCameraTargetDistance = CameraTargetDistance;
            m_ButtonDownNormalizedTargetDistance = NormalizeTargetDistance( m_ButtonDownCameraTargetDistance );
        }
Exemple #23
0
 public void SetupForJob(Camera camera)
 {
     this.WorldToCameraMatrix    = camera.worldToCameraMatrix;
     this.CameraProjectionMatrix = camera.projectionMatrix;
 }
        /*public void AddChildShape(float4x4 localTransform, CollisionShape childShape)
         * {
         *  var type = childShape.GetType().ToString();
         *  Debug.WriteLine(type);
         *  switch (type)
         *  {
         *      case "Fusee.Engine.BoxShape":
         *          Debug.WriteLine(type);
         *          var b = new BoxShape();
         *          b = (BoxShape) childShape;
         *          var shape = b._boxShapeImp;
         *          _compoundShapeImp.AddChildShape(localTransform, shape);
         *          break;
         *      default:
         *          Debug.WriteLine("default");
         *          var empty = new BoxShape();
         *          _compoundShapeImp.AddChildShape(localTransform, empty._boxShapeImp);
         *          break;
         *  }
         * }*/

        /// <summary>
        /// Adds a box as a child shape.
        /// </summary>
        /// <param name="localTransform">The local transformation of the child shape.</param>
        /// <param name="childShape">The child shape.</param>
        public void AddChildShape(float4x4 localTransform, BoxShape childShape)
        {
            _compoundShapeImp.AddChildShape(localTransform, childShape._boxShapeImp);
        }
        protected override void OnUpdate()
        {
            var worldToLocalComponents = m_ComponentGroup.ToComponentDataArray <WorldToLocal>(Allocator.TempJob);

            var counter = 0;

            Entities.With(m_ComponentGroup).ForEach((Entity entity, SpriteSkin spriteSkin) =>
            {
                var sr                  = EntityManager.GetSharedComponentData <SpriteComponent>(entity);
                var vertexBuffer        = EntityManager.GetBuffer <Vertex>(entity);
                var boneTransformBuffer = EntityManager.GetBuffer <BoneTransform>(entity);
                var currentSprite       = sr.Value;
                var currentWorldToLocal = worldToLocalComponents[counter];
                Sprite sprite           = null;
                if (spriteSkin != null)
                {
                    var spriteRenderer = spriteSkin.spriteRenderer;
                    var isValid        = spriteRenderer.enabled && spriteSkin.isValid;
                    var isVisible      = spriteRenderer.isVisible || spriteSkin.ForceSkinning;

                    if (!isValid)
                    {
                        spriteSkin.DeactivateSkinning();
                    }
                    else if (isVisible)
                    {
                        spriteSkin.ForceSkinning = false;
                        sprite = spriteRenderer.sprite;
                        float4x4 worldToLocal = spriteSkin.transform.worldToLocalMatrix;

                        if (vertexBuffer.Length != sprite.GetVertexCount())
                        {
                            vertexBuffer = PostUpdateCommands.SetBuffer <Vertex>(entity);
                            vertexBuffer.ResizeUninitialized(sprite.GetVertexCount());
                        }

                        InternalEngineBridge.SetDeformableBuffer(spriteRenderer, vertexBuffer.Reinterpret <Vector3>().AsNativeArray());

                        if (boneTransformBuffer.Length != spriteSkin.boneTransforms.Length)
                        {
                            boneTransformBuffer = PostUpdateCommands.SetBuffer <BoneTransform>(entity);
                            boneTransformBuffer.ResizeUninitialized(spriteSkin.boneTransforms.Length);
                        }

                        for (var j = 0; j < boneTransformBuffer.Length; ++j)
                        {
                            boneTransformBuffer[j] = new BoneTransform()
                            {
                                Value = spriteSkin.boneTransforms[j].localToWorldMatrix
                            }
                        }
                        ;

                        PostUpdateCommands.SetComponent <WorldToLocal>(entity, new WorldToLocal()
                        {
                            Value = worldToLocal
                        });
                    }

                    if (currentSprite != sprite)
                    {
                        PostUpdateCommands.SetSharedComponent <SpriteComponent>(entity, new SpriteComponent()
                        {
                            Value = sprite
                        });
                    }

                    if (!spriteRenderer.enabled)
                    {
                        spriteSkin.ForceSkinning = true;
                    }
                }
            });
            worldToLocalComponents.Dispose();
        }
 public void UpdateProjectionMatrix()
 {
     projectionMatrix = Matrix4x4.Perspective(fov, aspect, nearClipPlane, farClipPlane);
 }
 public void UpdateProjectionMatrix()
 {
     projectionMatrix = Matrix4x4.Ortho(-size, size, -size, size, nearClipPlane, farClipPlane);
 }
Exemple #28
0
        public float GetHingeAngle(float4x4 transA, float4x4 transB)
        {
            var retval = _hci.GetHingeAngle(Translater.Float4X4ToBtMatrix(transA), Translater.Float4X4ToBtMatrix(transB));

            return(retval);
        }
        public void RenderAFrame()
        {
            if (_currentGameState != _lastGameState)
            {
                switch (_currentGameState)
                {
                case (int)GameState.StartScreen:
                    _camMatrix = float4x4.CreateTranslation(0, 0, 0);
                    _gui.ShowStartGUI();
                    break;

                case (int)GameState.Running:
                    _gui.ShowPlayGUI();
                    _player.SetPosition(float4x4.Identity);
                    break;

                case (int)GameState.GameOver:
                    foreach (var target in _targets)
                    {
                        target.SetInactive();
                    }
                    _gui.ShowStartGUI();
                    _gui.ShowOverGUI();
                    _camMatrix    = float4x4.CreateTranslation(0, 0, 0);
                    _player.Speed = 0;
                    break;
                }
                _lastGameState = _currentGameState;
            }

            if (_currentGameState == (int)GameState.Running)
            {
                _player.Move();
                _camMatrix = _player.GetCamMatrix();
                _player.Render(_camMatrix);

                int activeGoalCount = 0;
                foreach (var target in _targets)
                {
                    var distanceVector = _player.GetPositionVector() - target.GetPositionVector();
                    if (distanceVector.Length < 500)
                    {
                        target.SetActive();
                    }
                    if (target.GetStatus())
                    {
                        activeGoalCount++;
                    }
                    target.Render(_camMatrix);
                }
                _curScore = activeGoalCount;

                if (_curScore != _oldScore)
                {
                    _gui.UpdateScore();
                }

                _oldScore = _curScore;

                if (_curScore == _maxScore)
                {
                    _currentGameState = (int)GameState.GameOver;
                }
            }
            else
            {
                _camMatrix *= float4x4.CreateRotationY(0.02f);
            }

            foreach (var gameEntity in _furniture)
            {
                gameEntity.Render(_camMatrix);
            }

            _gui.Render();
        }
Exemple #30
0
 public void SetPosition(float4x4 position)
 {
     Position = position;
 }
Exemple #31
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            RC.Viewport(0, 0, Width, Height);

            #region Controls

            // Mouse and keyboard movement
            if (Input.Keyboard.LeftRightAxis != 0 || Input.Keyboard.UpDownAxis != 0)
            {
                _keys = true;
            }

            if (Input.Mouse.LeftButton)
            {
                _keys         = false;
                _angleVelHorz = -RotationSpeed * Input.Mouse.XVel * Time.DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * Input.Mouse.YVel * Time.DeltaTime * 0.0005f;
            }
            else if (Input.Touch.GetTouchActive(TouchPoints.Touchpoint_0))
            {
                _keys = false;
                float2 touchVel = Input.Touch.GetVelocity(TouchPoints.Touchpoint_0);
                _angleVelHorz = -RotationSpeed * touchVel.x * Time.DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * touchVel.y * Time.DeltaTime * 0.0005f;
            }
            else
            {
                if (_keys)
                {
                    _angleVelHorz = -RotationSpeed * Input.Keyboard.LeftRightAxis * Time.DeltaTime;
                    _angleVelVert = -RotationSpeed * Input.Keyboard.UpDownAxis * Time.DeltaTime;
                }
                else
                {
                    float curDamp = (float)System.Math.Exp(-Damping * Time.DeltaTime);
                    _angleVelHorz *= curDamp;
                    _angleVelVert *= curDamp;
                }
            }

            _angleHorz += _angleVelHorz;
            _angleVert += _angleVelVert;

            // Create the camera matrix and set it as the current ModelView transformation
            float4x4 mtxRot = float4x4.CreateRotationX(_angleVert) * float4x4.CreateRotationY(_angleHorz);
            float4x4 mtxCam = float4x4.LookAt(0, 0, -5, 0, 0, 0, 0, 1, 0);

            float4x4 view         = mtxCam * mtxRot;
            float4x4 perspective  = float4x4.CreatePerspectiveFieldOfView(_fovy, (float)Width / Height, ZNear, ZFar);
            float4x4 orthographic = float4x4.CreateOrthographic(Width, Height, ZNear, ZFar);


            RC.View       = view;
            RC.Projection = _canvasRenderMode == CanvasRenderMode.Screen ? orthographic : perspective;
            // Constantly check for interactive objects.
            if (!Input.Mouse.Desc.Contains("Android"))
            {
                _sih.CheckForInteractiveObjects(RC, Input.Mouse.Position, Width, Height);
            }

            if (Input.Touch.GetTouchActive(TouchPoints.Touchpoint_0) && !Input.Touch.TwoPoint)
            {
                _sih.CheckForInteractiveObjects(RC, Input.Touch.GetPosition(TouchPoints.Touchpoint_0), Width, Height);
            }

            #endregion Controls

            //Annotations will be updated according to circle positions.
            //Lines will be updated according to circle and annotation positions.

            RC.View       = view;
            RC.Projection = perspective;
            SceneNode canvas = _gui.Children[0];

            foreach (SceneNode child in canvas.Children)
            {
                if (!child.Name.Contains("MarkModelContainer"))
                {
                    continue;
                }

                //1. Calculate the circles canvas position.
                for (int k = 0; k < child.Children.Count; k++)
                {
                    SceneNode container = child.Children[k];

                    SceneNode circle  = container.Children[0];
                    UIInput   uiInput = _uiInput[k];

                    //the monkey's matrices
                    SceneNode monkey     = _scene.Children[0];
                    float4x4  model      = monkey.GetGlobalTransformation();
                    float4x4  projection = perspective;

                    float4x4 mvpMonkey = projection * view * model;

                    float3 clipPos         = float4x4.TransformPerspective(mvpMonkey, uiInput.Position); //divides by 2
                    float2 canvasPosCircle = new float2(clipPos.x, clipPos.y) * 0.5f + 0.5f;

                    canvasPosCircle.x      *= _canvasWidth;
                    canvasPosCircle.y      *= _canvasHeight;
                    uiInput.CircleCanvasPos = canvasPosCircle;

                    var pos = new float2(uiInput.CircleCanvasPos.x - (uiInput.Size.x / 2), uiInput.CircleCanvasPos.y - (uiInput.Size.y / 2)); //we want the lower left point of the rect that encloses the
                    circle.GetComponent <RectTransform>().Offsets = UIElementPosition.CalcOffsets(AnchorPos.Middle, pos, _canvasHeight, _canvasWidth, uiInput.Size);

                    //1.1   Check if circle is visible

                    PickResult newPick = _scenePicker.Pick(RC, new float2(clipPos.x, clipPos.y)).ToList().OrderBy(pr => pr.ClipPos.z).FirstOrDefault();

                    if (newPick != null && uiInput.AffectedTriangles[0] == newPick.Triangle) //VISIBLE
                    {
                        uiInput.IsVisible = true;

                        var effect = circle.GetComponent <DefaultSurfaceEffect>();
                        effect.SetDiffuseAlphaInShaderEffect(UIHelper.alphaVis);
                    }
                    else
                    {
                        uiInput.IsVisible = false;
                        var effect = circle.GetComponent <DefaultSurfaceEffect>();
                        effect.SetDiffuseAlphaInShaderEffect(UIHelper.alphaInv);
                    }

                    //1.2   Calculate annotation positions without intersections.
                    if (!uiInput.CircleCanvasPos.Equals(uiInput.CircleCanvasPosCache))
                    {
                        float yPosScale = uiInput.CircleCanvasPos.y / _canvasHeight;
                        yPosScale = (yPosScale - 0.5f) * 2f;
                        uiInput.AnnotationCanvasPos.y = uiInput.CircleCanvasPos.y - (UIHelper.AnnotationDim.y / 2) + (2 * UIHelper.AnnotationDim.y * yPosScale);

                        if (uiInput.CircleCanvasPos.x > _canvasWidth / 2) //RIGHT
                        {
                            uiInput.AnnotationCanvasPos.x = UIHelper.CanvasWidthInit - UIHelper.AnnotationDim.x - UIHelper.AnnotationDistToLeftOrRightEdge;
                        }
                        else
                        {
                            uiInput.AnnotationCanvasPos.x = UIHelper.AnnotationDistToLeftOrRightEdge;
                        }
                    }
                    _uiInput[k] = uiInput;
                }

                // 2.   Find intersecting annotations and correct their position in _uiInput.
                //      Disable rendering of annotation if its corresponding circle is not visible.
                for (int k = 0; k < child.Children.Count; k++)
                {
                    SceneNode container  = child.Children[k];
                    SceneNode annotation = container.Children[1];
                    UIInput   uiInput    = _uiInput[k];

                    if (uiInput.IsVisible)
                    {
                        if (!uiInput.CircleCanvasPos.Equals(uiInput.CircleCanvasPosCache))
                        {
                            Dictionary <int, float2> intersectedAnnotations = new Dictionary <int, float2>();
                            int iterations = 0;
                            CalculateNonIntersectingAnnotationPositions(ref uiInput, ref intersectedAnnotations, ref iterations);
                        }

                        annotation.GetComponent <NineSlicePlane>().Active = true;
                        foreach (Mesh comp in annotation.GetComponentsInChildren <Mesh>())
                        {
                            comp.Active = true;
                        }
                    }
                    else
                    {
                        annotation.GetComponent <NineSlicePlane>().Active = false;
                        foreach (Mesh comp in annotation.GetComponentsInChildren <Mesh>())
                        {
                            comp.Active = false;
                        }
                    }
                }

                // 3.   Update annotation positions on canvas and draw line
                for (int k = 0; k < child.Children.Count; k++)
                {
                    SceneNode container = child.Children[k];

                    SceneNode line    = container.Children[2];
                    UIInput   uiInput = _uiInput[k];

                    if (uiInput.IsVisible)
                    {
                        if (!uiInput.CircleCanvasPos.Equals(uiInput.CircleCanvasPosCache))
                        {
                            UpdateAnnotationOffsets(child.Children[uiInput.Identifier].Children[1], uiInput);
                            DrawLine(child.Children[uiInput.Identifier].Children[2], uiInput);
                        }
                    }

                    DrawLine(line, uiInput);

                    uiInput.CircleCanvasPosCache = uiInput.CircleCanvasPos;
                    _uiInput[k] = uiInput;
                }
            }

            _sceneRenderer.Render(RC);

            RC.Projection = _canvasRenderMode == CanvasRenderMode.Screen ? orthographic : perspective;
            _guiRenderer.Render(RC);

            Present();
        }
Exemple #32
0
 public static bool GenerateSphere(ref BrushMesh brushMesh, Vector3 diameterXYZ, float offsetY, bool generateFromCenter, float4x4 transform, int horzSegments, int vertSegments, in ChiselSurfaceDefinition surfaceDefinition)
        void OnFinishRead(AsyncGPUReadbackRequest request)
        {
            bool useConnection = false;

            commandQueue.TryDequeue(out useConnection);
            float    depth    = request.GetData <float>().Element(0);
            float4x4 invvp    = (GL.GetGPUProjectionMatrix(cam.projectionMatrix, false) * cam.worldToCameraMatrix).inverse;
            float4   worldPos = mul(invvp, float4(uv * 2 - 1, depth, 1));

            worldPos.xyz /= worldPos.w;
            MTerrain terrain = MTerrain.current;

            if (!terrain)
            {
                return;
            }
            NativeList <ulong> allMaskTree = new NativeList <ulong>(5, Allocator.Temp);

            value = Mathf.Clamp(value, 0, terrain.terrainData.allMaterials.Length - 1);
            terrain.treeRoot->GetMaterialMaskRoot(worldPos.xz, paintRange, ref allMaskTree);
            terrainEditShader.SetInt(ShaderIDs._Count, MTerrain.MASK_RESOLUTION);
            if (!useConnection)
            {
                //TODO
                terrainEditShader.SetVector("_Circle0", float4(worldPos.xz, paintRange, 1));
                terrainEditShader.SetVector("_Circle1", float4(worldPos.xz, paintRange, 1));
                terrainEditShader.SetMatrix("_QuadMatrix", float4x4(0));
            }
            else
            {
                terrain.treeRoot->GetMaterialMaskRoot(lastFrameWorldPos.xz, paintRange, ref allMaskTree);
                float2 moveDir = lastFrameWorldPos.xz - worldPos.xz;
                float  len     = length(moveDir);
                moveDir /= len;
                float    dotMove      = dot(moveDir, moveDir);
                float2   verticleDir  = float2(-moveDir.y / dotMove, moveDir.x / dotMove);
                float3x3 localToWorld = float3x3(float3(moveDir * len, 0), float3(verticleDir * paintRange * 2, 0), float3((lastFrameWorldPos.xz + worldPos.xz) * 0.5f, 1));
                float3x3 worldToLocal = inverse(localToWorld);
                terrainEditShader.SetVector("_Circle0", float4(worldPos.xz, paintRange, 1));
                terrainEditShader.SetVector("_Circle1", float4(lastFrameWorldPos.xz, paintRange, 1));
                terrainEditShader.SetMatrix("_QuadMatrix", float4x4(float4(worldToLocal.c0, 0), float4(worldToLocal.c1, 0), float4(worldToLocal.c2, 0), 0));
            }
            const int disp = MTerrain.MASK_RESOLUTION / 8;

            foreach (var i in allMaskTree)
            {
                var treeNodePtr = (TerrainQuadTree *)i;
                if (treeNodePtr == null)
                {
                    continue;
                }
                int2 maskPos  = treeNodePtr->rootPos + (int2)treeNodePtr->maskScaleOffset.yz;
                int  texIndex = terrain.maskVT.GetChunkIndex(maskPos);
                if (texIndex < 0)
                {
                    continue;
                }
                terrainEditShader.SetVector("_SrcDestCorner", (float4)treeNodePtr->BoundedWorldPos);
                terrainEditShader.SetInt(ShaderIDs._OffsetIndex, texIndex);
                PaintMask(terrain, treeNodePtr, texIndex, disp);
            }
            if (!useConnection)
            {
                terrain.treeRoot->UpdateChunks(double3(worldPos.xz, paintRange));
            }
            else
            {
                terrain.treeRoot->UpdateChunks(double3(0.5f * (worldPos.xz + lastFrameWorldPos.xz), 0.5f * distance(worldPos.xz, lastFrameWorldPos.xz) + paintRange));
            }
            lastFrameWorldPos = worldPos.xyz;
        }
        public unsafe void ReplaceIfExists(NativeListArray <float3> .NativeList uniqueVertices, float4x4 nodeToTreeSpaceMatrix)
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
            // Add Unique vertex
            for (int i = 0; i < uniqueVertices.Length; i++)
            {
                var vertex = math.mul(nodeToTreeSpaceMatrix, new float4(uniqueVertices[i], 1)).xyz;
                HashedVerticesUtility.ReplaceIfExists((ushort *)m_HashTable, m_ChainedIndices, m_Vertices, vertex);
            }
        }
Exemple #35
0
        static void Pathtracing(Texture2D texture, int pass)
        {
            // View and projection matrices
            float4x4 viewMatrix       = Transforms.LookAtLH(CameraPosition, float3(0, 1, 0), float3(0, 1, 0));
            float4x4 projectionMatrix = Transforms.PerspectiveFovLH(pi_over_4, texture.Height / (float)texture.Width, 0.01f, 20);

            Scene <PositionNormalCoordinate, Material> scene = new Scene <PositionNormalCoordinate, Material>();

            //CreateMeshScene(scene);
            CreateRaycastScene(scene);

            // Raycaster to trace rays and lit closest surfaces
            Raytracer <PTRayPayload, PositionNormalCoordinate, Material> raycaster = new Raytracer <PTRayPayload, PositionNormalCoordinate, Material>();

            raycaster.OnClosestHit += delegate(IRaycastContext context, PositionNormalCoordinate attribute, Material material, ref PTRayPayload payload)
            {
                // Move geometry attribute to world space
                attribute = attribute.Transform(context.FromGeometryToWorld);

                float3 V = -normalize(context.GlobalRay.Direction);

                attribute.Normal = normalize(attribute.Normal);

                if (material.BumpMap != null)
                {
                    float3 T, B;
                    createOrthoBasis(attribute.Normal, out T, out B);
                    float3 tangentBump = material.BumpMap.Sample(material.TextureSampler, attribute.Coordinates).xyz * 2 - 1;
                    float3 globalBump  = tangentBump.x * T + tangentBump.y * B + tangentBump.z * attribute.Normal;
                    attribute.Normal = globalBump;// normalize(attribute.Normal + globalBump * 5f);
                }

                ScatteredRay outgoing = material.Scatter(attribute, V);

                payload.Color += payload.Importance * material.Emissive;

                // Recursive calls for indirect light due to reflections and refractions
                if (payload.Bounces > 0)
                {
                    float3 D           = outgoing.Direction;                                                  // recursive direction to check
                    float3 facedNormal = dot(D, attribute.Normal) > 0 ? attribute.Normal : -attribute.Normal; // normal respect to direction

                    RayDescription ray = new RayDescription {
                        Direction = D, Origin = attribute.Position + facedNormal * 0.001f, MinT = 0.0001f, MaxT = 10000
                    };

                    payload.Importance *= outgoing.Ratio / outgoing.PDF;
                    payload.Bounces--;

                    raycaster.Trace(scene, ray, ref payload);
                }
            };
            raycaster.OnMiss += delegate(IRaycastContext context, ref PTRayPayload payload)
            {
                payload.Color = float3(0, 0, 0); // Blue, as the sky.
            };

            /// Render all points of the screen
            for (int px = 0; px < texture.Width; px++)
            {
                for (int py = 0; py < texture.Height; py++)
                {
                    int progress = (px * texture.Height + py);
                    if (progress % 10000 == 0)
                    {
                        Console.Write("\r" + progress * 100 / (float)(texture.Width * texture.Height) + "%            ");
                    }

                    RayDescription ray = RayDescription.FromScreen(px + 0.5f, py + 0.5f, texture.Width, texture.Height, inverse(viewMatrix), inverse(projectionMatrix), 0, 1000);

                    float4       accum    = texture.Read(px, py) * pass;
                    PTRayPayload coloring = new PTRayPayload();
                    coloring.Importance = float3(1, 1, 1);
                    coloring.Bounces    = 3;

                    raycaster.Trace(scene, ray, ref coloring);

                    texture.Write(px, py, float4((accum.xyz + coloring.Color) / (pass + 1), 1));
                }
            }
        }
Exemple #36
0
 unsafe static ChiselBlobAssetReference <BrushTreeSpaceVerticesBlob> Build(ref ChiselBlobArray <float3> localVertices, float4x4 nodeToTreeSpaceMatrix)
 {
     var     totalSize         = localVertices.Length * sizeof(float3);
     var     builder           = new ChiselBlobBuilder(Allocator.Temp, math.max(4, totalSize));
     ref var root              = ref builder.ConstructRoot <BrushTreeSpaceVerticesBlob>();
 /// <summary>
 /// Calculates the principal transformation axis.
 /// </summary>
 /// <param name="masses">The masses.</param>
 /// <param name="principal">The principal axis.</param>
 /// <param name="inertia">The inertia.</param>
 public void CalculatePrincipalAxisTransform(float[] masses, float4x4 principal, float3 inertia)
 {
     _compoundShapeImp.CalculatePrincipalAxisTransform(masses, principal, inertia);
 }
 /// <summary>
 /// Adds a capsule as a child shape.
 /// </summary>
 /// <param name="localTransform">The local transformation of the child shape.</param>
 /// <param name="childShape">The child shape.</param>
 public void AddChildShape(float4x4 localTransform, CapsuleShape childShape)
 {
     _compoundShapeImp.AddChildShape(localTransform, childShape._capsuleShapeImp);
 }
Exemple #39
0
 public static float4x4 Mul
     (float4x4 m1, float4x4 m2, float4x4 m3)
 => math.mul(math.mul(m1, m2), m3);
        public ISliderConstraintImp AddSliderConstraint(IRigidBodyImp rigidBodyA, float4x4 frameInA, bool useLinearReferenceFrameA)
        {
            var rigidBodyAImp = (RigidBodyImp)rigidBodyA;
            var btRigidBodyA = rigidBodyAImp._rbi;
            var btFrameInA = Translater.Float4X4ToBtMatrix(frameInA);
            var btSliderConstraint = new SliderConstraint(btRigidBodyA, btFrameInA, useLinearReferenceFrameA);
            BtWorld.AddConstraint(btSliderConstraint);

            var retval = new SliderConstraintImp();
            retval._sci = btSliderConstraint;
            btSliderConstraint.UserObject = retval;
            return retval;
        }
Exemple #41
0
 public static float4x4 Mul
     (float4x4 m1, float4x4 m2, float4x4 m3, float4x4 m4, float4x4 m5)
 => math.mul(math.mul(math.mul(math.mul(m1, m2), m3), m4), m5);
 public void SetFrames(float4x4 frameA, float4x4 frameB)
 {
     var o = (SliderConstraint)_iSliderConstraintImp.UserObject;
     o._iSliderConstraintImp.SetFrames(frameA, frameB);
 }
        protected override void OnUpdate()
        {
            var bgfxinst = World.GetExistingSystem <RendererBGFXSystem>().InstancePointer();

            if (!bgfxinst->m_initialized)
            {
                return;
            }

            // setup bgfx side
            Entities.WithoutBurst().ForEach((Entity e, ref RenderPass pass) =>
            {
                if (pass.viewId == 0xffff)
                {
                    RenderDebug.LogFormat("Render pass entity {0} on render node entity {1} is not referenced by the render graph. It should be deleted.", e, pass.inNode);
                    Assert.IsTrue(false);
                    return;
                }
                bool rtt = EntityManager.HasComponent <FramebufferBGFX>(pass.inNode);
                if (rtt)
                {
                    pass.passFlags = RenderPassFlags.RenderToTexture;
                }
                else
                {
                    pass.passFlags = 0;
                }
                // those could be more shared ... (that is, do all passes really need a copy of view & projection?)
                unsafe { fixed(float4x4 * viewp = &pass.viewTransform, projp = &pass.projectionTransform)
                         {
                             if (bgfxinst->m_homogeneousDepth && bgfxinst->m_originBottomLeft) // gl style
                             {
                                 bgfx.set_view_transform(pass.viewId, viewp, projp);
                                 pass.passFlags &= ~RenderPassFlags.FlipCulling;
                             }
                             else // dx style
                             {
                                 bool yflip = !bgfxinst->m_originBottomLeft && rtt;
                                 float4x4 adjustedProjection = RendererBGFXStatic.AdjustProjection(ref pass.projectionTransform, !bgfxinst->m_homogeneousDepth, yflip);
                                 bgfx.set_view_transform(pass.viewId, viewp, &adjustedProjection);
                                 if (yflip)
                                 {
                                     pass.passFlags |= RenderPassFlags.FlipCulling;
                                 }
                                 else
                                 {
                                     pass.passFlags &= ~RenderPassFlags.FlipCulling;
                                 }
                             }
                             // make a viewProjection
                             pass.viewProjectionTransform = math.mul(pass.projectionTransform, pass.viewTransform);
                         } }
                bgfx.set_view_mode(pass.viewId, (bgfx.ViewMode)pass.sorting);
                if (bgfxinst->m_originBottomLeft)
                {
                    bgfx.set_view_rect(pass.viewId, pass.viewport.x, (ushort)(pass.targetRect.h - pass.viewport.y - pass.viewport.h), pass.viewport.w, pass.viewport.h);
                    if (pass.scissor.h == 0)
                    {
                        bgfx.set_view_scissor(pass.viewId, 0, 0, 0, 0);
                    }
                    else
                    {
                        bgfx.set_view_scissor(pass.viewId, pass.scissor.x, (ushort)(pass.targetRect.h - pass.scissor.y - pass.scissor.h), pass.scissor.w, pass.scissor.h);
                    }
                }
                else
                {
                    if (rtt)
                    {
                        bgfx.set_view_rect(pass.viewId, pass.viewport.x, pass.viewport.y, pass.viewport.w, pass.viewport.h);
                        bgfx.set_view_scissor(pass.viewId, pass.scissor.x, pass.scissor.y, pass.scissor.w, pass.scissor.h);
                    }
                    else
                    {
                        bgfx.set_view_rect(pass.viewId, pass.viewport.x, (ushort)(pass.targetRect.h - pass.viewport.y - pass.viewport.h), pass.viewport.w, pass.viewport.h);
                        if (pass.scissor.h == 0)
                        {
                            bgfx.set_view_scissor(pass.viewId, 0, 0, 0, 0);
                        }
                        else
                        {
                            bgfx.set_view_scissor(pass.viewId, pass.scissor.x, (ushort)(pass.targetRect.h - pass.scissor.y - pass.scissor.h), pass.scissor.w, pass.scissor.h);
                        }
                    }
                }
                bgfx.set_view_clear(pass.viewId, (ushort)pass.clearFlags, pass.clearRGBA, pass.clearDepth, pass.clearStencil);
                if (rtt)
                {
                    var rttbgfx = EntityManager.GetComponentData <FramebufferBGFX>(pass.inNode);
                    bgfx.set_view_frame_buffer(pass.viewId, rttbgfx.handle);
                }
                else
                {
                    bgfx.set_view_frame_buffer(pass.viewId, new bgfx.FrameBufferHandle {
                        idx = 0xffff
                    });
                }
                // touch it? needed?
                bgfx.touch(pass.viewId);
            }).Run();
        }
Exemple #44
0
        public void Render(float4x4 camMatrix)
        {
            _rc.ModelView = CorrectionMatrix * Position * camMatrix;

            _shaderEffect.RenderMesh(_mesh);
        }
 /// <summary>
 /// Adds an empty shape as a child shape.
 /// </summary>
 /// <param name="localTransform">The local transformation of the child shape.</param>
 /// <param name="childShape">The child shape.</param>
 public void AddChildShape(float4x4 localTransform, EmptyShape childShape)
 {
     _compoundShapeImp.AddChildShape(localTransform, childShape._emtyShapeImp);
 }
        //Liest Eingabe des Spielers
        public void PlayerInput()
        {
            _angleVelHorz = RotationSpeed * Input.Instance.GetAxis(InputAxis.MouseX);
            _angleVelVert = RotationSpeed * Input.Instance.GetAxis(InputAxis.MouseY);

            _angleHorz -= _angleVelHorz;
            _angleVert -= _angleVelVert;

            //Bewegungsferiheit einschränken um Orientierungslosigkeit des Spielers zu verhindern
            if (_angleVert >= 0.9f)
            {
                _angleVert = 0.9f;
            }
            if (_angleVert <= -0.8f)
            {
                _angleVert = -0.8f;
            }

            _rotY = float4x4.CreateRotationY(_angleHorz);
            _rotX = float4x4.CreateRotationX(_angleVert);
            var mtxRot = float4x4.CreateRotationX(_angleVert) * float4x4.CreateRotationY(_angleHorz);

            _mtxCam = mtxRot * float4x4.LookAt(0, 40, -1, 0, 40, 1, 0, 1, 0);
            _mtxCam *= float4x4.CreateTranslation(0, 40, -1);

            //Schiessen
            Weapon.WeaponInput(_mtxCam);
        }
        public IConeTwistConstraintImp AddConeTwistConstraint(IRigidBodyImp rigidBodyA, IRigidBodyImp rigidBodyB, float4x4 rbAFrame,float4x4 rbBFrame)
        {
            var rigidBodyAImp = (RigidBodyImp)rigidBodyA;
            var btRigidBodyA = rigidBodyAImp._rbi;

            var rigidBodyBImp = (RigidBodyImp)rigidBodyB;
            var btRigidBodyB = rigidBodyBImp._rbi;

            var btRbAFrame = Translater.Float4X4ToBtMatrix(rbAFrame);
            var btRbBFrame = Translater.Float4X4ToBtMatrix(rbBFrame);

            var btCTConstraint = new ConeTwistConstraint(btRigidBodyA, btRigidBodyB, btRbAFrame, btRbBFrame);

            BtWorld.AddConstraint(btCTConstraint);

            var retval = new ConeTwistConstraintImp();
            retval._cti = btCTConstraint;
            btCTConstraint.UserObject = retval;
            return retval;
        }
 /// <summary>
 /// Adds a multi-sphere as a child shape.
 /// </summary>
 /// <param name="localTransform">The local transformation of the child shape.</param>
 /// <param name="childShape">The child shape.</param>
 public void AddChildShape(float4x4 localTransform, MultiSphereShape childShape)
 {
     _compoundShapeImp.AddChildShape(localTransform, childShape._multiSphereShapeImp);
 }
        public IHingeConstraintImp AddHingeConstraint(IRigidBodyImp rigidBodyA, IRigidBodyImp rigidBodyB, float4x4 brAFrame, float4x4 brBFrame, bool useReferenceFrameA)
        {
            var rigidBodyAImp = (RigidBodyImp)rigidBodyA;
            var btRigidBodyA = rigidBodyAImp._rbi;

            var rigidBodyBImp = (RigidBodyImp)rigidBodyB;
            var btRigidBodyB = rigidBodyBImp._rbi;

            var btRbAFrame = Translater.Float4X4ToBtMatrix(brAFrame);
            var btRbBFrame = Translater.Float4X4ToBtMatrix(brBFrame);

            var btHingeConstraint = new HingeConstraint(btRigidBodyA, btRigidBodyB,btRbAFrame, btRbBFrame, useReferenceFrameA);
            BtWorld.AddConstraint(btHingeConstraint);

            var retval = new HingeConstraintImp();
            retval._hci = btHingeConstraint;
            btHingeConstraint.UserObject = retval;
            return retval;
        }
Exemple #50
0
 public void SetCorrectionMatrix(float4x4 corrMatrix)
 {
     CorrectionMatrix = corrMatrix;
 }
 public void CalculateTransforms(float4x4 transA, float4x4 transB)
 {
     _iSliderConstraintImp.CalculateTransforms(transA, transB);
 }
Exemple #52
0
 public static ChiselAABB Create(float4x4 transformation, float3[] vertices)
 {
     if (vertices == null ||
         vertices.Length == 0)
     {
         return(default);
        public void TRS_LocalPositionsHierarchy()
        {
            var pi        = 3.14159265359f;
            var rotations = new quaternion[]
            {
                quaternion.EulerYZX(new float3(0.125f * pi, 0.0f, 0.0f)),
                quaternion.EulerYZX(new float3(0.5f * pi, 0.0f, 0.0f)),
                quaternion.EulerYZX(new float3(pi, 0.0f, 0.0f)),
            };
            var translations = new float3[]
            {
                new float3(0.0f, 0.0f, 1.0f),
                new float3(0.0f, 1.0f, 0.0f),
                new float3(1.0f, 0.0f, 0.0f),
                new float3(0.5f, 0.5f, 0.5f),
            };

            //  0: R:[0] T:[0]
            //  1:  - R:[1] T:[1]
            //  2:    - R:[2] T:[0]
            //  3:    - R:[2] T:[1]
            //  4:    - R:[2] T:[2]
            //  5:      - R:[1] T:[0]
            //  6:      - R:[1] T:[1]
            //  7:      - R:[1] T:[2]
            //  8:  - R:[2] T:[2]
            //  9:    - R:[1] T:[0]
            // 10:    - R:[1] T:[1]
            // 11:    - R:[1] T:[2]
            // 12:      - R:[0] T:[0]
            // 13:        - R:[0] T:[1]
            // 14:          - R:[0] T:[2]
            // 15:            - R:[0] T:[2]

            var rotationIndices    = new int[] { 0, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 1, 0, 0, 0, 0 };
            var translationIndices = new int[] { 0, 1, 0, 1, 2, 0, 1, 2, 2, 0, 1, 2, 0, 1, 2, 2 };
            var parentIndices      = new int[] { -1, 0, 1, 1, 1, 4, 4, 4, 0, 8, 8, 8, 11, 12, 13, 14 };

            var expectedLocalToParent = new float4x4[16];

            for (int i = 0; i < 16; i++)
            {
                var rotationIndex    = rotationIndices[i];
                var translationIndex = translationIndices[i];
                var localToParent    = new float4x4(rotations[rotationIndex], translations[translationIndex]);
                expectedLocalToParent[i] = localToParent;
            }

            var expectedLocalToWorld = new float4x4[16];

            expectedLocalToWorld[0] = expectedLocalToParent[0];
            for (int i = 1; i < 16; i++)
            {
                var parentIndex = parentIndices[i];
                expectedLocalToWorld[i] = math.mul(expectedLocalToWorld[parentIndex], expectedLocalToParent[i]);
            }

            var bodyArchetype   = m_Manager.CreateArchetype(typeof(Position), typeof(Rotation));
            var attachArchetype = m_Manager.CreateArchetype(typeof(Attach));
            var bodyEntities    = new NativeArray <Entity>(16, Allocator.TempJob);
            var attachEntities  = new NativeArray <Entity>(15, Allocator.TempJob);

            m_Manager.CreateEntity(bodyArchetype, bodyEntities);
            m_Manager.CreateEntity(attachArchetype, attachEntities);

            for (int i = 0; i < 16; i++)
            {
                var rotationIndex    = rotationIndices[i];
                var translationIndex = translationIndices[i];
                var rotation         = new Rotation {
                    Value = rotations[rotationIndex]
                };
                var position = new Position {
                    Value = translations[translationIndex]
                };

                m_Manager.SetComponentData(bodyEntities[i], rotation);
                m_Manager.SetComponentData(bodyEntities[i], position);
            }

            for (int i = 1; i < 16; i++)
            {
                var parentIndex = parentIndices[i];
                m_Manager.SetComponentData(attachEntities[i - 1],
                                           new Attach {
                    Parent = bodyEntities[parentIndex], Child = bodyEntities[i]
                });
            }

            World.GetOrCreateManager <EndFrameTransformSystem>().Update();

            // Check all non-root LocalToParent
            for (int i = 1; i < 16; i++)
            {
                var entity        = bodyEntities[i];
                var localToParent = m_Manager.GetComponentData <LocalToParent>(entity).Value;

                AssertCloseEnough(expectedLocalToParent[i], localToParent);
            }

            // Check all LocalToWorld
            for (int i = 0; i < 16; i++)
            {
                var entity       = bodyEntities[i];
                var localToWorld = m_Manager.GetComponentData <LocalToWorld>(entity).Value;

                AssertCloseEnough(expectedLocalToWorld[i], localToWorld);
            }

            bodyEntities.Dispose();
            attachEntities.Dispose();
        }
Exemple #54
0
 public LastVPData(Camera c)
 {
     lastP           = GraphicsUtility.GetGPUProjectionMatrix(c.projectionMatrix, false);
     camlocalToWorld = c.transform.localToWorldMatrix;
     lastVP          = mul(lastP, c.worldToCameraMatrix);
 }
        // TODO add vector implementations
        /// <summary>
        /// Sets a <see cref="float4x4" /> shader parameter.
        /// </summary>
        /// <param name="param">The parameter.</param>
        /// <param name="val">The value.</param>
        public void SetShaderParam(IShaderParam param, float4x4 val)
        {
            unsafe
            {
                var mF = (float*)(&val);
                // Row order notation
                // GL.UniformMatrix4(((ShaderParam) param).handle, 1, false, mF);

                // Column order notation
                GL.UniformMatrix4(((ShaderParam)param).handle, 1, true, mF);
            }
        }
Exemple #56
0
        static void Raytracing(Texture2D texture)
        {
            // View and projection matrices
            float4x4 viewMatrix       = Transforms.LookAtLH(CameraPosition, float3(0, 1, 0), float3(0, 1, 0));
            float4x4 projectionMatrix = Transforms.PerspectiveFovLH(pi_over_4, texture.Height / (float)texture.Width, 0.01f, 20);

            Scene <PositionNormalCoordinate, Material> scene = new Scene <PositionNormalCoordinate, Material>();

            //CreateMeshScene(scene);
            CreateRaycastScene(scene);

            // Raycaster to trace rays and check for shadow rays.
            Raytracer <ShadowRayPayload, PositionNormalCoordinate, Material> shadower = new Raytracer <ShadowRayPayload, PositionNormalCoordinate, Material>();

            shadower.OnAnyHit += delegate(IRaycastContext context, PositionNormalCoordinate attribute, Material material, ref ShadowRayPayload payload)
            {
                if (any(material.Emissive))
                {
                    return(HitResult.Discard); // Discard light sources during shadow test.
                }
                // If any object is found in ray-path to the light, the ray is shadowed.
                payload.Shadowed = true;
                // No neccessary to continue checking other objects
                return(HitResult.Stop);
            };

            // Raycaster to trace rays and lit closest surfaces
            Raytracer <RTRayPayload, PositionNormalCoordinate, Material> raycaster = new Raytracer <RTRayPayload, PositionNormalCoordinate, Material>();

            raycaster.OnClosestHit += delegate(IRaycastContext context, PositionNormalCoordinate attribute, Material material, ref RTRayPayload payload)
            {
                // Move geometry attribute to world space
                attribute = attribute.Transform(context.FromGeometryToWorld);

                float3 V = -normalize(context.GlobalRay.Direction);

                float3 L = (LightPosition - attribute.Position);
                float  d = length(L);
                L /= d; // normalize direction to light reusing distance to light

                attribute.Normal = normalize(attribute.Normal);

                if (material.BumpMap != null)
                {
                    float3 T, B;
                    createOrthoBasis(attribute.Normal, out T, out B);
                    float3 tangentBump = material.BumpMap.Sample(material.TextureSampler, attribute.Coordinates).xyz * 2 - 1;
                    float3 globalBump  = tangentBump.x * T + tangentBump.y * B + tangentBump.z * attribute.Normal;
                    attribute.Normal = globalBump;// normalize(attribute.Normal + globalBump * 5f);
                }

                float lambertFactor = max(0, dot(attribute.Normal, L));

                // Check ray to light...
                ShadowRayPayload shadow = new ShadowRayPayload();
                shadower.Trace(scene,
                               RayDescription.FromDir(attribute.Position + attribute.Normal * 0.001f, // Move an epsilon away from the surface to avoid self-shadowing
                                                      L), ref shadow);

                float3 Intensity = (shadow.Shadowed ? 0.2f : 1.0f) * LightIntensity / (d * d);

                payload.Color = material.Emissive + material.EvalBRDF(attribute, V, L) * Intensity * lambertFactor; // direct light computation

                // Recursive calls for indirect light due to reflections and refractions
                if (payload.Bounces > 0)
                {
                    foreach (var impulse in material.GetBRDFImpulses(attribute, V))
                    {
                        float3 D = impulse.Direction;                                                             // recursive direction to check

                        float3 facedNormal = dot(D, attribute.Normal) > 0 ? attribute.Normal : -attribute.Normal; // normal respect to direction

                        RayDescription ray = new RayDescription {
                            Direction = D, Origin = attribute.Position + facedNormal * 0.001f, MinT = 0.0001f, MaxT = 10000
                        };

                        RTRayPayload newPayload = new RTRayPayload
                        {
                            Bounces = payload.Bounces - 1
                        };

                        raycaster.Trace(scene, ray, ref newPayload);

                        payload.Color += newPayload.Color * impulse.Ratio;
                    }
                }
            };
            raycaster.OnMiss += delegate(IRaycastContext context, ref RTRayPayload payload)
            {
                payload.Color = float3(0, 0, 0); // Blue, as the sky.
            };

            /// Render all points of the screen
            for (int px = 0; px < texture.Width; px++)
            {
                for (int py = 0; py < texture.Height; py++)
                {
                    int progress = (px * texture.Height + py);
                    if (progress % 1000 == 0)
                    {
                        Console.Write("\r" + progress * 100 / (float)(texture.Width * texture.Height) + "%            ");
                    }

                    RayDescription ray = RayDescription.FromScreen(px + 0.5f, py + 0.5f, texture.Width, texture.Height, inverse(viewMatrix), inverse(projectionMatrix), 0, 1000);

                    RTRayPayload coloring = new RTRayPayload();
                    coloring.Bounces = 3;

                    raycaster.Trace(scene, ray, ref coloring);

                    texture.Write(px, py, float4(coloring.Color, 1));
                }
            }
        }
Exemple #57
0
        // HERE is where we get our information from the curve!
        public void GetCubicInformation(float val, out float3 position, out float3 direction, out float3 tangent, out float width)
        {
            float3 p0 = 0;
            float3 v0 = 0;
            float3 p1 = 0;
            float3 v1 = 0;

            float3 p2 = float3(0.0f, 0.0f, 0.0f);

            float vPP = positions.Count;


            // Figuring out how much we should go around.
            // to the end point? or loop back aroudn to first point?
            float c       = closed ?  0:1;
            float baseVal = val * (vPP - c);

            // Get our base and ceiling
            int baseUp   = (int)(floor(baseVal)) % positions.Count;
            int baseDown = (int)(ceil(baseVal)) % positions.Count;

            // make sure we are within our positions
            baseVal %= positions.Count;

            // TOD MAKE UNIFORM
            float3 up = float3(0, 1, 0);


            // IF out down and up are the same it means we are right at the
            // point of the matrices so we can pass the info stright through
            if (baseUp == baseDown || (baseVal % 1) == 0)
            {
                float4x4 pointMatrix = pointMatrices[(int)baseVal];

                float3 pointPower = powers[(int)baseVal];
                position  = mul(pointMatrix, float4(0, 0, 0, 1)).xyz;
                direction = normalize(mul(pointMatrix, float4(0, 0, 1, 0)).xyz);


                tangent = normalize(mul(pointMatrix, float4(0, 1, 0, 0)).xyz);
                tangent = normalize(cross(direction, tangent));

                width = pointPower.z;//lerp( pointPower.z , pointDownPower.z , amount );


                // IF arent *right* at the point, it means we need to do our actual cubic
            }
            else
            {
                float amount = baseVal - (float)baseUp;

                float4x4 pointMatrixUp   = pointMatrices[baseUp];
                float4x4 pointMatrixDown = pointMatrices[baseDown];

                float3 pointUpPower   = powers[baseUp];
                float3 pointDownPower = powers[baseDown];

                // positions
                p0 = mul(pointMatrixUp, float4(0, 0, 0, 1)).xyz;
                p1 = mul(pointMatrixDown, float4(0, 0, 0, 1)).xyz;

                // velocities
                v0 = pointUpPower.x * normalize(mul(pointMatrixUp, float4(0, 0, 1, 0)).xyz);
                v1 = pointDownPower.y * normalize(mul(pointMatrixDown, float4(0, 0, 1, 0)).xyz);



                // Setting up our points for the curve
                float3 c0     = p0;
                float3 c1     = p0 + v0;
                float3 c2     = p1 - v1;
                float3 c3     = p1;
                float  smooth = amount * amount * (3 - 2 * amount);

                // doing our actual curvvving!
                float3 pos   = cubicCurve(amount, c0, c1, c2, c3);
                float3 upPos = cubicCurve(amount + .001f, c0, c1, c2, c3);

                position  = pos;
                direction = normalize((upPos - pos) * 1000);


                tangent = lerp(normalize(mul(pointMatrixUp, float4(0, 1, 0, 0)).xyz), normalize(mul(pointMatrixDown, float4(0, 1, 0, 0)).xyz), smooth);
                tangent = normalize(cross(direction, tangent));

                width = lerp(pointUpPower.z, pointDownPower.z, smooth);
            }
        }
 /// <summary>
 /// Adds a cylinder as a child shape.
 /// </summary>
 /// <param name="localTransform">The local transformation of the child shape.</param>
 /// <param name="childShape">The child shape.</param>
 public void AddChildShape(float4x4 localTransform, CylinderShape childShape)
 {
     _compoundShapeImp.AddChildShape(localTransform, childShape._cylinderShapeImp);
 }
 public void CalcAngleInfo2(float4x4 transA, float4x4 transB, float4x4 invInertiaWorldA, float4x4 invInertiaWorldB)
 {
     _iCTConstraintImp.CalcAngleInfo2(transA, transB, invInertiaWorldA, invInertiaWorldB);
 }
        //[MethodImpl(MethodImplOptions.NoInlining)]
        void FindIntersectionVertices(ref BlobArray <float4> intersectingPlanes0,
                                      ref BlobArray <float4> intersectingPlanes1,
                                      ref BlobArray <PlanePair> usedPlanePairs1,
                                      ref BlobArray <int> intersectingPlaneIndices0,
                                      float4x4 nodeToTreeSpaceMatrix0,
                                      //ref HashedVertices              hashedVertices,
                                      NativeArray <PlaneVertexIndexPair> foundIndices0,
                                      ref int foundIndices0Length,
                                      NativeArray <PlaneVertexIndexPair> foundIndices1,
                                      ref int foundIndices1Length)
        {
            var foundVertices      = new NativeArray <float4>(usedPlanePairs1.Length * intersectingPlanes0.Length, Allocator.Temp);
            var foundEdges         = new NativeArray <IntersectionEdge>(usedPlanePairs1.Length * intersectingPlanes0.Length, Allocator.Temp);
            var foundIntersections = new NativeArray <IntersectionPlanes>(usedPlanePairs1.Length * intersectingPlanes0.Length, Allocator.Temp);
            var n = 0;

            for (int i = 0; i < usedPlanePairs1.Length; i++)
            {
                for (int j = 0; j < intersectingPlanes0.Length; j++)
                {
                    foundIntersections[n] = new IntersectionPlanes
                    {
                        plane0      = usedPlanePairs1[i].plane0,
                        plane1      = usedPlanePairs1[i].plane1,
                        plane2      = intersectingPlanes0[j],
                        planeIndex0 = usedPlanePairs1[i].planeIndex0,
                        planeIndex1 = usedPlanePairs1[i].planeIndex1,
                        planeIndex2 = intersectingPlaneIndices0[j]
                    };

                    foundEdges[n] = new IntersectionEdge
                    {
                        edgeVertex0 = usedPlanePairs1[i].edgeVertex0,
                        edgeVertex1 = usedPlanePairs1[i].edgeVertex1
                    };

                    var plane0 = usedPlanePairs1[i].plane0;
                    var plane1 = usedPlanePairs1[i].plane1;
                    var plane2 = intersectingPlanes0[j];

                    foundVertices[n] = new float4(PlaneExtensions.Intersection(plane2, plane0, plane1), 1);
                    n++;
                }
            }

            for (int k = n - 1; k >= 0; k--)
            {
                var edgeVertex0 = foundEdges[k].edgeVertex0;
                var edgeVertex1 = foundEdges[k].edgeVertex1;
                var plane2      = foundIntersections[k].plane2;

                if (math.abs(math.dot(plane2, edgeVertex0)) <= kDistanceEpsilon &&
                    math.abs(math.dot(plane2, edgeVertex1)) <= kDistanceEpsilon)
                {
                    if (k < n - 1)
                    {
                        foundIntersections[k] = foundIntersections[n - 1];
                        foundVertices[k]      = foundVertices[n - 1];
                    }
                    n--;
                }
            }

            // TODO: since we're using a pair in the outer loop, we could also determine which
            //       2 planes it intersects at both ends and just check those two planes ..

            // NOTE: for brush2, the intersection will always be only on two planes
            //       UNLESS it's a corner vertex along that edge (we can compare to the two vertices)
            //       in which case we could use a pre-calculated list of planes ..
            //       OR when the intersection is outside of the edge ..

            for (int k = n - 1; k >= 0; k--)
            {
                if (IsOutsidePlanes(ref intersectingPlanes0, foundVertices[k]) ||
                    IsOutsidePlanes(ref intersectingPlanes1, foundVertices[k]))
                {
                    if (k < n - 1)
                    {
                        foundIntersections[k] = foundIntersections[n - 1];
                        foundVertices[k]      = foundVertices[n - 1];
                    }
                    n--;
                }
            }

            for (int k = 0; k < n; k++)
            {
                var planeIndex0 = (ushort)foundIntersections[k].planeIndex0;
                var planeIndex1 = (ushort)foundIntersections[k].planeIndex1;
                var planeIndex2 = (ushort)foundIntersections[k].planeIndex2;

                var localVertex = foundVertices[k];

                // TODO: should be having a Loop for each plane that intersects this vertex, and add that vertex
                //       to ensure they are identical
                var treeSpaceVertex = math.mul(nodeToTreeSpaceMatrix0, localVertex).xyz;
                var vertexIndex     = hashedVertices.AddNoResize(treeSpaceVertex);

                foundIndices0[foundIndices0Length] = new PlaneVertexIndexPair {
                    planeIndex = planeIndex2, vertexIndex = vertexIndex
                };
                foundIndices0Length++;

                foundIndices1[foundIndices1Length] = new PlaneVertexIndexPair {
                    planeIndex = planeIndex0, vertexIndex = vertexIndex
                };
                foundIndices1Length++;

                foundIndices1[foundIndices1Length] = new PlaneVertexIndexPair {
                    planeIndex = planeIndex1, vertexIndex = vertexIndex
                };
                foundIndices1Length++;
            }
        }