예제 #1
0
 public JointTarget(string name, TransformComponent transComponent, Transform targetTransform)
     : base(name, targetTransform)
 {
     Subcomponent = transComponent;
     TargetJoint = targetTransform;
     AnimationType = typeof(Transform);
 }
예제 #2
0
 public JointTarget(string name, TransformComponent transComponent, Transform targetTransform, float flip_)
     : base(name, targetTransform)
 {
     Subcomponent = transComponent;
     TargetJoint = targetTransform;
     AnimationType = typeof(Transform);
     flipModifier = flip_;
 }
예제 #3
0
 protected void parseModel()
 {
     components = model.Children.First().Components;
     foreach (var component in components)
     {
         if (component.GetType() == typeof(MaterialComponent)) { materialComponent = (MaterialComponent)component; }
         if (component.GetType() == typeof(TransformComponent)) { transformComponent = (TransformComponent)component; }
         if (component.GetType() == typeof(MeshComponent)) { meshComponent = (MeshComponent)component; }
     }
 }
예제 #4
0
        protected override async Task LoadContent()
        {
            await base.LoadContent();
            
            // sets the virtual resolution
            areaSize = new Vector2(GraphicsDevice.BackBuffer.Width, GraphicsDevice.BackBuffer.Height);

            // Creates the camera
            CameraComponent.UseCustomProjectionMatrix = true;
            CameraComponent.ProjectionMatrix = SpriteBatch.CalculateDefaultProjection(new Vector3(areaSize, 200));

            // Load assets
            groundSprites = Asset.Load<SpriteGroup>("GroundSprite");
            ballSprite1 = Asset.Load<Texture>("Sphere1");
            ballSprite2 = Asset.Load<Texture>("Sphere2");
            ball = Asset.Load<Entity>("Ball");

            // create fore/background entities
            foreground = new Entity();
            background = new Entity();
            foreground.Add(new SpriteComponent { SpriteProvider = new SpriteFromSpriteGroup { SpriteGroup = groundSprites }, CurrentFrame = 1 });
            background.Add(new SpriteComponent { SpriteProvider = new SpriteFromSpriteGroup { SpriteGroup = groundSprites }, CurrentFrame = 0 });

            Scene.AddChild(ball);
            Scene.AddChild(foreground);
            Scene.AddChild(background);

            spriteComponent = ball.Get(SpriteComponent.Key);
            transfoComponent = ball.Get(TransformComponent.Key);

            transfoComponent.Position.X = areaSize.X / 2;
            transfoComponent.Position.Y = areaSize.Y / 2;

            var decorationScalings = new Vector3(areaSize.X, areaSize.Y, 1);
            background.Get(TransformComponent.Key).Scale = decorationScalings;
            foreground.Get(TransformComponent.Key).Scale = decorationScalings;
            background.Get(TransformComponent.Key).Position = new Vector3(0, 0, -1);
            foreground.Get(TransformComponent.Key).Position = new Vector3(0, areaSize.Y, 1);

            SpriteAnimation.Play(spriteComponent, 0, spriteComponent.SpriteProvider.SpritesCount-1, AnimationRepeatMode.LoopInfinite, 30);
        }
예제 #5
0
        protected override async Task LoadContent()
        {
            await base.LoadContent();
            
            // sets the virtual resolution
            areaSize = new Vector2(GraphicsDevice.BackBuffer.Width, GraphicsDevice.BackBuffer.Height);

            // Creates the camera
            CameraComponent.UseCustomProjectionMatrix = true;
            CameraComponent.ProjectionMatrix = Matrix.OrthoRH(areaSize.X, areaSize.Y, -2, 2);

            // Load assets
            groundSprites = Asset.Load<SpriteSheet>("GroundSprite");
            ballSprite1 = Asset.Load<SpriteSheet>("BallSprite1");
            ballSprite2 = Asset.Load<SpriteSheet>("BallSprite2");
            ball = new Entity { new SpriteComponent { SpriteProvider = new SpriteFromSheet { Sheet = Asset.Load<SpriteSheet>("BallSprite1") } } };

            // create fore/background entities
            foreground = new Entity();
            background = new Entity();
            foreground.Add(new SpriteComponent { SpriteProvider = new SpriteFromSheet { Sheet = groundSprites }, CurrentFrame = 1 });
            background.Add(new SpriteComponent { SpriteProvider = new SpriteFromSheet { Sheet = groundSprites }, CurrentFrame = 0 });

            Scene.Entities.Add(ball);
            Scene.Entities.Add(foreground);
            Scene.Entities.Add(background);

            spriteComponent = ball.Get<SpriteComponent>();
            transfoComponent = ball.Get<TransformComponent>();
            
            var decorationScalings = new Vector3(areaSize.X, areaSize.Y, 1);
            background.Get<TransformComponent>().Scale = decorationScalings;
            foreground.Get<TransformComponent>().Scale = decorationScalings/2;
            background.Get<TransformComponent>().Position = new Vector3(0, 0, -1);
            foreground.Get<TransformComponent>().Position = new Vector3(0, 0, 1);

            SpriteAnimation.Play(spriteComponent, 0, spriteComponent.SpriteProvider.SpritesCount-1, AnimationRepeatMode.LoopInfinite, 30);
        }
예제 #6
0
 /// <summary>
 /// Performs a direction transformation using the given <see cref="TransformComponent.WorldMatrix"/>.
 /// </summary>
 /// <param name="transform">The transform to get the world matrix from.</param>
 /// <param name="direction">The direction vector to transform.</param>
 /// <returns>The transformed direction.</returns>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> is <see langword="null"/>.</exception>
 /// <remarks>
 /// This method does not update the <see cref="TransformComponent.WorldMatrix"/> before performing the transformation.
 /// If the <see cref="TransformComponent"/> has been modified since the last frame you may need to call the <see cref="TransformComponent.UpdateWorldMatrix"/> method first.
 /// </remarks>
 public static Vector3 TransformDirection(this TransformComponent transform, Vector3 direction)
 {
     transform.TransformDirection(ref direction, out var result);
     return(result);
 }
예제 #7
0
            public void Update(RenderUIElement renderObject, float vFoV, ref Matrix viewMatrix, ref Matrix projMatrix)
            {
                var worldMatrix = renderObject.WorldMatrix;

                // rotate the UI element perpendicular to the camera view vector, if billboard is activated
                if (renderObject.IsFullScreen)
                {
                    Matrix.Scaling(ref renderObject.Component.Entity.Transform.Scale, out Matrix scalar);
                    worldMatrix = ReallyCloseUI * scalar;
                }
                else
                {
                    if (renderObject.IsBillboard || renderObject.IsFullScreen)
                    {
                        Matrix viewInverse;
                        Matrix.Invert(ref viewMatrix, out viewInverse);
                        var diff = worldMatrix.TranslationVector - viewInverse.TranslationVector;

                        if (renderObject.IsBillboard)
                        {
                            switch (renderObject.Component.BillboardType)
                            {
                            case UIComponent.BILLBOARD_TYPE.VIEW:
                                var viewInverseRow1 = viewInverse.Row1;
                                var viewInverseRow2 = viewInverse.Row2;

                                // remove scale of the camera
                                viewInverseRow1 /= viewInverseRow1.XYZ().Length();
                                viewInverseRow2 /= viewInverseRow2.XYZ().Length();

                                // set the scale of the object
                                viewInverseRow1 *= worldMatrix.Row1.XYZ().Length();
                                viewInverseRow2 *= worldMatrix.Row2.XYZ().Length();

                                // set the adjusted world matrix
                                worldMatrix.Row1 = viewInverseRow1;
                                worldMatrix.Row2 = viewInverseRow2;
                                worldMatrix.Row3 = viewInverse.Row3;
                                break;

                            case UIComponent.BILLBOARD_TYPE.POSITION:
                                // generate a new matrix that looks at the camera's position
                                Quaternion look = new Quaternion();
                                Quaternion.LookAt(ref look, diff);
                                TransformComponent original = renderObject.Component.Entity.Transform;
                                worldMatrix = Matrix.Transformation(original.WorldScale(), look, original.WorldPosition());
                                break;
                            }
                        }

                        if (renderObject.IsFixedSize)
                        {
                            var distVec = diff.Length();

                            worldMatrix.Row1 *= distVec;
                            worldMatrix.Row2 *= distVec;
                            worldMatrix.Row3 *= distVec;
                        }
                    }

                    // If the UI component is not drawn fullscreen it should be drawn as a quad with world sizes corresponding to its actual size
                    worldMatrix = Matrix.Scaling(1f / renderObject.Resolution) * worldMatrix;
                }

                // capture 3D world matrix for picking against things in 3D space
                renderObject.WorldMatrix3D = worldMatrix;

                // Rotation of Pi along 0x to go from UI space to world space
                worldMatrix.Row2 = -worldMatrix.Row2;
                worldMatrix.Row3 = -worldMatrix.Row3;

                Matrix worldViewMatrix;

                Matrix.Multiply(ref worldMatrix, ref viewMatrix, out worldViewMatrix);
                Matrix.Multiply(ref worldViewMatrix, ref projMatrix, out WorldViewProjectionMatrix);
            }
