Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sceneMgr"></param>
        private void SetupBody(SceneManager sceneMgr)
        {
            // create main model
            bodyNode = sceneMgr.RootSceneNode.CreateChildSceneNode(Axiom.Math.Vector3.UnitY * CharHeight);
            bodyEnt  = sceneMgr.CreateEntity("SinbadBody", "Sinbad.mesh");
            bodyNode.AttachObject(bodyEnt);

            // create swords and attach to sheath
            sword1 = sceneMgr.CreateEntity("SinbadSword1", "Sword.mesh");
            sword2 = sceneMgr.CreateEntity("SinbadSword2", "Sword.mesh");
            bodyEnt.AttachObjectToBone("Sheath.L", sword1);
            bodyEnt.AttachObjectToBone("Sheath.R", sword2);

            // create a couple of ribbon trails for the swords, just for fun
            NamedParameterList paras = new NamedParameterList();

            paras["numberOfChains"] = "2";
            paras["maxElements"]    = "80";
            swordTrail = (RibbonTrail)sceneMgr.CreateMovableObject("SinbadRibbon", "RibbonTrail", paras);
            swordTrail.MaterialName = "Examples/LightRibbonTrail";
            swordTrail.TrailLength  = 20;
            swordTrail.IsVisible    = false;
            sceneMgr.RootSceneNode.AttachObject(swordTrail);

            for (int i = 0; i < 2; i++)
            {
                swordTrail.SetInitialColor(i, new ColorEx(1, 0.8f, 0));
                swordTrail.SetColorChange(i, new ColorEx(0.75f, 0.25f, 0.25f, 0.25f));
                swordTrail.SetWidthChange(i, 1);
                swordTrail.SetInitialWidth(i, 0.5f);
            }

            keyDirection     = Axiom.Math.Vector3.Zero;
            verticalVelocity = 0;
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="deltaTime"></param>
        private void UpdateBody(Real deltaTime)
        {
            // we will calculate this
            goalDirection = Axiom.Math.Vector3.Zero;

            if (keyDirection != Axiom.Math.Vector3.Zero && baseAnimID != AnimationID.Dance)
            {
                // calculate actually goal direction in world based on player's key directions
                goalDirection  += keyDirection.z * cameraNode.Orientation.ZAxis;
                goalDirection  += keyDirection.x * cameraNode.Orientation.XAxis;
                goalDirection.y = 0;
                goalDirection.Normalize();

                Quaternion toGoal = bodyNode.Orientation.ZAxis.GetRotationTo(goalDirection);
                // calculate how much the character has to turn to face goal direction
                Real yawToGlobal = toGoal.Yaw;
                // this is how much the character CAN turn this frame
                Real yawAtSpeed = yawToGlobal / Utility.Abs(yawToGlobal) * deltaTime * TurnSpeed;
                // reduce "turnability" if we're in midair
                if (baseAnimID == AnimationID.JumpLoop)
                {
                    yawAtSpeed *= 0.2;
                }

                // turn as much as we can, but not more than we need to
                if (yawToGlobal < 0)
                {
                    yawToGlobal = Utility.Min <Real>(yawToGlobal, yawAtSpeed);
                }
                else if (yawToGlobal > 0)
                {
                    yawToGlobal = Utility.Max <Real>(0, Utility.Min <Real>(yawToGlobal, yawAtSpeed));
                }

                bodyNode.Yaw(yawToGlobal);

                // move in current body direction (not the goal direction)
                bodyNode.Translate(new Axiom.Math.Vector3(0, 0, deltaTime * RunSpeed * anims[(int)baseAnimID].Weight), TransformSpace.Local);
            }

            if (baseAnimID == AnimationID.JumpLoop)
            {
                // if we're jumping, add a vertical offset too, and apply gravity
                bodyNode.Translate(new Axiom.Math.Vector3(0, verticalVelocity * deltaTime, 0), TransformSpace.Local);
                verticalVelocity -= Gravity * deltaTime;

                Axiom.Math.Vector3 pos = bodyNode.Position;
                if (pos.y <= CharHeight)
                {
                    // if we've hit the ground, change to landing state
                    pos.y             = CharHeight;
                    bodyNode.Position = pos;
                    SetBaseAnimation(AnimationID.JumpEnd, true);
                    timer = 0;
                }
            }
        }
Exemplo n.º 3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="deltaTime"></param>
 private void UpdateCamera(Real deltaTime)
 {
     // place the camera pivot roughly at the character's shoulder
     cameraPivot.Position = bodyNode.Position + Axiom.Math.Vector3.UnitY * CamHeight;
     // move the camera smoothly to the goal
     Axiom.Math.Vector3 goalOffset = cameraGoal.DerivedPosition - cameraNode.Position;
     cameraNode.Translate(goalOffset * deltaTime * 9.0f);
     // always look at the pivot
     cameraNode.LookAt(cameraPivot.DerivedPosition, TransformSpace.World);
 }
Exemplo n.º 4
0
		/// <summary>
		/// 
		/// </summary>
		public TerrainSample()
		{
			Metadata[ "Title" ] = "Terrain";
			Metadata[ "Description" ] = "Demonstrates use of the terrain rendering plugin.";
			Metadata[ "Thumbnail" ] = "thumb_terrain.png";
			Metadata[ "Category" ] = "Environment";
			Metadata[ "Help" ] = "Left click and drag anywhere in the scene to look around. Let go again to show " +
			"cursor and access widgets. Use WASD keys to move. Use +/- keys when in edit mode to change content.";

			mode = Mode.Normal;
			layerEdit = 1;
			brushSizeTerrainSpace = 0.02f;
			terrainPos = new Vector3( 1000, 0, 5000 );

			// Update terrain at max 20fps
			heightUpdateRate = 1.0f / 2.0f;
		}
Exemplo n.º 5
0
		public Triangle( Vector3 v1, Vector3 v2, Vector3 v3, ColorEx c1, ColorEx c2, ColorEx c3 )
		{
			vertexData = new VertexData();
			renderOperation.vertexData = vertexData;
			renderOperation.vertexData.vertexCount = 3;
			renderOperation.vertexData.vertexStart = 0;
			renderOperation.indexData = null;
			renderOperation.operationType = OperationType.TriangleList;
			renderOperation.useIndices = false;

			var decl = vertexData.vertexDeclaration;
			var binding = vertexData.vertexBufferBinding;

			// add a position and color element to the declaration
			decl.AddElement( POSITION, 0, VertexElementType.Float3, VertexElementSemantic.Position );
			decl.AddElement( COLOR, 0, VertexElementType.Color, VertexElementSemantic.Diffuse );

			// POSITIONS
			// create a vertex buffer for the position
			var buffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.Clone( POSITION ), vertexData.vertexCount,
			                                                                BufferUsage.StaticWriteOnly );

			var positions = new Vector3[]
			                {
			                	v1, v2, v3
			                };

			// write the positions to the buffer
			buffer.WriteData( 0, buffer.Size, positions, true );

			// bind the position buffer
			binding.SetBinding( POSITION, buffer );

			// COLORS
			// create a color buffer
			buffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.Clone( COLOR ), vertexData.vertexCount,
			                                                            BufferUsage.StaticWriteOnly );

			// create an int array of the colors to use.
			// note: these must be converted to the current API's
			// preferred packed int format
			var colors = new int[]
			             {
			             	Root.Instance.RenderSystem.ConvertColor( c1 ), Root.Instance.RenderSystem.ConvertColor( c2 ),
			             	Root.Instance.RenderSystem.ConvertColor( c3 )
			             };

			// write the colors to the color buffer
			buffer.WriteData( 0, buffer.Size, colors, true );

			// bind the color buffer
			binding.SetBinding( COLOR, buffer );

			// MATERIAL
			// grab a copy of the BaseWhite material for our use
			var material = (Material)MaterialManager.Instance.GetByName( "BaseWhite" );
			material = material.Clone( "TriMat" );

			// disable lighting to vertex colors are used
			material.Lighting = false;
			// set culling to none so the triangle is drawn 2 sided
			material.CullingMode = CullingMode.None;

			Material = material;

			// set the bounding box of the tri
			// TODO: not right, but good enough for now
			box = new AxisAlignedBox( new Vector3( 25, 50, 0 ), new Vector3( -25, 0, 0 ) );
		}