예제 #8
0
        /// <summary>
        /// Rebuilds outdated triangle data for colliders and recalculates hashes storing everything in StaticColliderData
        /// </summary>
        private void BuildInput(StaticColliderData[] collidersLocal, CollisionFilterGroupFlags includedCollisionGroups)
        {
            NavigationMeshCache lastCache = oldNavigationMesh?.Cache;

            bool clearCache = false;

            Dispatcher.ForEach(collidersLocal, colliderData =>
            {
                var entity = colliderData.Component.Entity;
                TransformComponent entityTransform = entity.Transform;
                Matrix entityWorldMatrix           = entityTransform.WorldMatrix;

                NavigationMeshInputBuilder entityNavigationMeshInputBuilder = colliderData.InputBuilder = new NavigationMeshInputBuilder();

                // Compute hash of collider and compare it with the previous build if there is one
                colliderData.ParameterHash = NavigationMeshBuildUtils.HashEntityCollider(colliderData.Component, includedCollisionGroups);
                colliderData.Previous      = null;
                if (lastCache?.Objects.TryGetValue(colliderData.Component.Id, out colliderData.Previous) ?? false)
                {
                    if (colliderData.Previous.ParameterHash == colliderData.ParameterHash)
                    {
                        // In this case, we don't need to recalculate the geometry for this shape, since it wasn't changed
                        // here we take the triangle mesh from the previous build as the current
                        colliderData.InputBuilder = colliderData.Previous.InputBuilder;
                        colliderData.Planes.Clear();
                        colliderData.Planes.AddRange(colliderData.Previous.Planes);
                        colliderData.Processed = false;
                        return;
                    }
                }

                // Clear cache on removal of infinite planes
                if (colliderData.Planes.Count > 0)
                {
                    clearCache = true;
                }

                // Clear planes
                colliderData.Planes.Clear();

                // Return empty data for disabled colliders, filtered out colliders or trigger colliders
                if (!colliderData.Component.Enabled || colliderData.Component.IsTrigger ||
                    !NavigationMeshBuildUtils.CheckColliderFilter(colliderData.Component, includedCollisionGroups))
                {
                    colliderData.Processed = true;
                    return;
                }

                // Make sure shape is up to date
                colliderData.Component.ComposeShape();

                // Interate through all the colliders shapes while queueing all shapes in compound shapes to process those as well
                Queue <ColliderShape> shapesToProcess = new Queue <ColliderShape>();
                if (colliderData.Component.ColliderShape != null)
                {
                    shapesToProcess.Enqueue(colliderData.Component.ColliderShape);
                    while (shapesToProcess.Count > 0)
                    {
                        var shape     = shapesToProcess.Dequeue();
                        var shapeType = shape.GetType();
                        if (shapeType == typeof(BoxColliderShape))
                        {
                            var box          = (BoxColliderShape)shape;
                            var boxDesc      = GetColliderShapeDesc <BoxColliderShapeDesc>(box.Description);
                            Matrix transform = box.PositiveCenterMatrix * entityWorldMatrix;

                            var meshData = GeometricPrimitive.Cube.New(boxDesc.Size, toLeftHanded: true);
                            entityNavigationMeshInputBuilder.AppendMeshData(meshData, transform);
                        }
                        else if (shapeType == typeof(SphereColliderShape))
                        {
                            var sphere       = (SphereColliderShape)shape;
                            var sphereDesc   = GetColliderShapeDesc <SphereColliderShapeDesc>(sphere.Description);
                            Matrix transform = sphere.PositiveCenterMatrix * entityWorldMatrix;

                            var meshData = GeometricPrimitive.Sphere.New(sphereDesc.Radius, toLeftHanded: true);
                            entityNavigationMeshInputBuilder.AppendMeshData(meshData, transform);
                        }
                        else if (shapeType == typeof(CylinderColliderShape))
                        {
                            var cylinder     = (CylinderColliderShape)shape;
                            var cylinderDesc = GetColliderShapeDesc <CylinderColliderShapeDesc>(cylinder.Description);
                            Matrix transform = cylinder.PositiveCenterMatrix * entityWorldMatrix;

                            var meshData = GeometricPrimitive.Cylinder.New(cylinderDesc.Height, cylinderDesc.Radius, toLeftHanded: true);
                            entityNavigationMeshInputBuilder.AppendMeshData(meshData, transform);
                        }
                        else if (shapeType == typeof(CapsuleColliderShape))
                        {
                            var capsule      = (CapsuleColliderShape)shape;
                            var capsuleDesc  = GetColliderShapeDesc <CapsuleColliderShapeDesc>(capsule.Description);
                            Matrix transform = capsule.PositiveCenterMatrix * entityWorldMatrix;

                            var meshData = GeometricPrimitive.Capsule.New(capsuleDesc.Length, capsuleDesc.Radius, toLeftHanded: true);
                            entityNavigationMeshInputBuilder.AppendMeshData(meshData, transform);
                        }
                        else if (shapeType == typeof(ConeColliderShape))
                        {
                            var cone         = (ConeColliderShape)shape;
                            var coneDesc     = GetColliderShapeDesc <ConeColliderShapeDesc>(cone.Description);
                            Matrix transform = cone.PositiveCenterMatrix * entityWorldMatrix;

                            var meshData = GeometricPrimitive.Cone.New(coneDesc.Radius, coneDesc.Height, toLeftHanded: true);
                            entityNavigationMeshInputBuilder.AppendMeshData(meshData, transform);
                        }
                        else if (shapeType == typeof(StaticPlaneColliderShape))
                        {
                            var planeShape   = (StaticPlaneColliderShape)shape;
                            var planeDesc    = GetColliderShapeDesc <StaticPlaneColliderShapeDesc>(planeShape.Description);
                            Matrix transform = entityWorldMatrix;

                            Plane plane = new Plane(planeDesc.Normal, planeDesc.Offset);

                            // Pre-Transform plane parameters
                            plane.Normal = Vector3.TransformNormal(planeDesc.Normal, transform);
                            plane.Normal.Normalize();
                            plane.D += Vector3.Dot(transform.TranslationVector, plane.Normal);

                            colliderData.Planes.Add(plane);
                        }
                        else if (shapeType == typeof(ConvexHullColliderShape))
                        {
                            var hull         = (ConvexHullColliderShape)shape;
                            Matrix transform = hull.PositiveCenterMatrix * entityWorldMatrix;

                            // Convert hull indices to int
                            int[] indices = new int[hull.Indices.Count];
                            if (hull.Indices.Count % 3 != 0)
                            {
                                throw new InvalidOperationException("Physics hull does not consist of triangles");
                            }
                            for (int i = 0; i < hull.Indices.Count; i += 3)
                            {
                                indices[i]     = (int)hull.Indices[i];
                                indices[i + 2] = (int)hull.Indices[i + 1]; // NOTE: Reversed winding to create left handed input
                                indices[i + 1] = (int)hull.Indices[i + 2];
                            }

                            entityNavigationMeshInputBuilder.AppendArrays(hull.Points.ToArray(), indices, transform);
                        }
                        else if (shapeType == typeof(CompoundColliderShape))
                        {
                            // Unroll compound collider shapes
                            var compound = (CompoundColliderShape)shape;
                            for (int i = 0; i < compound.Count; i++)
                            {
                                shapesToProcess.Enqueue(compound[i]);
                            }
                        }
                    }
                }

                // Clear cache on addition of infinite planes
                if (colliderData.Planes.Count > 0)
                {
                    clearCache = true;
                }

                // Mark collider as processed
                colliderData.Processed = true;
            });

            if (clearCache && oldNavigationMesh != null)
            {
                oldNavigationMesh = null;
            }
        }