Exemplo n.º 6
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="sceneMgr"></param>
		private void SetupBody( SceneManager sceneMgr )
		{
			// create main model
			bodyNode = sceneMgr.RootSceneNode.CreateChildSceneNode( Vector3.UnitY * CharHeight );
			bodyEnt = sceneMgr.CreateEntity( "SinbadBody", "Sinbad.mesh" );
			bodyNode.AttachObject( bodyEnt );

			// create swords and attach to sheath
			sword1 = sceneMgr.CreateEntity( "SinbadSword1", "Sword.mesh" );
			sword2 = sceneMgr.CreateEntity( "SinbadSword2", "Sword.mesh" );
			bodyEnt.AttachObjectToBone( "Sheath.L", sword1 );
			bodyEnt.AttachObjectToBone( "Sheath.R", sword2 );

			// create a couple of ribbon trails for the swords, just for fun
			NamedParameterList paras = new NamedParameterList();
			paras[ "numberOfChains" ] = "2";
			paras[ "maxElements" ] = "80";
			swordTrail = (RibbonTrail)sceneMgr.CreateMovableObject( "SinbadRibbon", "RibbonTrail", paras );
			swordTrail.MaterialName = "Examples/LightRibbonTrail";
			swordTrail.TrailLength = 20;
			swordTrail.IsVisible = false;
			sceneMgr.RootSceneNode.AttachObject( swordTrail );

			for ( int i = 0; i < 2; i++ )
			{
				swordTrail.SetInitialColor( i, new ColorEx( 1, 0.8f, 0 ) );
				swordTrail.SetColorChange( i, new ColorEx( 0.75f, 0.25f, 0.25f, 0.25f ) );
				swordTrail.SetWidthChange( i, 1 );
				swordTrail.SetInitialWidth( i, 0.5f );
			}

			keyDirection = Vector3.Zero;
			verticalVelocity = 0;

		}
Exemplo n.º 7
0
 /// <summary>
 ///		Construct a plane through a normal, and a distance to move the plane along the normal.
 /// </summary>
 /// <param name="normal"></param>
 /// <param name="constant"></param>
 public Plane( Vector3 normal, Real constant )
 {
     this.Normal = normal;
     this.D = -constant;
 }
Exemplo n.º 8
0
 /// <summary>
 ///		Construct a plane from 3 coplanar points.
 /// </summary>
 /// <param name="point0">First point.</param>
 /// <param name="point1">Second point.</param>
 /// <param name="point2">Third point.</param>
 public void Redefine( Vector3 point0, Vector3 point1, Vector3 point2 )
 {
     Vector3 edge1 = point1 - point0;
     Vector3 edge2 = point2 - point0;
     this.Normal = edge1.Cross( edge2 );
     this.Normal.Normalize();
     this.D = -this.Normal.Dot( point0 );
 }
Exemplo n.º 9
0
        /// <summary>
        ///     Project a point onto the plane.
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public Vector3 ProjectVector( Vector3 point )
        {
            // We know plane normal is unit length, so use simple method
            Matrix3 xform;

            xform.m00 = 1.0f - this.Normal.x * this.Normal.x;
            xform.m01 = -this.Normal.x * this.Normal.y;
            xform.m02 = -this.Normal.x * this.Normal.z;
            xform.m10 = -this.Normal.y * this.Normal.x;
            xform.m11 = 1.0f - this.Normal.y * this.Normal.y;
            xform.m12 = -this.Normal.y * this.Normal.z;
            xform.m20 = -this.Normal.z * this.Normal.x;
            xform.m21 = -this.Normal.z * this.Normal.y;
            xform.m22 = 1.0f - this.Normal.z * this.Normal.z;

            return xform * point;
        }
Exemplo n.º 10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public PlaneSide GetSide( Vector3 point )
        {
            Real distance = this.GetDistance( point );

            if( distance < 0.0f )
            {
                return PlaneSide.Negative;
            }

            if( distance > 0.0f )
            {
                return PlaneSide.Positive;
            }

            return PlaneSide.None;
        }