예제 #9
0
        public void SimulateParticles(ParticleEmitterComponent component, ForcesComponent forces, TransformComponent transform)
        {
            if (component.IsEnabled)
            {
                this.SimulationEffect.Velocity        = component.Velocity.ReadTarget;
                this.SimulationEffect.Position        = component.Position.ReadTarget;
                this.SimulationEffect.InitialVelocity = component.InitialVelocity.ReadTarget;

                this.SimulationEffect.LengthScale     = component.LengthScale;
                this.SimulationEffect.FieldSpeed      = component.FieldSpeed;
                this.SimulationEffect.NoiseStrength   = component.NoiseStrength;
                this.SimulationEffect.ProgressionRate = component.ProgressionRate;
                this.SimulationEffect.SpherePosition  = component.SpherePosition;
                this.SimulationEffect.SphereRadius    = component.SphereRadius;
                this.SimulationEffect.EmitterSize     = component.Size;
                this.SimulationEffect.MaxLifeTime     = component.MaxLifeTime;

                this.SimulationEffect.Elapsed = this.FrameService.Elapsed;
                this.SimulationEffect.Time    = this.FrameService.Time;

                this.SimulationEffect.ParentVelocity = forces.Velocity;
                this.SimulationEffect.ObjectToWorld  = transform.Matrix;
                this.SimulationEffect.WorldToObject  = Matrix.Invert(transform.Matrix);

                this.SimulationEffect.ApplyParticleVelocitySimulationTechnique();
                this.Device.SetRenderTarget(component.Velocity.WriteTarget);
                this.PostProcessTriangle.Render(this.Device);

                this.SimulationEffect.ApplyParticlePositionSimulationTechnique();
                this.Device.SetRenderTargets(component.Position.WriteTarget, component.InitialVelocity.WriteTarget);
                this.PostProcessTriangle.Render(this.Device);

                component.Swap();
            }
        }
예제 #10
0
        public static TemporaryManipulateTransformKepperComponent Create(Matrix4x4 temporary, TransformComponent original)
        {
            return(new TemporaryManipulateTransformKepperComponent {
                Tag = new ElementTag(Guid.NewGuid().ToString()),
                Original = original,
                temporary = temporary,

                IsModified = true,
                IsValid = true,
            });
        }