Exemplo n.º 11
0
		// set the origin value
		public void SetOrigin( Vector3 newOrigin )
		{
			mOrigin = newOrigin;
		}
Exemplo n.º 12
0
		protected override void SetupContent()
		{
			var blankTerrain = false;

			this.editMarker = SceneManager.CreateEntity( "editMarker", "sphere.mesh" );
			this.editNode = SceneManager.RootSceneNode.CreateChildSceneNode();
			this.editNode.AttachObject( this.editMarker );
			this.editNode.Scale = new Vector3( 0.05f, 0.05f, 0.05f );

			_setupControls();

			CameraManager.TopSpeed = 50;

			DragLook = true;

			MaterialManager.Instance.SetDefaultTextureFiltering( TextureFiltering.Anisotropic );
			MaterialManager.Instance.DefaultAnisotropy = 7;

			SceneManager.SetFog( FogMode.Linear, new ColorEx( 0.07f, 0.07f, 0.08f ), 0, 10000, 25000 );

			var lightDir = new Vector3( 0.55f, 0.3f, 0.75f );
			lightDir.Normalize();

			var l = SceneManager.CreateLight( "tsLight" );
			l.Type = LightType.Directional;
			l.Direction = lightDir;
			l.Diffuse = ColorEx.White;
			l.Specular = new ColorEx( 0.4f, 0.4f, 0.4f );

			SceneManager.AmbientLight = new ColorEx( 0.2f, 0.2f, 0.2f );

			this.terrainGroup = new TerrainGroup( SceneManager, Alignment.Align_X_Z, (ushort)TerrainSize, TerrainWorldSize );
			this.terrainGroup.SetFilenameConvention( TerrainFilePrefix, TerrainFileSuffix );
			this.terrainGroup.Origin = this.terrainPos;

			_configureTerrainDefaults( l );
#if PAGING
	// Paging setup
            pageManager = new PageManager();
            // Since we're not loading any pages from .page files, we need a way just 
            // to say we've loaded them without them actually being loaded
            pageManager.PageProvider = dummyPageProvider;
            pageManager.AddCamera( Camera );
            terrainPaging = new TerrainPaging( pageManager );
            PagedWorld world = pageManager.CreateWorld();
            terrainPaging.CreateWorldSection( world, terrainGroup, 2000, 3000,
                TerrainPageMinX, TerrainPageMinY,
                TerrainPageMaxX, TerrainPageMaxY );
#else
			for ( long x = TerrainPageMinX; x <= TerrainPageMaxX; ++x )
			{
				for ( long y = TerrainPageMinY; y <= TerrainPageMaxY; ++y )
				{
					_defineTerrain( x, y, blankTerrain );
				}
			}
			// sync load since we want everything in place when we start
			this.terrainGroup.LoadAllTerrains( true );
#endif

			if ( this.terrainsImported )
			{
				foreach ( var ts in this.terrainGroup.TerrainSlots )
				{
					_initBlendMaps( ts.Instance );
				}
			}

			this.terrainGroup.FreeTemporaryResources();

			var e = SceneManager.CreateEntity( "TudoMesh", "tudorhouse.mesh" );
			var entPos = new Vector3( this.terrainPos.x + 2043, 0, this.terrainPos.z + 1715 );
			var rot = new Quaternion();
			entPos.y = this.terrainGroup.GetHeightAtWorldPosition( entPos ) + 65.5 + this.terrainPos.y;
			rot = Quaternion.FromAngleAxis( Utility.RangeRandom( -180, 180 ), Vector3.UnitY );
			var sn = SceneManager.RootSceneNode.CreateChildSceneNode( entPos, rot );
			sn.Scale = new Vector3( 0.12, 0.12, 0.12 );
			sn.AttachObject( e );
			this.houseList.Add( e );

			e = SceneManager.CreateEntity( "TudoMesh1", "tudorhouse.mesh" );
			entPos = new Vector3( this.terrainPos.x + 1850, 0, this.terrainPos.z + 1478 );
			entPos.y = this.terrainGroup.GetHeightAtWorldPosition( entPos ) + 65.5 + this.terrainPos.y;
			rot = Quaternion.FromAngleAxis( Utility.RangeRandom( -180, 180 ), Vector3.UnitY );
			sn = SceneManager.RootSceneNode.CreateChildSceneNode( entPos, rot );
			sn.Scale = new Vector3( 0.12, 0.12, 0.12 );
			sn.AttachObject( e );
			this.houseList.Add( e );

			e = SceneManager.CreateEntity( "TudoMesh2", "tudorhouse.mesh" );
			entPos = new Vector3( this.terrainPos.x + 1970, 0, this.terrainPos.z + 2180 );
			entPos.y = this.terrainGroup.GetHeightAtWorldPosition( entPos ) + 65.5 + this.terrainPos.y;
			rot = Quaternion.FromAngleAxis( Utility.RangeRandom( -180, 180 ), Vector3.UnitY );
			sn = SceneManager.RootSceneNode.CreateChildSceneNode( entPos, rot );
			sn.Scale = new Vector3( 0.12, 0.12, 0.12 );
			sn.AttachObject( e );
			this.houseList.Add( e );

			//SceneManager.SetSkyDome( true, "Examples/CloudyNoonSkyBox", 5000, 8 );
			SceneManager.SetSkyDome( true, "Examples/CloudySky", 5000, 8 );
		}
Exemplo n.º 13
0
		/// <summary>
		///
		/// </summary>
		/// <param name="startPoint">Point where the line will start.</param>
		/// <param name="direction">The direction the vector is heading in.</param>
		/// <param name="length">The length (magnitude) of the line vector.</param>
		/// <param name="color">The color which this line should be.</param>
		public Line3d( Vector3 startPoint, Vector3 direction, float length, ColorEx color )
		{
			// normalize the direction vector to ensure all elements fall in [0,1] range.
			direction.Normalize();

			// calculate the actual endpoint
			var endPoint = startPoint + ( direction*length );

			vertexData = new VertexData();
			renderOperation.vertexData = vertexData;
			renderOperation.vertexData.vertexCount = 2;
			renderOperation.vertexData.vertexStart = 0;
			renderOperation.indexData = null;
			renderOperation.operationType = OperationType.LineList;
			renderOperation.useIndices = false;

			var decl = vertexData.vertexDeclaration;
			var binding = vertexData.vertexBufferBinding;

			// add a position and color element to the declaration
			decl.AddElement( POSITION, 0, VertexElementType.Float3, VertexElementSemantic.Position );
			decl.AddElement( COLOR, 0, VertexElementType.Color, VertexElementSemantic.Diffuse );

			// create a vertex buffer for the position
			var buffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.Clone( POSITION ), vertexData.vertexCount,
			                                                                BufferUsage.StaticWriteOnly );
			var pos = new Vector3[]
			          {
			          	startPoint, endPoint
			          };

			// write the data to the position buffer
			buffer.WriteData( 0, buffer.Size, pos, true );

			// bind the position buffer
			binding.SetBinding( POSITION, buffer );

			// create a color buffer
			buffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.Clone( COLOR ), vertexData.vertexCount,
			                                                            BufferUsage.StaticWriteOnly );

			var colorValue = Root.Instance.RenderSystem.ConvertColor( color );

			var colors = new int[]
			             {
			             	colorValue, colorValue
			             };

			// write the data to the position buffer
			buffer.WriteData( 0, buffer.Size, colors, true );

			// bind the color buffer
			binding.SetBinding( COLOR, buffer );

			// MATERIAL
			// grab a copy of the BaseWhite material for our use
			var material = (Material)MaterialManager.Instance.GetByName( "BaseWhite" );
			material = material.Clone( "LineMat" );
			// disable lighting to vertex colors are used
			material.Lighting = false;
			// set culling to none so the triangle is drawn 2 sided
			material.CullingMode = CullingMode.None;

			Material = material;

			// set the bounding box of the line
			box = new AxisAlignedBox( startPoint, endPoint );
		}
Exemplo n.º 14
0
		public virtual bool frameRenderingQueued( FrameEventArgs evt )
		{
			if ( mStyle == CameraStyle.FreeLook )
			{
				// build our acceleration vector based on keyboard input composite
				Vector3 accel = Vector3.Zero;
				if ( mGoingForward )
					accel += mCamera.Direction;
				if ( mGoingBack )
					accel -= mCamera.Direction;
				if ( mGoingRight )
					accel += mCamera.Right;
				if ( mGoingLeft )
					accel -= mCamera.Right;
				if ( mGoingUp )
					accel += mCamera.Up;
				if ( mGoingDown )
					accel -= mCamera.Up;

				// if accelerating, try to reach top speed in a certain time
				if ( accel.LengthSquared != 0 )
				{
					accel.Normalize();
					mVelocity += accel * TopSpeed * evt.TimeSinceLastFrame * 10;
				}
				// if not accelerating, try to stop in a certain time
				else
					mVelocity -= mVelocity * evt.TimeSinceLastFrame * 10;

				// keep camera velocity below top speed and above zero
				if ( mVelocity.LengthSquared > TopSpeed * TopSpeed )
				{
					mVelocity.Normalize();
					mVelocity *= TopSpeed;
				}
				else if ( mVelocity.LengthSquared < 0.1 )
					mVelocity = Vector3.Zero;

				if ( mVelocity != Vector3.Zero )
					mCamera.Move( mVelocity * evt.TimeSinceLastFrame );
			}

			return true;
		}
Exemplo n.º 15
0
		/*-----------------------------------------------------------------------------
		| Manually stops the camera when in free-look mode.
		-----------------------------------------------------------------------------*/
		public virtual void manualStop()
		{
			if ( mStyle == CameraStyle.FreeLook )
			{
				mGoingForward = false;
				mGoingBack = false;
				mGoingLeft = false;
				mGoingRight = false;
				mGoingUp = false;
				mGoingDown = false;
				mVelocity = Vector3.Zero;
			}
		}
Exemplo n.º 16
0
		public SdkCameraManager( Camera cam )
		{
			mTarget = null;
			mOrbiting = false;
			mZooming = false;
			mCamera = null;
			TopSpeed = 150;
			mGoingForward = false;
			mGoingBack = false;
			mGoingLeft = false;
			mGoingRight = false;
			mGoingUp = false;
			mGoingDown = false;
			mVelocity = Vector3.Zero;

			Camera = cam;
			setStyle( CameraStyle.FreeLook );
		}
Exemplo n.º 17
0
		//----------------------------------------------------------------------------
		public void Set( Vector3 newOrigin, Vector3 newEnd )
		{
			Origin = newOrigin;
			// calc the direction vector
			Direction = newEnd - Origin;
			Extent = Direction.Normalize();
		}
Exemplo n.º 18
0
		// set the origin plane
		public void SetOriginPlane( Vector3 rkNormal, Vector3 rkPoint )
		{
			mOriginPlane.Redefine( rkNormal, rkPoint );
		}