예제 #11
0
 /// <summary>
 /// Depending on which direction the vehicle is facing,
 /// change its draw depth. Vehicles can choose between special drawdetph
 /// when facing north or south. East and west are easy.
 /// </summary>
 private int GetDrawDepth(TransformComponent xform, bool northOnly)
 {
     if (northOnly)
     {
         return(xform.LocalRotation.Degrees switch
         {
        private unsafe object ExportAnimation(ICommandContext commandContext, ContentManager contentManager)
        {
            // Read from model file
            var modelSkeleton = LoadSkeleton(commandContext, contentManager); // we get model skeleton to compare it to real skeleton we need to map to

            AdjustSkeleton(modelSkeleton);

            TimeSpan      duration;
            var           animationClips = LoadAnimation(commandContext, contentManager, out duration);
            AnimationClip animationClip  = null;

            if (animationClips.Count > 0)
            {
                animationClip          = new AnimationClip();
                animationClip.Duration = duration;

                AnimationClip rootMotionAnimationClip = null;

                // If root motion is explicitely enabled, or if there is no skeleton, try to find root node and apply animation directly on TransformComponent
                if ((AnimationRootMotion || SkeletonUrl == null) && modelSkeleton.Nodes.Length >= 1)
                {
                    // No skeleton, map root node only
                    // TODO: For now, it seems to be located on node 1 in FBX files. Need to check if always the case, and what happens with Assimp
                    var rootNode0 = modelSkeleton.Nodes.Length >= 1 ? modelSkeleton.Nodes[0].Name : null;
                    var rootNode1 = modelSkeleton.Nodes.Length >= 2 ? modelSkeleton.Nodes[1].Name : null;
                    if ((rootNode0 != null && animationClips.TryGetValue(rootNode0, out rootMotionAnimationClip)) ||
                        (rootNode1 != null && animationClips.TryGetValue(rootNode1, out rootMotionAnimationClip)))
                    {
                        foreach (var channel in rootMotionAnimationClip.Channels)
                        {
                            var curve = rootMotionAnimationClip.Curves[channel.Value.CurveIndex];

                            // Root motion
                            var channelName = channel.Key;
                            if (channelName.StartsWith("Transform."))
                            {
                                animationClip.AddCurve($"[TransformComponent.Key]." + channelName.Replace("Transform.", string.Empty), curve);
                            }

                            // Also apply Camera curves
                            // TODO: Add some other curves?
                            if (channelName.StartsWith("Camera."))
                            {
                                animationClip.AddCurve($"[CameraComponent.Key]." + channelName.Replace("Camera.", string.Empty), curve);
                            }
                        }
                    }
                }

                // Load asset reference skeleton
                if (SkeletonUrl != null)
                {
                    var skeleton        = contentManager.Load <Skeleton>(SkeletonUrl);
                    var skeletonMapping = new SkeletonMapping(skeleton, modelSkeleton);

                    // Process missing nodes
                    foreach (var nodeAnimationClipEntry in animationClips)
                    {
                        var nodeName          = nodeAnimationClipEntry.Key;
                        var nodeAnimationClip = nodeAnimationClipEntry.Value;
                        var nodeIndex         = modelSkeleton.Nodes.IndexOf(x => x.Name == nodeName);

                        // Node doesn't exist in skeleton? skip it
                        if (nodeIndex == -1 || skeletonMapping.SourceToSource[nodeIndex] != nodeIndex)
                        {
                            continue;
                        }

                        // Skip root motion node (if any)
                        if (nodeAnimationClip == rootMotionAnimationClip)
                        {
                            continue;
                        }

                        // Find parent node
                        var parentNodeIndex = modelSkeleton.Nodes[nodeIndex].ParentIndex;

                        if (parentNodeIndex != -1 && skeletonMapping.SourceToSource[parentNodeIndex] != parentNodeIndex)
                        {
                            // Some nodes were removed, we need to concat the anim curves
                            var currentNodeIndex = nodeIndex;
                            var nodesToMerge     = new List <Tuple <ModelNodeDefinition, AnimationBlender, AnimationClipEvaluator> >();
                            while (currentNodeIndex != -1 && currentNodeIndex != skeletonMapping.SourceToSource[parentNodeIndex])
                            {
                                AnimationClip          animationClipToMerge;
                                AnimationClipEvaluator animationClipEvaluator = null;
                                AnimationBlender       animationBlender       = null;
                                if (animationClips.TryGetValue(modelSkeleton.Nodes[currentNodeIndex].Name, out animationClipToMerge))
                                {
                                    animationBlender       = new AnimationBlender();
                                    animationClipEvaluator = animationBlender.CreateEvaluator(animationClipToMerge);
                                }
                                nodesToMerge.Add(Tuple.Create(modelSkeleton.Nodes[currentNodeIndex], animationBlender, animationClipEvaluator));
                                currentNodeIndex = modelSkeleton.Nodes[currentNodeIndex].ParentIndex;
                            }

                            // Put them in proper parent to children order
                            nodesToMerge.Reverse();

                            // Find all key times
                            // TODO: We should detect discontinuities and keep them
                            var animationKeysSet = new HashSet <CompressedTimeSpan>();

                            foreach (var node in nodesToMerge)
                            {
                                foreach (var curve in node.Item3.Clip.Curves)
                                {
                                    foreach (CompressedTimeSpan time in curve.Keys)
                                    {
                                        animationKeysSet.Add(time);
                                    }
                                }
                            }

                            // Sort key times
                            var animationKeys = animationKeysSet.ToList();
                            animationKeys.Sort();

                            var animationOperations = new FastList <AnimationOperation>();

                            var combinedAnimationClip = new AnimationClip();

                            var translationCurve = new AnimationCurve <Vector3>();
                            var rotationCurve    = new AnimationCurve <Quaternion>();
                            var scaleCurve       = new AnimationCurve <Vector3>();

                            // Evaluate at every key frame
                            foreach (var animationKey in animationKeys)
                            {
                                var matrix = Matrix.Identity;

                                // Evaluate node
                                foreach (var node in nodesToMerge)
                                {
                                    // Get default position
                                    var modelNodeDefinition = node.Item1;

                                    // Compute
                                    AnimationClipResult animationClipResult = null;
                                    animationOperations.Clear();
                                    animationOperations.Add(AnimationOperation.NewPush(node.Item3, animationKey));
                                    node.Item2.Compute(animationOperations, ref animationClipResult);

                                    var updateMemberInfos = new List <UpdateMemberInfo>();
                                    foreach (var channel in animationClipResult.Channels)
                                    {
                                        updateMemberInfos.Add(new UpdateMemberInfo {
                                            Name = channel.PropertyName, DataOffset = channel.Offset
                                        });
                                    }

                                    // TODO: Cache this
                                    var compiledUpdate = UpdateEngine.Compile(typeof(ModelNodeDefinition), updateMemberInfos);

                                    unsafe
                                    {
                                        fixed(byte *data = animationClipResult.Data)
                                        UpdateEngine.Run(modelNodeDefinition, compiledUpdate, (IntPtr)data, null);
                                    }

                                    Matrix localMatrix;
                                    TransformComponent.CreateMatrixTRS(ref modelNodeDefinition.Transform.Position, ref modelNodeDefinition.Transform.Rotation, ref modelNodeDefinition.Transform.Scale,
                                                                       out localMatrix);
                                    matrix = Matrix.Multiply(localMatrix, matrix);
                                }

                                // Done evaluating, let's decompose matrix
                                TransformTRS transform;
                                matrix.Decompose(out transform.Scale, out transform.Rotation, out transform.Position);

                                // Create a key
                                translationCurve.KeyFrames.Add(new KeyFrameData <Vector3>(animationKey, transform.Position));
                                rotationCurve.KeyFrames.Add(new KeyFrameData <Quaternion>(animationKey, transform.Rotation));
                                scaleCurve.KeyFrames.Add(new KeyFrameData <Vector3>(animationKey, transform.Scale));
                            }

                            combinedAnimationClip.AddCurve($"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Position)}", translationCurve);
                            combinedAnimationClip.AddCurve($"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Rotation)}", rotationCurve);
                            combinedAnimationClip.AddCurve($"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Scale)}", scaleCurve);
                            nodeAnimationClip = combinedAnimationClip;
                        }

                        var transformStart    = $"{nameof(ModelNodeTransformation.Transform)}.";
                        var transformPosition = $"{nameof(ModelNodeTransformation.Transform)}.{nameof(TransformTRS.Position)}";

                        foreach (var channel in nodeAnimationClip.Channels)
                        {
                            var curve = nodeAnimationClip.Curves[channel.Value.CurveIndex];

                            // TODO: Root motion
                            var channelName = channel.Key;
                            if (channelName.StartsWith(transformStart))
                            {
                                if (channelName == transformPosition)
                                {
                                    // Translate node with parent 0 using PivotPosition
                                    var keyFrames = ((AnimationCurve <Vector3>)curve).KeyFrames;
                                    for (int i = 0; i < keyFrames.Count; ++i)
                                    {
                                        if (parentNodeIndex == 0)
                                        {
                                            keyFrames.Items[i].Value -= PivotPosition;
                                        }
                                        keyFrames.Items[i].Value *= ScaleImport;
                                    }
                                }
                                animationClip.AddCurve($"[ModelComponent.Key].Skeleton.NodeTransformations[{skeletonMapping.SourceToTarget[nodeIndex]}]." + channelName, curve);
                            }
                        }
                    }
                }
            }

            if (animationClip == null)
            {
                commandContext.Logger.Info("File {0} has an empty animation.", SourcePath);
            }
            else
            {
                if (animationClip.Duration.Ticks == 0)
                {
                    commandContext.Logger.Warning("File {0} has a 0 tick long animation.", SourcePath);
                }

                // Optimize and set common parameters
                animationClip.RepeatMode = AnimationRepeatMode;
                animationClip.Optimize();
            }
            return(animationClip);
        }
예제 #13
0
        public override void Update(float dt)
        {
            foreach (Entity rotationEntity in _rotationEntities)
            {
                TransformComponent rotationTransform = rotationEntity.GetComponent <TransformComponent>();
                float  closestDistance = float.PositiveInfinity;
                Entity closestPlayer   = null;

                foreach (Entity playerEntity in _playerEntities)
                {
                    TransformComponent playerTransform = playerEntity.GetComponent <TransformComponent>();
                    float distance = (rotationTransform.Position - playerTransform.Position).Length();

                    if (distance < closestDistance)
                    {
                        closestDistance = distance;
                        closestPlayer   = playerEntity;
                    }
                }

                if (closestPlayer != null)
                {
                    float currentRotation = rotationEntity.GetComponent <TransformComponent>().Rotation;

                    Vector2 target = closestPlayer.GetComponent <TransformComponent>().Position - rotationTransform.Position;

                    float targetAngle = (float)Math.Atan2(target.Y, target.X);

                    currentRotation = MathHelper.WrapAngle(currentRotation);
                    targetAngle     = MathHelper.WrapAngle(targetAngle);

                    float diff     = targetAngle - currentRotation;
                    float newAngle = currentRotation;

                    if (diff > 0)
                    {
                        if (Math.Abs(diff) < Math.PI)
                        {
                            newAngle += rotationEntity.GetComponent <RotationComponent>().RotationSpeed *dt;
                        }
                        else
                        {
                            newAngle -= rotationEntity.GetComponent <RotationComponent>().RotationSpeed *dt;
                        }
                    }
                    else
                    {
                        if (Math.Abs(diff) < Math.PI)
                        {
                            newAngle -= rotationEntity.GetComponent <RotationComponent>().RotationSpeed *dt;
                        }
                        else
                        {
                            newAngle += rotationEntity.GetComponent <RotationComponent>().RotationSpeed *dt;
                        }
                    }

                    Vector2 newDirection = new Vector2((float)Math.Cos(newAngle), (float)Math.Sin(newAngle));
                    rotationEntity.GetComponent <MovementComponent>().MovementVector = newDirection * rotationEntity.GetComponent <MovementComponent>().MovementVector.Length();
                    rotationEntity.GetComponent <TransformComponent>().Rotate(newAngle - currentRotation);
                }
            }
        }
예제 #14
0
 /// <summary>
 /// Rotates the given <see cref="TransformComponent"/> by the specified <paramref name="eulerAngles"/> in the coordinate space defined by <paramref name="relativeTo"/>.
 /// </summary>
 /// <param name="transform">The <see cref="TransformComponent"/> to update.</param>
 /// <param name="eulerAngles">The euler angles in radians to rotate by.</param>
 /// <param name="relativeTo">The coordinate space to perform the rotation in.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException">If <paramref name="transform"/> has <see cref="TransformComponent.UseTRS"/> set to <see langword="null"/>.</exception>
 /// <remarks>
 /// This method updates the <see cref="TransformComponent.LocalMatrix"/> and <see cref="TransformComponent.WorldMatrix"/> after transformation.
 /// </remarks>
 public static void Rotate(this TransformComponent transform, Vector3 eulerAngles, Space relativeTo = Space.Self)
 {
     transform.Rotate(ref eulerAngles, relativeTo);
 }
예제 #15
0
 /// <summary>
 /// Moves the given <see cref="TransformComponent"/> position by the specified <paramref name="translation"/> relative to the local coordinate space of another <see cref="TransformComponent"/>.
 /// </summary>
 /// <param name="transform">The <see cref="TransformComponent"/> to update.</param>
 /// <param name="translation">The translation vector to move by.</param>
 /// <param name="relativeTo">The <see cref="TransformComponent"/> to perform the translation relative to.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> or <paramref name="relativeTo"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException">If <paramref name="transform"/> has <see cref="TransformComponent.UseTRS"/> set to <see langword="null"/>.</exception>
 /// <remarks>
 /// This method updates the <see cref="TransformComponent.LocalMatrix"/> and <see cref="TransformComponent.WorldMatrix"/> after transformation.
 /// </remarks>
 public static void Translate(this TransformComponent transform, Vector3 translation, TransformComponent relativeTo)
 {
     transform.Translate(ref translation, relativeTo);
 }
예제 #16
0
        /// <summary>
        /// Moves the given <see cref="TransformComponent"/> position by the specified <paramref name="translation"/> relative to the local coordinate space of another <see cref="TransformComponent"/>.
        /// </summary>
        /// <param name="transform">The <see cref="TransformComponent"/> to update.</param>
        /// <param name="translation">The translation vector to move by.</param>
        /// <param name="relativeTo">The <see cref="TransformComponent"/> to perform the translation relative to.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="transform"/> or <paramref name="relativeTo"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="transform"/> has <see cref="TransformComponent.UseTRS"/> set to <see langword="null"/>.</exception>
        /// <remarks>
        /// This method updates the <see cref="TransformComponent.LocalMatrix"/> and <see cref="TransformComponent.WorldMatrix"/> after transformation.
        /// </remarks>
        public static void Translate(this TransformComponent transform, ref Vector3 translation, TransformComponent relativeTo)
        {
            if (transform == null)
            {
                throw new ArgumentNullException(nameof(transform));
            }

            if (!transform.UseTRS)
            {
                throw new ArgumentException("Must use TRS", nameof(transform));
            }

            if (relativeTo == null)
            {
                throw new ArgumentNullException(nameof(relativeTo));
            }

            relativeTo.TransformDirection(ref translation, out var localTranslation);
            transform.Translate(ref localTranslation, Space.World);
        }
예제 #17
0
 public void LockModelToHeight(TerrainMapComponent terComp, TransformComponent trsComp, float offset)
 {
     trsComp.Position = new Vector3(trsComp.Position.X, offset + TerrainMapRenderSystem.GetTerrainHeight(terComp, trsComp.Position.X, Math.Abs(trsComp.Position.Z)), trsComp.Position.Z);
 }
        public override void Update(float dt)
        {
            Dictionary <Entity, List <Entity> > correctedEntityPairs = new Dictionary <Entity, List <Entity> >();

            foreach (Entity entity in _movingEnemyEntities)
            {
                QuadTreeReferenceComponent quadTreeReferenceComp = entity.GetComponent <QuadTreeReferenceComponent>();
                if (quadTreeReferenceComp.node == null)
                {
                    // Quad tree hasn't been generated yet (or this entity isn't a part of it yet),
                    // skip.
                    continue;
                }
                TransformComponent transformComp = entity.GetComponent <TransformComponent>();

                QuadTreeNode root = quadTreeReferenceComp.node;
                while (root.parent != null)
                {
                    root = root.parent;
                }

                // Find all quad tree nodes that intersect the radius we are searching for
                float radius        = CVars.Get <float>("enemy_minimum_separation_distance");
                float radiusSquared = radius * radius;
                List <QuadTreeNode> intersectingNodes = new List <QuadTreeNode>();
                InsertIntersectingChildNodes(transformComp.Position, radius, quadTreeReferenceComp.node, root, ref intersectingNodes);

                List <Entity> neighborEntities = new List <Entity>();
                foreach (QuadTreeNode node in intersectingNodes)
                {
                    foreach (Entity otherEntity in node.leaves)
                    {
                        if (otherEntity == entity)
                        {
                            continue;
                        }

                        if (_movingEnemyFamily.Matches(otherEntity))
                        {
                            TransformComponent otherTransformComp = otherEntity.GetComponent <TransformComponent>();
                            if ((transformComp.Position - otherTransformComp.Position).LengthSquared() <= radiusSquared)
                            {
                                neighborEntities.Add(otherEntity);
                            }
                        }
                    }
                }

                if (neighborEntities.Count > 0)
                {
                    foreach (Entity otherEntity in neighborEntities)
                    {
                        if (!correctedEntityPairs.ContainsKey(entity))
                        {
                            correctedEntityPairs.Add(entity, new List <Entity>());
                        }
                        if (correctedEntityPairs[entity].Contains(otherEntity))
                        {
                            // This entity pair has already been separated, skip
                            continue;
                        }

                        SeparateEntities(entity, otherEntity, radius);

                        // Add to other's list, since this Entity is this current loop (can't loop this entity again this frame)
                        if (!correctedEntityPairs.ContainsKey(otherEntity))
                        {
                            correctedEntityPairs.Add(otherEntity, new List <Entity>());
                        }
                        correctedEntityPairs[otherEntity].Add(entity);
                    }
                }
            }
        }
예제 #19
0
 /// <summary>
 /// Performs a coordinate transformation using the inverse of the given <see cref="TransformComponent.WorldMatrix"/>.
 /// </summary>
 /// <param name="transform">The transform to get the world matrix from.</param>
 /// <param name="position">The coordinate vector to transform.</param>
 /// <returns>The transformed coordinate.</returns>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> is <see langword="null"/>.</exception>
 /// <remarks>
 /// This method does not update the <see cref="TransformComponent.WorldMatrix"/> before performing the transformation.
 /// If the <see cref="TransformComponent"/> has been modified since the last frame you may need to call the <see cref="TransformComponent.UpdateWorldMatrix"/> method first.
 /// </remarks>
 public static Vector3 InverseTransformPosition(this TransformComponent transform, Vector3 position)
 {
     transform.InverseTransformPosition(ref position, out var result);
     return(result);
 }
예제 #20
0
 /// <summary>
 /// Performs a normal transformation using the inverse of the given <see cref="TransformComponent.WorldMatrix"/>.
 /// </summary>
 /// <param name="transform">The transform to get the world matrix from.</param>
 /// <param name="vector">The normal vector to transform.</param>
 /// <returns>The transformed normal.</returns>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> is <see langword="null"/>.</exception>
 /// <remarks>
 /// This method does not update the <see cref="TransformComponent.WorldMatrix"/> before performing the transformation.
 /// If the <see cref="TransformComponent"/> has been modified since the last frame you may need to call the <see cref="TransformComponent.UpdateWorldMatrix"/> method first.
 /// </remarks>
 public static Vector3 InverseTransformVector(this TransformComponent transform, Vector3 vector)
 {
     transform.InverseTransformVector(ref vector, out var result);
     return(result);
 }
        public EatResponse OnEvent(EventId id, object cookie)
        {
            switch (id)
            {
            case EventId.PreEntityKilled:
            {
                Entity             entity             = (Entity)cookie;
                BuildingComponent  buildingComponent  = entity.Get <BuildingComponent>();
                TransformComponent transformComponent = entity.Get <TransformComponent>();
                if (transformComponent != null)
                {
                    DefensiveCameraEventType type = DefensiveCameraEventType.TroopDestroyed;
                    if (buildingComponent != null)
                    {
                        if (buildingComponent.BuildingType.Type == BuildingType.Wall)
                        {
                            type = DefensiveCameraEventType.WallDestroyed;
                        }
                        else
                        {
                            type = DefensiveCameraEventType.BuildingDestroyed;
                        }
                    }
                    this.AddCameraEvent(Units.BoardToWorldX(transformComponent.CenterX()), Units.BoardToWorldZ(transformComponent.CenterZ()), type);
                }
                break;
            }

            case EventId.EntityKilled:
            {
                Entity item = (Entity)cookie;
                if (this.currentWave != null && this.currentWave.Troops.Contains(item))
                {
                    this.currentWave.Troops.Remove(item);
                    if (this.currentWave.Troops.Count == 0 && this.timers.Count == 0)
                    {
                        this.EndCurrentWave();
                    }
                }
                break;
            }

            case EventId.PostBuildingEntityKilled:
            case EventId.EntityDestroyed:
                break;

            case EventId.EntityHit:
            {
                Bullet             bullet        = (Bullet)cookie;
                SmartEntity        target        = bullet.Target;
                uint               iD            = target.ID;
                TransformComponent transformComp = target.TransformComp;
                BuildingComponent  buildingComp  = target.BuildingComp;
                if (buildingComp != null && transformComp != null)
                {
                    if (this.numTimesEntityHit.ContainsKey(iD))
                    {
                        Dictionary <uint, int> arg_17B_0 = this.numTimesEntityHit;
                        uint key = iD;
                        int  num = arg_17B_0[key];
                        arg_17B_0[key] = num + 1;
                    }
                    else
                    {
                        this.numTimesEntityHit.Add(iD, 1);
                    }
                    if (this.currentCameraEvent == null || this.numTimesEntityHit[iD] > 5)
                    {
                        this.numTimesEntityHit[iD] = 0;
                        this.AddCameraEvent(Units.BoardToWorldX(transformComp.CenterX()), Units.BoardToWorldZ(transformComp.CenterZ()), DefensiveCameraEventType.EntityDamaged);
                    }
                }
                break;
            }

            default:
                if (id != EventId.CameraFinishedMoving)
                {
                    if (id == EventId.UserStartedCameraMove)
                    {
                        this.autoMoveCamera = false;
                        this.cameraEvents.Clear();
                        this.numTimesEntityHit.Clear();
                        this.UnRegisterObservers();
                    }
                }
                else
                {
                    this.MoveCameraToAction();
                }
                break;
            }
            return(EatResponse.NotEaten);
        }
예제 #22
0
 /// <summary>
 /// Sets the transforms rotation so it's forward vector points at the <paramref name="target"/>.
 /// The world up vector use is defined by <see cref="WorldUp"/>.
 /// </summary>
 /// <param name="transform">The <see cref="TransformComponent"/> to update.</param>
 /// <param name="target">The target to point towards</param>
 /// <param name="smooth">Value between 0 and 1 indicating the weight of target orientation. The default is 1.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException">If <paramref name="transform"/> has <see cref="TransformComponent.UseTRS"/> set to <see langword="null"/>.</exception>
 /// <remarks>
 /// This method updates the <see cref="TransformComponent.LocalMatrix"/> and <see cref="TransformComponent.WorldMatrix"/> after transformation.
 /// </remarks>
 public static void LookAt(this TransformComponent transform, Vector3 target, float smooth = 1.0f)
 {
     transform.LookAt(ref target, ref WorldUp, smooth);
 }
예제 #23
0
 public abstract void Process(TransformComponent transformComponent);
예제 #24
0
 /// <summary>
 /// Moves the given <see cref="TransformComponent"/> position by the specified <paramref name="translation"/> in the coordinate space defined by <paramref name="relativeTo"/>.
 /// </summary>
 /// <param name="transform">The <see cref="TransformComponent"/> to update.</param>
 /// <param name="translation">The translation vector to move by.</param>
 /// <param name="relativeTo">The coordinate space to perform the translation in.</param>
 /// <exception cref="ArgumentNullException">If <paramref name="transform"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException">If <paramref name="transform"/> has <see cref="TransformComponent.UseTRS"/> set to <see langword="null"/>.</exception>
 /// <remarks>
 /// This method updates the <see cref="TransformComponent.LocalMatrix"/> and <see cref="TransformComponent.WorldMatrix"/> after transformation.
 /// </remarks>
 public static void Translate(this TransformComponent transform, Vector3 translation, Space relativeTo = Space.Self)
 {
     transform.Translate(ref translation, relativeTo);
 }
예제 #25
0
        public static void Render(SpriteBatch spriteBatch, ContentManager contentManager, TransformComponent transform, Color color, int radius)
        {
            if (_circle == null)
            {
                _circle = contentManager.Load <Texture2D>("explosion");
            }

            var worldPosition  = transform.WorldPosition;
            var renderPosition = new Vector2(worldPosition.X - radius, worldPosition.Y - radius);

            spriteBatch.Draw(_circle, renderPosition, null, Color.White, 0, Vector2.Zero, 0.3f, SpriteEffects.None, 0);
        }
예제 #26
0
        SceneContainer CreateScene()
        {
            // Initialize transform components that need to be changed inside "RenderAFrame"
            _baseTransform = new TransformComponent
            {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 0, 0)
            };
            _bodyTransform = new TransformComponent
            {
                Rotation    = new float3(0, 1.2f, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 6, 0)
            };
            _upperArmTransform = new TransformComponent
            {
                Rotation    = new float3(0.8f, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(2, 4, 0)
            };
            _foreArmTransform = new TransformComponent
            {
                Rotation    = new float3(0.8f, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(-2, 8, 0)
            };

            // Setup the scene graph
            return(new SceneContainer
            {
                Children = new List <SceneNodeContainer>
                {
                    // GREY BASE
                    new SceneNodeContainer
                    {
                        Components = new List <SceneComponentContainer>
                        {
                            // TRANSFROM COMPONENT
                            _baseTransform,

                            // SHADER EFFECT COMPONENT
                            new ShaderEffectComponent
                            {
                                Effect = SimpleMeshes.MakeShaderEffect(new float3(0.7f, 0.7f, 0.7f), new float3(0.7f, 0.7f, 0.7f), 5)
                            },

                            // MESH COMPONENT
                            SimpleMeshes.CreateCuboid(new float3(10, 2, 10))
                        }
                    },
                    // RED BODY
                    new SceneNodeContainer
                    {
                        Components = new List <SceneComponentContainer>
                        {
                            _bodyTransform,
                            new ShaderEffectComponent
                            {
                                Effect = SimpleMeshes.MakeShaderEffect(new float3(1, 0, 0), new float3(1, 1, 1), 5)
                            },
                            SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                        },
                        Children = new ChildList
                        {
                            // GREEN UPPER ARM
                            new SceneNodeContainer
                            {
                                Components = new List <SceneComponentContainer>
                                {
                                    _upperArmTransform,
                                },
                                Children = new ChildList
                                {
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            new TransformComponent
                                            {
                                                Rotation = new float3(0, 0, 0),
                                                Scale = new float3(1, 1, 1),
                                                Translation = new float3(0, 4, 0)
                                            },
                                            new ShaderEffectComponent
                                            {
                                                Effect = SimpleMeshes.MakeShaderEffect(new float3(0, 1, 0), new float3(1, 1, 1), 5)
                                            },
                                            SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                        }
                                    },
                                    // BLUE FOREARM
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            _foreArmTransform,
                                        },
                                        Children = new ChildList
                                        {
                                            new SceneNodeContainer
                                            {
                                                Components = new List <SceneComponentContainer>
                                                {
                                                    new TransformComponent
                                                    {
                                                        Rotation = new float3(0, 0, 0),
                                                        Scale = new float3(1, 1, 1),
                                                        Translation = new float3(0, 4, 0)
                                                    },
                                                    new ShaderEffectComponent
                                                    {
                                                        Effect = SimpleMeshes.MakeShaderEffect(new float3(0, 0, 1), new float3(1, 1, 1), 5)
                                                    },
                                                    SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                        }
                    }
                }
            });
        }
예제 #27
0
        /// <summary>The render.</summary>
        /// <param name="spriteBatch">The sprite batch.</param>
        /// <param name="contentManager">The content manager.</param>
        /// <param name="transformComponent">The TransformComponent.</param>
        public static void Render(SpriteBatch spriteBatch, ContentManager contentManager, TransformComponent transformComponent)
        {
            if (ship == null)
            {
                ship = contentManager.Load <Texture2D>("player");
            }

            spriteBatch.Draw(ship, new Vector2(transformComponent.X - (ship.Width * 0.5f), transformComponent.Y - (ship.Height * 0.5f)), ship.Bounds, Color.White);
        }
        SceneContainer CreateScene()
        {
            // Initialize transform components that need to be changed inside "RenderAFrame"
            _baseTransform = new TransformComponent
            {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 0, 0),
            };
            _bodyTransform = new TransformComponent
            {
                Rotation    = new float3(0, 1.2f, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 6, 0),
            };
            _upperArmTransform = new TransformComponent
            {
                Rotation    = new float3(0.8f, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(2, 4, 0),
            };
            _foreArmTransform = new TransformComponent
            {
                Rotation    = new float3(0.8f, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(-2, 8, 0),
            };
            _greifhand1Transform = new TransformComponent
            {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 1.5f, 0),
            };
            _greifhand2Transform = new TransformComponent
            {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(-4.5f, -1, 0),
            };
            _greifhand3Transform = new TransformComponent
            {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(4.5f, -1, 0),
            };

            // Setup the scene graph
            return(new SceneContainer
            {
                Children = new List <SceneNodeContainer>
                {
                    // GREY BASE
                    new SceneNodeContainer
                    {
                        Components = new List <SceneComponentContainer>
                        {
                            // TRANSFROM COMPONENT
                            _baseTransform,

                            // MATERIAL COMPONENT
                            new MaterialComponent
                            {
                                Diffuse = new MatChannelContainer {
                                    Color = new float3(0.7f, 0.7f, 0.7f)
                                },
                                Specular = new SpecularChannelContainer {
                                    Color = new float3(1, 1, 1), Shininess = 5
                                }
                            },

                            // MESH COMPONENT
                            SimpleMeshes.CreateCuboid(new float3(10, 2, 10))
                        }
                    },
                    // RED BODY
                    new SceneNodeContainer
                    {
                        Components = new List <SceneComponentContainer>
                        {
                            _bodyTransform,
                            new MaterialComponent
                            {
                                Diffuse = new MatChannelContainer {
                                    Color = new float3(1, 0, 0)
                                },
                                Specular = new SpecularChannelContainer {
                                    Color = new float3(1, 1, 1), Shininess = 5
                                }
                            },
                            SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                        },
                        Children = new List <SceneNodeContainer>
                        {
                            // GREEN UPPER ARM
                            new SceneNodeContainer
                            {
                                Components = new List <SceneComponentContainer>
                                {
                                    _upperArmTransform,
                                },
                                Children = new List <SceneNodeContainer>
                                {
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            new TransformComponent
                                            {
                                                Rotation = new float3(0, 0, 0),
                                                Scale = new float3(1, 1, 1),
                                                Translation = new float3(0, 4, 0)
                                            },
                                            new MaterialComponent
                                            {
                                                Diffuse = new MatChannelContainer {
                                                    Color = new float3(0, 1, 0)
                                                },
                                                Specular = new SpecularChannelContainer {
                                                    Color = new float3(1, 1, 1), Shininess = 5
                                                }
                                            },
                                            SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                        }
                                    },
                                    // BLUE FOREARM
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            _foreArmTransform,
                                        },
                                        Children = new List <SceneNodeContainer>
                                        {
                                            new SceneNodeContainer
                                            {
                                                Components = new List <SceneComponentContainer>
                                                {
                                                    new TransformComponent
                                                    {
                                                        Rotation = new float3(0, 0, 0),
                                                        Scale = new float3(1, 1, 1),
                                                        Translation = new float3(0, 4, 0)
                                                    },
                                                    new MaterialComponent
                                                    {
                                                        Diffuse = new MatChannelContainer {
                                                            Color = new float3(0, 0, 1)
                                                        },
                                                        Specular = new SpecularChannelContainer {
                                                            Color = new float3(1, 1, 1), Shininess = 5
                                                        }
                                                    },
                                                    SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                                }
                                                // Greifhand1
                                                new SceneNodeContainer {
                                                    Components = new List <SceneComponentContainer> {
                                                        _greifhand1Transform,
                                                    },
                                                    Children = new List <SceneNodeContainer> {
                                                        new SceneNodeContainer {
                                                            Components = new List <SceneComponentContainer> {
                                                                new TransformComponent {
                                                                    Rotation = new float3(0, 0, 0),
                                                                    Scale = new float3(1, 1, 1),
                                                                    Translation = new float3(0, 4, 0)
                                                                },
                                                                new MaterialComponent {
                                                                    Diffuse = new MatChannelContainer {
                                                                        Color = new float3(1, 1, 0)
                                                                    },
                                                                    Specular = new SpecularChannelContainer {
                                                                        Color = new float3(1, 1, 1), Shininess = 5
                                                                    }
                                                                }
                                                            },
                                                            SimpleMeshes.CreateCuboid(new float3(10, 1, 2))
                                                        },
예제 #29
0
        public static void Render(ContentManager content, GraphicsDevice graphicsDevice, TransformComponent transform, CameraComponent camera, BasicEffect effect)
        {
            if (_quad == null)
            {
                _texture = content.Load <Texture2D>("Images/OryxChar");
                TextureFrame textureFrame = new TextureFrame(0.292f, 0.031f, 0.042f, 0.031f);

                Vector3 normal = camera.Rotation.Forward * -1;
                Vector3 up     = camera.Rotation.Up;

                _quad = new QuadShape(transform.Position, normal, up, textureFrame, 0.5f, 0.5f);
            }

            _quad.Origin = transform.Position + new Vector3(0, _quad.Height / 2.0f, 0);
            _quad.UpdateVertexData();

            effect.Texture = _texture;

            graphicsDevice.DrawUserIndexedPrimitives <VertexPositionNormalTexture>(PrimitiveType.TriangleList, _quad.Vertices, 0, 4, _quad.Indexes, 0, 2);
        }
예제 #30
0
        public void RotateGameObject(SmartEntity entity, float dx, float dz, float dt)
        {
            GameObjectViewComponent gameObjectViewComp = entity.GameObjectViewComp;
            TransformComponent      transformComp      = entity.TransformComp;

            if (entity.TroopComp != null && entity.TroopComp.TroopShooterVO.TargetSelf && transformComp.RotationInitialized)
            {
                return;
            }
            float                     num                     = transformComp.Rotation;
            bool                      flag                    = dx != 0f || dz != 0f;
            SmartEntity               smartEntity             = null;
            GameObjectViewComponent   gameObjectViewComponent = null;
            SecondaryTargetsComponent secondaryTargetsComp    = entity.SecondaryTargetsComp;
            ShooterComponent          shooterComp             = entity.ShooterComp;

            if (secondaryTargetsComp != null && shooterComp != null)
            {
                ShooterController shooterController = Service.ShooterController;
                smartEntity = shooterController.GetTroopTarget(secondaryTargetsComp, shooterComp);
                if (smartEntity != null && (gameObjectViewComponent = smartEntity.GameObjectViewComp) == null)
                {
                    smartEntity = shooterController.GetPrimaryTarget(shooterComp);
                    if (smartEntity != null)
                    {
                        gameObjectViewComponent = smartEntity.GameObjectViewComp;
                    }
                }
            }
            else
            {
                PathingComponent pathingComp = entity.PathingComp;
                if (pathingComp != null)
                {
                    smartEntity = pathingComp.Target;
                    if (smartEntity != null)
                    {
                        gameObjectViewComponent = smartEntity.GameObjectViewComp;
                    }
                }
            }
            bool flag2 = !transformComp.RotationInitialized;

            if (flag2 && smartEntity == null && (entity.DefenderComp != null || TroopController.IsEntityHealer(entity)))
            {
                gameObjectViewComp.MainGameObject.SetActive(true);
                transformComp.RotationInitialized = true;
            }
            else
            {
                bool flag3 = flag2 || entity.StateComp.CurState == EntityState.Attacking || entity.StateComp.CurState == EntityState.Turning;
                if (flag3 && gameObjectViewComponent != null)
                {
                    gameObjectViewComp.ComputeRotationToTarget(gameObjectViewComponent, ref num);
                    flag = false;
                    if (flag2)
                    {
                        gameObjectViewComp.MainGameObject.SetActive(true);
                        transformComp.Rotation            = num;
                        transformComp.RotationInitialized = true;
                    }
                }
            }
            if (flag)
            {
                num = Mathf.Atan2(dz, dx);
            }
            num = MathUtils.MinAngle(transformComp.Rotation, num);
            float num2       = (float)entity.WalkerComp.SpeedVO.RotationSpeed / 1000f;
            float smoothTime = 0.7853982f / num2;
            float num3       = (dt != 0f) ? Mathf.SmoothDampAngle(transformComp.Rotation, num, ref transformComp.RotationVelocity, smoothTime, num2, dt) : transformComp.Rotation;

            num3 = MathUtils.WrapAngle(num3);
            gameObjectViewComp.Rotate(num3 + -1.57079637f);
            transformComp.Rotation = num3;
        }
예제 #31
0
 public TransformNode(SceneNode parent, TransformComponent transform) : base(parent)
 {
     this.transform = transform;
 }
예제 #32
0
        // Init is called on startup.
        public override void Init()
        {
            // Set the clear color for the backbuffer to white (100% intentsity in all color channels R, G, B, A).
            RC.ClearColor = ColorUint.Tofloat4(ColorUint.PaleGreen);

            // Create a scene with a cube
            // The three components: one XForm, one Shader and the Mesh
            _cubeTransform = new TransformComponent {
                Scale = new float3(1, 1, 1), Translation = new float3(0, 0, 0), Rotation = new float3(0.1f, 0, 0.3f)
            };
            _cubeShader = new ShaderEffectComponent
            {
                Effect = SimpleMeshes.MakeShaderEffect(ColorUint.Tofloat3(ColorUint.Crimson), new float3(1, 1, 1), 4)
            };
            var cubeMesh = SimpleMeshes.CreateCuboid(new float3(10, 10, 10));

            // Assemble the cube node containing the three components
            var cubeNode = new SceneNodeContainer();

            cubeNode.Components = new List <SceneComponentContainer>();
            cubeNode.Components.Add(_cubeTransform);
            cubeNode.Components.Add(_cubeShader);
            cubeNode.Components.Add(cubeMesh);
// Würfel 2
            _cube2Transform = new TransformComponent {
                Scale = new float3(5, 1, 1), Translation = new float3(30, 0, 30), Rotation = new float3(0.6f, 0.6f, 0)
            };
            _cube2Shader = new ShaderEffectComponent
            {
                Effect = SimpleMeshes.MakeShaderEffect(ColorUint.Tofloat3(ColorUint.Navy), new float3(1, 1, 1), 4)
            };
            var cubeMesh2 = SimpleMeshes.CreateCuboid(new float3(5, 5, 5));

            // Assemble the cube node containing the three components
            var cubeNode2 = new SceneNodeContainer();

            cubeNode2.Components = new List <SceneComponentContainer>();
            cubeNode2.Components.Add(_cube2Transform);
            cubeNode2.Components.Add(_cube2Shader);
            cubeNode2.Components.Add(cubeMesh2);
//würfel 3
            _cube3Transform = new TransformComponent {
                Scale = new float3(1, 1, 1), Translation = new float3(18, 0, -30)
            };
            _cube3Shader = new ShaderEffectComponent
            {
                Effect = SimpleMeshes.MakeShaderEffect(ColorUint.Tofloat3(ColorUint.Lime), new float3(1, 2, 1), 4)
            };
            var cubeMesh3 = SimpleMeshes.CreateCuboid(new float3(1, 1, 1));

            // Assemble the cube node containing the three components
            var cubeNode3 = new SceneNodeContainer();

            cubeNode3.Components = new List <SceneComponentContainer>();
            cubeNode3.Components.Add(_cube3Transform);
            cubeNode3.Components.Add(_cube3Shader);
            cubeNode3.Components.Add(cubeMesh3);

            // Create the scene containing the cube as the only object
            _scene          = new SceneContainer();
            _scene.Children = new List <SceneNodeContainer>();
            _scene.Children.Add(cubeNode);
            _scene.Children.Add(cubeNode2);
            _scene.Children.Add(cubeNode3);

            // Create a scene renderer holding the scene above
            _sceneRenderer = new SceneRenderer(_scene);

            // RenderAFrame is called once a frame
        }
예제 #33
0
 protected override void DoInitialize()
 {
     this.transform = this.BindingObject.Transform;
 }
예제 #34
0
파일: aufgabe9.cs 프로젝트: DennisKokot/CG
        SceneContainer CreateScene()
        {
            // Initialize transform components that need to be changed inside "RenderAFrame"
            _baseTransform = new TransformComponent
            {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 0, 0)
            };


            //roter Arm
            _bodyTransform = new TransformComponent {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(0, 6, 0)
            };


            //grüner Arm
            _upperArmTransform = new TransformComponent {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(2, 4, 0)
            };


            //blauer Arm
            _ArmTransform = new TransformComponent {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(-3, 8, 0)
            };


            //blauer Arm
            _Arm2Transform = new TransformComponent {
                Rotation    = new float3(0, 0, 0),
                Scale       = new float3(1, 1, 1),
                Translation = new float3(3, 8, 0)
            };



            // Setup the scene graph
            return(new SceneContainer
            {
                Children = new List <SceneNodeContainer>
                {
                    new SceneNodeContainer
                    {
                        Components = new List <SceneComponentContainer>
                        {
                            // TRANSFROM COMPONENT
                            _baseTransform,



                            // MATERIAL COMPONENT
                            new MaterialComponent
                            {
                                Diffuse = new MatChannelContainer {
                                    Color = new float3(0.7f, 0.7f, 0.7f)
                                },
                                Specular = new SpecularChannelContainer {
                                    Color = new float3(1, 1, 1), Shininess = 5
                                }
                            },


                            // MESH COMPONENT
                            SimpleMeshes.CreateCuboid(new float3(10, 2, 10))
                        }
                    },



                    //Red Body
                    new SceneNodeContainer {
                        Components = new List <SceneComponentContainer> {
                            _bodyTransform,
                            new MaterialComponent {
                                Diffuse = new MatChannelContainer {
                                    Color = new float3(1, 0, 0)
                                },
                                Specular = new SpecularChannelContainer {
                                    Color = new float3(1, 1, 1), Shininess = 5
                                }
                            },
                            SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                        },

                        Children = new List <SceneNodeContainer> {
                            // GREEN UPPER ARM
                            new SceneNodeContainer
                            {
                                Components = new List <SceneComponentContainer>
                                {
                                    _upperArmTransform,
                                },
                                Children = new List <SceneNodeContainer>
                                {
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            new TransformComponent
                                            {
                                                Rotation = new float3(0, 0, 0),
                                                Scale = new float3(1, 1, 1),
                                                Translation = new float3(0, 4, 0)
                                            },
                                            new MaterialComponent
                                            {
                                                Diffuse = new MatChannelContainer {
                                                    Color = new float3(0, 1, 0)
                                                },
                                                Specular = new SpecularChannelContainer {
                                                    Color = new float3(1, 1, 1), Shininess = 5
                                                }
                                            },
                                            SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                        }
                                    },


                                    // BLUE FOREARM
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            _ArmTransform,
                                        },
                                        Children = new List <SceneNodeContainer>
                                        {
                                            new SceneNodeContainer
                                            {
                                                Components = new List <SceneComponentContainer>
                                                {
                                                    new TransformComponent
                                                    {
                                                        Rotation = new float3(0, 0, 0),
                                                        Scale = new float3(1, 1, 1),
                                                        Translation = new float3(0, 4, 0)
                                                    },
                                                    new MaterialComponent
                                                    {
                                                        Diffuse = new MatChannelContainer {
                                                            Color = new float3(0, 0, 1)
                                                        },
                                                        Specular = new SpecularChannelContainer {
                                                            Color = new float3(1, 1, 1), Shininess = 5
                                                        }
                                                    },
                                                    SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                                }
                                            }
                                        }
                                    },


                                    //arm2
                                    new SceneNodeContainer
                                    {
                                        Components = new List <SceneComponentContainer>
                                        {
                                            _Arm2Transform,
                                        },
                                        Children = new List <SceneNodeContainer>
                                        {
                                            new SceneNodeContainer
                                            {
                                                Components = new List <SceneComponentContainer>
                                                {
                                                    new TransformComponent
                                                    {
                                                        Rotation = new float3(0, 0, 0),
                                                        Scale = new float3(1, 1, 1),
                                                        Translation = new float3(0, 4, 0)
                                                    },
                                                    new MaterialComponent
                                                    {
                                                        Diffuse = new MatChannelContainer {
                                                            Color = new float3(0, 0, 1)
                                                        },
                                                        Specular = new SpecularChannelContainer {
                                                            Color = new float3(1, 1, 1), Shininess = 5
                                                        }
                                                    },
                                                    SimpleMeshes.CreateCuboid(new float3(2, 10, 2))
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                        }
                    }
                }
            });
        }
예제 #35
0
 void OnTransform(TransformComponent xform)
 {
     _model.Tos *= xform.Matrix();
     RC.ModelView = View * _model.Tos;
 }
예제 #36
0
        /// <summary>The render.</summary>
        /// <param name="spriteBatch">The sprite batch.</param>
        /// <param name="contentManager">The content manager.</param>
        /// <param name="transformComponent">The TransformComponent.</param>
        public static void Render(SpriteBatch spriteBatch, ContentManager contentManager, TransformComponent transformComponent)
        {
            if (bullet == null)
            {
                bullet = contentManager.Load <Texture2D>("bullet");
            }

            spriteBatch.Draw(bullet, new Vector2(transformComponent.X - (bullet.Width * 0.5f), transformComponent.Y - (bullet.Height * 0.5f)), bullet.Bounds, Color.White);
        }
예제 #37
0
    public static string GetEnumDescription(TransformComponent value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
예제 #38
0
        public override void Init()
        {
            // Set the clear color for the backbuffer to light green (intensities in R, G, B, A).
            RC.ClearColor  = new float4(0f, 1f, 2f, 1f);
            _cubeTransform = new TransformComponent {
                Scale = new float3(1, 1, 1), Translation = new float3(0, 0, 0)
            };

            var cubeShader = new ShaderEffectComponent
            {
                Effect = SimpleMeshes.MakeShaderEffect(ColorUint.Tofloat3(ColorUint.Beige), new float3(1, 1, 1), 4)
            };
            var cubeMesh = SimpleMeshes.CreateCuboid(new float3(10, 10, 10));


            // Assemble the cube node containing the three components
            var cubeNode = new SceneNodeContainer();

            cubeNode.Components = new List <SceneComponentContainer>();
            cubeNode.Components.Add(_cubeTransform);
            cubeNode.Components.Add(cubeShader);
            cubeNode.Components.Add(cubeMesh);

//CUBE2_________________________________________________________________________

            _cube2Transform = new TransformComponent {
                Scale = new float3(3, 3, 1), Translation = new float3(30, 0, 30), Rotation = new float3(0.1f, 0.5f, 0)
            };
            _cube2Shader = new ShaderEffectComponent
            {
                Effect = SimpleMeshes.MakeShaderEffect(ColorUint.Tofloat3(ColorUint.DarkRed), new float3(1, 1, 1), 4)
            };
            var cubeMesh2 = SimpleMeshes.CreateCuboid(new float3(5, 5, 5));

            // Assemble the cube node containing the three components
            var cubeNode2 = new SceneNodeContainer();

            cubeNode2.Components = new List <SceneComponentContainer>();
            cubeNode2.Components.Add(_cube2Transform);
            cubeNode2.Components.Add(_cube2Shader);
            cubeNode2.Components.Add(cubeMesh2);



//CUBE3_______________________________________________________________________________
            _cube3Transform = new TransformComponent {
                Scale = new float3(1, 1, 1), Translation = new float3(15, 0, -10), Rotation = new float3(-0.1f, -0.5f, 0)
            };
            _cube3Shader = new ShaderEffectComponent
            {
                Effect = SimpleMeshes.MakeShaderEffect(ColorUint.Tofloat3(ColorUint.MediumSeaGreen), new float3(1, 2, 1), 4)
            };
            var cubeMesh3 = SimpleMeshes.CreateCuboid(new float3(2, 3, 1));

            // Assemble the cube node containing the three components
            var cubeNode3 = new SceneNodeContainer();

            cubeNode3.Components = new List <SceneComponentContainer>();
            cubeNode3.Components.Add(_cube3Transform);
            cubeNode3.Components.Add(_cube3Shader);
            cubeNode3.Components.Add(cubeMesh3);

            // Create the scene containing the cube as the only object
            _scene          = new SceneContainer();
            _scene.Children = new List <SceneNodeContainer>();
            _scene.Children.Add(cubeNode);
            _scene.Children.Add(cubeNode2);
            _scene.Children.Add(cubeNode3);



            // Create a scene renderer holding the scene above
            _sceneRenderer = new SceneRenderer(_scene);
        }
예제 #39
0
 public abstract void Process(TransformComponent transformComponent);
예제 #40
0
 void OnTransform(TransformComponent xform)
 {
     _model.Tos  *= xform.Matrix();
     RC.ModelView = View * _model.Tos;
 }