Exemplo n.º 19
0
		/// <summary>
		/// 
		/// </summary>
		protected void Initialize()
		{
			Vector3 ax = Vector3.Zero, ay = Vector3.Zero, az = Vector3.Zero;
			int x = 0;
			Quaternion q = Quaternion.Identity;
			this.things.Clear();
			this.orbits.Clear();

			for ( x = 0; x < this.count; x++ )
			{
				ax = new Vector3( GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat() );
				ay = new Vector3( GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat() );
				az = ax.Cross( ay );
				ay = az.Cross( ax );
				ax.Normalize();
				ay.Normalize();
				az.Normalize();
				q = Quaternion.FromAxes( ax, ay, az );
				this.things.Add( q );

				ax = new Vector3( GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat() );
				ay = new Vector3( GenerateRandomFloat(), GenerateRandomFloat(), GenerateRandomFloat() );
				az = ax.Cross( ay );
				ay = az.Cross( ax );
				ax.Normalize();
				ay.Normalize();
				az.Normalize();
				q = Quaternion.FromAxes( ax, ay, az );
				this.orbits.Add( q );
			}

			int nVertices = this.count*4;

			var indexData = new IndexData();
			var vertexData = new VertexData();

			//Quads
			var faces = new short[this.count*6];
			for ( x = 0; x < this.count; x++ )
			{
				faces[ x*6 + 0 ] = (short)( x*4 + 0 );
				faces[ x*6 + 1 ] = (short)( x*4 + 1 );
				faces[ x*6 + 2 ] = (short)( x*4 + 2 );
				faces[ x*6 + 3 ] = (short)( x*4 + 0 );
				faces[ x*6 + 4 ] = (short)( x*4 + 2 );
				faces[ x*6 + 5 ] = (short)( x*4 + 3 );
			}

			vertexData.vertexStart = 0;
			vertexData.vertexCount = nVertices;

			VertexDeclaration decl = vertexData.vertexDeclaration;
			VertexBufferBinding bind = vertexData.vertexBufferBinding;

			int offset = 0;
			offset += decl.AddElement( 0, offset, VertexElementType.Float3, VertexElementSemantic.Position ).Size;

			this.vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer( decl.Clone( 0 ), nVertices,
			                                                                       BufferUsage.DynamicWriteOnly );

			bind.SetBinding( 0, this.vertexBuffer );

			HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer( IndexType.Size16, this.count*6,
			                                                                                    BufferUsage.StaticWriteOnly );
			indexData.indexBuffer = indexBuffer;
			indexData.indexStart = 0;
			indexData.indexCount = this.count*6;

			indexBuffer.WriteData( 0, indexBuffer.Size, faces, true );

			faces = null;

			renderOperation.operationType = OperationType.TriangleList;
			renderOperation.indexData = indexData;
			renderOperation.vertexData = vertexData;
			renderOperation.useIndices = true;
		}
Exemplo n.º 20
0
		/// <summary>
		/// 
		/// </summary>
		protected override void SetupContent()
		{
			bool blankTerrain = false;

			//editMarker = SceneManager.CreateEntity( "editMarker", "sphere.mesh" );
			//editNode = SceneManager.RootSceneNode.CreateChildSceneNode();
			//editNode.AttachObject( editMarker );
			//editNode.Scale = new Vector3( 0.05f, 0.05f, 0.05f );

			SetupControls();

			CameraManager.TopSpeed = 50;

			DragLook = true;

			MaterialManager.Instance.SetDefaultTextureFiltering( TextureFiltering.Anisotropic );
			MaterialManager.Instance.DefaultAnisotropy = 7;

			SceneManager.SetFog( FogMode.Linear, new ColorEx( 0.07f, 0.07f, 0.08f ), 0, 10000, 25000 );

			Vector3 lightDir = new Vector3( 0.55f, 0.3f, 0.75f );
			lightDir.Normalize();

			Light l = SceneManager.CreateLight( "tsLight" );
			l.Type = LightType.Directional;
			l.Direction = lightDir;
			l.Diffuse = ColorEx.White;
			l.Specular = new ColorEx( 0.4f, 0.4f, 0.4f );

			SceneManager.AmbientLight = new ColorEx( 0.8f, 0.8f, 0.8f );

			terrainGroup = new TerrainGroup( SceneManager, Alignment.Align_X_Z, (ushort)TerrainSize, TerrainWorldSize );
			terrainGroup.SetFilenamConvention( TerrainFilePrefix, TerrainFileSuffix );
			terrainGroup.Origin = Vector3.Zero;
			
			Axiom.Components.Terrain.Terrain terrain = new Components.Terrain.Terrain( SceneManager );
			terrain.Position = terrainPos;
			ImportData data  = ConfigureTerrainDefaults( l );

			for ( long x = TerrainPageMinX; x <= TerrainPageMaxX; x++ )
			{
				for ( long y = TerrainPageMinY; y <= TerrainPageMaxY; y++ )
				{
					DefineTerrain( x, y, false );
				}
			}
			// sync load since we want everything in place when we start
			terrainGroup.LoadAllTerrains( true );

			if ( terrainsImported)
			{
				Axiom.Components.Terrain.Terrain t = terrainGroup.GetTerrain( 0, 0 );
				InitBlendMaps( t );
			}

			//Entity e = SceneManager.CreateEntity( "TudoMesh", "tudorhouse.mesh" );
			//Vector3 entPos = new Vector3( terrainPos.x + 2043, 0, terrainPos.z + 1715 );
			//Quaternion rot = new Quaternion();
			//entPos.y = terrainGroup.GetTerrain(0,0).GetHeightAtWorldPosition( entPos ) + 65.5f + terrainPos.y;
			//rot = Quaternion.FromAngleAxis( Utility.RangeRandom( -180, 180 ), Vector3.UnitY );
			//SceneNode sn = SceneManager.RootSceneNode.CreateChildSceneNode( entPos, rot );
			//sn.Scale = new Vector3( 0.12, 0.12, 0.12 );
			//sn.AttachObject( e );
			//Camera.Position = entPos;
			terrainGroup.FreeTemporaryResources();
			SceneManager.SetSkyDome( true, "Examples/CloudySky", 5, 8 );
			//SceneManager.SetSkyBox( true, "Examples/CloudyNoonSkyBox" , 5000);
		}
Exemplo n.º 21
0
		public virtual PageID GetPageID( Vector3 worldPos )
		{
			return this.mStrategy.GetPageID( worldPos, this );
		}
Exemplo n.º 22
0
 /// <summary>
 /// This is a pseudodistance. The sign of the return value is
 /// positive if the point is on the positive side of the plane,
 /// negative if the point is on the negative side, and zero if the
 ///	 point is on the plane.
 /// The absolute value of the return value is the true distance only
 /// when the plane normal is a unit length vector.
 /// </summary>
 /// <param name="point"></param>
 /// <returns></returns>
 public Real GetDistance( Vector3 point )
 {
     return this.Normal.Dot( point ) + this.D;
 }
Exemplo n.º 23
0
		public virtual Page LoadOrCreatePage( Vector3 worldPos )
		{
			PageID id = GetPageID( worldPos );
			// this will create a Page instance no matter what, even if load fails
			// we force the load attempt to happen immediately (forceSynchronous)
			LoadPage( id, true );
			return GetPage( id );
		}
Exemplo n.º 24
0
        /// <summary>
        ///     Returns which side of the plane that the given box lies on.
        ///     The box is defined as centre/half-size pairs for effectively.
        /// </summary>
        /// <param name="centre">The centre of the box.</param>
        /// <param name="halfSize">The half-size of the box.</param>
        /// <returns>
        ///     Positive if the box complete lies on the "positive side" of the plane,
        ///     Negative if the box complete lies on the "negative side" of the plane,
        ///     and Both if the box intersects the plane.
        /// </returns>
        public PlaneSide GetSide( Vector3 centre, Vector3 halfSize )
        {
            // Calculate the distance between box centre and the plane
            Real dist = this.GetDistance( centre );

            // Calculate the maximise allows absolute distance for
            // the distance between box centre and plane
            Real maxAbsDist = this.Normal.AbsDot( halfSize );

            if( dist < -maxAbsDist )
            {
                return PlaneSide.Negative;
            }

            if( dist > +maxAbsDist )
            {
                return PlaneSide.Positive;
            }

            return PlaneSide.Both;
        }
Exemplo n.º 25
0
		/// <summary>
		/// Default Costructor
		/// </summary>
		public DeflectorPlaneAffector()
		{
			this.type = "DeflectorPlane";

			// defaults
			_planePoint = Vector3.Zero;
			_planeNormal = Vector3.UnitY;
			_bounce = 1.0f;
		}
Exemplo n.º 26
0
 /// <summary>
 /// Redefine this plane based on a normal and a point.
 /// </summary>
 /// <param name="rkNormal">Normal vector</param>
 /// <param name="rkPoint">Point vector</param>
 public void Redefine( Vector3 rkNormal, Vector3 rkPoint )
 {
     this.Normal = rkNormal;
     this.D = -rkNormal.Dot( rkPoint );
 }
Exemplo n.º 27
0
		private static void _createSphere( Mesh mesh )
		{
			// sphere creation code taken from the DeferredShading sample, originally from the [Ogre] wiki
			var pSphereVertex = mesh.CreateSubMesh();

			const int NUM_SEGMENTS = 16;
			const int NUM_RINGS = 16;
			const float SPHERE_RADIUS = 50.0f;

			mesh.SharedVertexData = new VertexData();
			var vertexData = mesh.SharedVertexData;

			// define the vertex format
			var vertexDecl = vertexData.vertexDeclaration;
			var offset = 0;
			// positions
			vertexDecl.AddElement( 0, offset, VertexElementType.Float3, VertexElementSemantic.Position );
			offset += VertexElement.GetTypeSize( VertexElementType.Float3 );
			// normals
			vertexDecl.AddElement( 0, offset, VertexElementType.Float3, VertexElementSemantic.Normal );
			offset += VertexElement.GetTypeSize( VertexElementType.Float3 );
			// two dimensional texture coordinates
			vertexDecl.AddElement( 0, offset, VertexElementType.Float2, VertexElementSemantic.TexCoords, 0 );
			offset += VertexElement.GetTypeSize( VertexElementType.Float2 );

			// allocate the vertex buffer
			vertexData.vertexCount = ( NUM_RINGS + 1 )*( NUM_SEGMENTS + 1 );

			var vBuf = HardwareBufferManager.Instance.CreateVertexBuffer( vertexDecl.Clone( 0 ), vertexData.vertexCount,
			                                                              BufferUsage.StaticWriteOnly, false );

			var binding = vertexData.vertexBufferBinding;
			binding.SetBinding( 0, vBuf );

			// allocate index buffer
			pSphereVertex.IndexData.indexCount = 6*NUM_RINGS*( NUM_SEGMENTS + 1 );

			pSphereVertex.IndexData.indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer( IndexType.Size16,
			                                                                                        pSphereVertex.IndexData.
			                                                                                        	indexCount,
			                                                                                        BufferUsage.StaticWriteOnly,
			                                                                                        false );
			var iBuf = pSphereVertex.IndexData.indexBuffer;

#if !AXIOM_SAFE_ONLY
			unsafe
#endif
			{
				var iVertex = 0;
				var pVertex = vBuf.Lock( BufferLocking.Discard ).ToFloatPointer();
				var iIndices = 0;
				var pIndices = iBuf.Lock( BufferLocking.Discard ).ToUShortPointer();

				float fDeltaRingAngle = ( Utility.PI/NUM_RINGS );
				float fDeltaSegAngle = ( 2*Utility.PI/NUM_SEGMENTS );
				ushort wVerticeIndex = 0;

				// Generate the group of rings for the sphere
				for ( var ring = 0; ring <= NUM_RINGS; ring++ )
				{
					float r0 = SPHERE_RADIUS*Utility.Sin( ring*fDeltaRingAngle );
					float y0 = SPHERE_RADIUS*Utility.Cos( ring*fDeltaRingAngle );

					// Generate the group of segments for the current ring
					for ( var seg = 0; seg <= NUM_SEGMENTS; seg++ )
					{
						float x0 = r0*Utility.Sin( seg*fDeltaSegAngle );
						float z0 = r0*Utility.Cos( seg*fDeltaSegAngle );

						// Add one vertex to the strip which makes up the sphere
						pVertex[ iVertex++ ] = x0;
						pVertex[ iVertex++ ] = y0;
						pVertex[ iVertex++ ] = z0;

						var vNormal = new Vector3( x0, y0, z0 ).ToNormalized();
						pVertex[ iVertex++ ] = vNormal.x;
						pVertex[ iVertex++ ] = vNormal.y;
						pVertex[ iVertex++ ] = vNormal.z;

						pVertex[ iVertex++ ] = (float)seg/(float)NUM_SEGMENTS;
						pVertex[ iVertex++ ] = (float)ring/(float)NUM_RINGS;

						if ( ring != NUM_RINGS )
						{
							// each vertex (except the last) has six indicies pointing to it
							pIndices[ iIndices++ ] = (ushort)( wVerticeIndex + NUM_SEGMENTS + 1 );
							pIndices[ iIndices++ ] = (ushort)( wVerticeIndex );
							pIndices[ iIndices++ ] = (ushort)( wVerticeIndex + NUM_SEGMENTS );
							pIndices[ iIndices++ ] = (ushort)( wVerticeIndex + NUM_SEGMENTS + 1 );
							pIndices[ iIndices++ ] = (ushort)( wVerticeIndex + 1 );
							pIndices[ iIndices++ ] = (ushort)( wVerticeIndex );
							wVerticeIndex++;
						}
					}
					; // end for seg
				} // end for ring
			}

			// Unlock
			vBuf.Unlock();
			iBuf.Unlock();

			// Generate face list
			pSphereVertex.useSharedVertices = true;

			// the original code was missing this line:
			mesh.BoundingBox = new AxisAlignedBox( new Vector3( -SPHERE_RADIUS, -SPHERE_RADIUS, -SPHERE_RADIUS ),
			                                       new Vector3( SPHERE_RADIUS, SPHERE_RADIUS, SPHERE_RADIUS ) );

			mesh.BoundingSphereRadius = SPHERE_RADIUS;
		}
Exemplo n.º 28
0
 //public Plane()
 //{
 //    this.Normal = Vector3.Zero;
 //    this.D = Real.NaN;
 //}
 public Plane( Plane plane )
 {
     this.Normal = plane.Normal;
     this.D = plane.D;
 }
Exemplo n.º 29
0
		/// <summary>
		/// Default Costructor
		/// </summary>
		public DeflectorPlaneAffector( ParticleSystem psys )
			: base( psys )
		{
			type = "DeflectorPlane";

			// defaults
			this._planePoint = Vector3.Zero;
			this._planeNormal = Vector3.UnitY;
			this._bounce = 1.0f;
		}
Exemplo n.º 30
0
 public Plane( Vector3 normal, Vector3 point )
 {
     this.Normal = normal;
     this.D = -normal.Dot( point );
 }
Exemplo n.º 31
0
		public override void CreateScene()
		{
			// Register Compositor Logics
			CompositorManager.Instance.RegisterCompositorLogic( "HDR", new HdrLogic() );

			scene.ShadowTechnique = ShadowTechnique.TextureModulative;
			scene.ShadowFarDistance = 1000;

			scene.AmbientLight = new ColorEx( 0.3f, 0.3f, 0.2f );

			Light light = scene.CreateLight( "Light2" );
			Vector3 dir = new Vector3( -1, -1, 0 );
			dir.Normalize();
			light.Type = LightType.Directional;
			light.Direction = dir;
			light.Diffuse = new ColorEx( 1.0f, 1.0f, 0.8f );
			light.Specular = new ColorEx( 1.0f, 1.0f, 1.0f );

			Entity entity;

			// House
			entity = scene.CreateEntity( "1", "tudorhouse.mesh" );
			SceneNode n1 = scene.RootSceneNode.CreateChildSceneNode( new Vector3( 350, 450, -200 ) );
			n1.AttachObject( entity );

			entity = scene.CreateEntity( "2", "tudorhouse.mesh" );
			SceneNode n2 = scene.RootSceneNode.CreateChildSceneNode( new Vector3( -350, 450, -200 ) );
			n2.AttachObject( entity );

			entity = scene.CreateEntity( "3", "knot.mesh" );
			_spinny = scene.RootSceneNode.CreateChildSceneNode( new Vector3( 0, 0, 300 ) );
			_spinny.AttachObject( entity );
			entity.MaterialName = "Examples/MorningCubeMap";

			scene.SetSkyBox( true, "Examples/MorningSkyBox", 50 );

			Plane plane = new Plane();
			plane.Normal = Vector3.UnitY;
			plane.D = 100;
			MeshManager.Instance.CreatePlane( "Myplane", ResourceGroupManager.DefaultResourceGroupName, plane, 1500, 1500, 10, 10, true, 1, 5, 5, Vector3.UnitZ );
			Entity planeEntity = scene.CreateEntity( "plane", "Myplane" );
			planeEntity.MaterialName = "Examples/Rockwall";
			planeEntity.CastShadows = false;
			scene.RootSceneNode.CreateChildSceneNode().AttachObject( planeEntity );

			camera.Position = new Vector3( -400, 50, 900 );
			camera.LookAt( new Vector3( 0, 80, 0 ) );

			/// Create a couple of hard coded postfilter effects as an example of how to do it
			/// but the preferred method is to use compositor scripts.
			_createEffects();

			foreach ( string name in _compositorList )
			{
				CompositorManager.Instance.AddCompositor( this.window.GetViewport( 0 ), name );
			}

			//CompositorManager.Instance.SetCompositorEnabled(this.window.GetViewport(0),
			//                                                 _compositorList[_compositorList.Length - 2],
			//                                                 true);
			CompositorManager.Instance.SetCompositorEnabled( this.window.GetViewport( 0 ),
															 _compositorList[ 0 ],
															 true );
		}
Exemplo n.º 32
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="deltaTime"></param>
		private void UpdateBody( Real deltaTime )
		{
			// we will calculate this
			goalDirection = Vector3.Zero;

			if ( keyDirection != Vector3.Zero && baseAnimID != AnimationID.Dance )
			{
				// calculate actually goal direction in world based on player's key directions
				goalDirection += keyDirection.z * cameraNode.Orientation.ZAxis;
				goalDirection += keyDirection.x * cameraNode.Orientation.XAxis;
				goalDirection.y = 0;
				goalDirection.Normalize();

				Quaternion toGoal = bodyNode.Orientation.ZAxis.GetRotationTo( goalDirection );
				// calculate how much the character has to turn to face goal direction
				Real yawToGlobal = toGoal.Yaw;
				// this is how much the character CAN turn this frame
				Real yawAtSpeed = yawToGlobal / Utility.Abs( yawToGlobal ) * deltaTime * TurnSpeed;
				// reduce "turnability" if we're in midair
				if ( baseAnimID == AnimationID.JumpLoop )
					yawAtSpeed *= 0.2;

				// turn as much as we can, but not more than we need to
				if ( yawToGlobal < 0 )
					yawToGlobal = Utility.Min<Real>( yawToGlobal, yawAtSpeed );
				else if ( yawToGlobal > 0 )
					yawToGlobal = Utility.Max<Real>( 0, Utility.Min<Real>( yawToGlobal, yawAtSpeed ) );

				bodyNode.Yaw( yawToGlobal );

				// move in current body direction (not the goal direction)
				bodyNode.Translate( new Vector3( 0, 0, deltaTime * RunSpeed * anims[ (int)baseAnimID ].Weight ), TransformSpace.Local );
			}

			if ( baseAnimID == AnimationID.JumpLoop )
			{
				// if we're jumping, add a vertical offset too, and apply gravity
				bodyNode.Translate( new Vector3( 0, verticalVelocity * deltaTime, 0 ), TransformSpace.Local );
				verticalVelocity -= Gravity * deltaTime;

				Vector3 pos = bodyNode.Position;
				if ( pos.y <= CharHeight )
				{
					// if we've hit the ground, change to landing state
					pos.y = CharHeight;
					bodyNode.Position = pos;
					SetBaseAnimation( AnimationID.JumpEnd, true );
					timer = 0;
				}
			}
		}
Exemplo n.º 33
0
		public void DoTerrainModify( Axiom.Components.Terrain.Terrain terrain, Vector3 centrepos, Real timeElapsed )
		{
			var tsPos = Vector3.Zero;
			terrain.GetTerrainPosition( centrepos, ref tsPos );

#if !( WINDOWS_PHONE || XBOX || XBOX360 || ANDROID || IOS )
			if ( Keyboard.IsKeyDown( SIS.KeyCode.Key_EQUALS ) || Keyboard.IsKeyDown( SIS.KeyCode.Key_ADD ) ||
			     Keyboard.IsKeyDown( SIS.KeyCode.Key_MINUS ) || Keyboard.IsKeyDown( SIS.KeyCode.Key_SUBTRACT ) )
			{
				switch ( this.mode )
				{
					case Mode.EditHeight:
					{
						// we need point coords
						Real terrainSize = ( terrain.Size - 1 );
						var startx = (long)( ( tsPos.x - this.brushSizeTerrainSpace )*terrainSize );
						var starty = (long)( ( tsPos.y - this.brushSizeTerrainSpace )*terrainSize );
						var endx = (long)( ( tsPos.x + this.brushSizeTerrainSpace )*terrainSize );
						var endy = (long)( ( tsPos.y + this.brushSizeTerrainSpace )*terrainSize );
						startx = Utility.Max( startx, 0L );
						starty = Utility.Max( starty, 0L );
						endx = Utility.Min( endx, (long)terrainSize );
						endy = Utility.Min( endy, (long)terrainSize );
						for ( long y = starty; y <= endy; ++y )
						{
							for ( long x = startx; x <= endx; ++x )
							{
								Real tsXdist = ( x/terrainSize ) - tsPos.x;
								Real tsYdist = ( y/terrainSize ) - tsPos.y;

								Real weight = Utility.Min( (Real)1.0,
								                           Utility.Sqrt( tsYdist*tsYdist + tsXdist*tsXdist )/
								                           (Real)( 0.5*this.brushSizeTerrainSpace ) );
								weight = 1.0 - ( weight*weight );

								var addedHeight = weight*250.0*timeElapsed;
								float newheight;
								if ( Keyboard.IsKeyDown( SIS.KeyCode.Key_EQUALS ) || Keyboard.IsKeyDown( SIS.KeyCode.Key_ADD ) )
								{
									newheight = terrain.GetHeightAtPoint( x, y ) + addedHeight;
								}
								else
								{
									newheight = terrain.GetHeightAtPoint( x, y ) - addedHeight;
								}
								terrain.SetHeightAtPoint( x, y, newheight );
							}
						}
						if ( this.heightUpdateCountDown == 0 )
						{
							this.heightUpdateCountDown = this.heightUpdateRate;
						}
					}
						break;

					case Mode.EditBlend:
					{
						var layer = terrain.GetLayerBlendMap( this.layerEdit );
						// we need image coords
						Real imgSize = terrain.LayerBlendMapSize;
						var startx = (long)( ( tsPos.x - this.brushSizeTerrainSpace )*imgSize );
						var starty = (long)( ( tsPos.y - this.brushSizeTerrainSpace )*imgSize );
						var endx = (long)( ( tsPos.x + this.brushSizeTerrainSpace )*imgSize );
						var endy = (long)( ( tsPos.y + this.brushSizeTerrainSpace )*imgSize );
						startx = Utility.Max( startx, 0L );
						starty = Utility.Max( starty, 0L );
						endx = Utility.Min( endx, (long)imgSize );
						endy = Utility.Min( endy, (long)imgSize );
						for ( var y = (int)starty; y <= endy; ++y )
						{
							for ( var x = (int)startx; x <= endx; ++x )
							{
								Real tsXdist = ( x/imgSize ) - tsPos.x;
								Real tsYdist = ( y/imgSize ) - tsPos.y;

								Real weight = Utility.Min( (Real)1.0,
								                           Utility.Sqrt( tsYdist*tsYdist + tsXdist*tsXdist )/
								                           (Real)( 0.5*this.brushSizeTerrainSpace ) );
								weight = 1.0 - ( weight*weight );

								float paint = weight*timeElapsed;
								var imgY = (int)( imgSize - y );
								float val;
								if ( Keyboard.IsKeyDown( SIS.KeyCode.Key_EQUALS ) || Keyboard.IsKeyDown( SIS.KeyCode.Key_ADD ) )
								{
									val = layer.GetBlendValue( x, imgY ) + paint;
								}
								else
								{
									val = layer.GetBlendValue( x, imgY ) - paint;
								}
								val = Utility.Clamp( val, 1.0f, 0.0f );
								layer.SetBlendValue( x, imgY, val );
							}
						}

						layer.Update();
					}
						break;

					case Mode.Normal:
					case Mode.Count:
					default:
						break;
				}
				;
			}
#endif
		}