示例#1
0
 public override void Move(int moveX, int moveY)
 {
     TerminateThreads();
     xorigin -= (Real)(moveX) * (xmax - xmin) / (Real)screenWidth;
     yorigin -= (Real)(moveY) * (ymax - ymin) / (Real)screenHeight;
     Draw(numIterations, numThreads);
 }
示例#2
0
		public virtual void Start( RenderWindow window, ushort numGroupsInit, ushort numGroupsLoad, Real initProportion )
		{
			mWindow = window;
			mNumGroupsInit = numGroupsInit;
			mNumGroupsLoad = numGroupsLoad;
			mInitProportion = initProportion;
			// We need to pre-initialise the 'Bootstrap' group so we can use
			// the basic contents in the loading screen
			ResourceGroupManager.Instance.InitializeResourceGroup( "Bootstrap" );

			OverlayManager omgr = OverlayManager.Instance;
			mLoadOverlay = omgr.GetByName( "Core/LoadOverlay" );
			if ( mLoadOverlay == null )
			{
				throw new KeyNotFoundException( "Cannot find loading overlay" );
			}
			mLoadOverlay.Show();

			// Save links to the bar and to the loading text, for updates as we go
			mLoadingBarElement = omgr.Elements.GetElement( "Core/LoadPanel/Bar/Progress" );
			mLoadingCommentElement = omgr.Elements.GetElement( "Core/LoadPanel/Comment" );
			mLoadingDescriptionElement = omgr.Elements.GetElement( "Core/LoadPanel/Description" );

			OverlayElement barContainer = omgr.Elements.GetElement( "Core/LoadPanel/Bar" );
			mProgressBarMaxSize = barContainer.Width;
			mLoadingBarElement.Width = 0;

			// self is listener
			ResourceGroupManager.Instance.AddResourceGroupListener( this );
		}
		public void Reset()
		{
			this.aabb.IsNull = true;
			this.receiverAabb.IsNull = true;
			this.minDistance = float.NegativeInfinity;
			this.maxDistance = 0;
		}
示例#4
0
		public override bool FrameRenderingQueued( FrameEventArgs evt )
		{
			// shoot a ray from the cursor to the plane
			var ray = TrayManager.GetCursorRay( Camera );
			this.mCursorQuery.Ray = ray;
			var result = this.mCursorQuery.Execute();

			if ( result.Count != 0 )
			{
				// using the point of intersection, find the corresponding texel on our texture
				var pt = ray.GetPoint( result[ result.Count - 1 ].Distance );
				this.mBrushPos = ( ( new Vector2( pt.x, -pt.y ) )*( 1.0f/this.mPlaneSize ) + ( new Vector2( 0.5, 0.5 ) ) )*
				                 TEXTURE_SIZE;
			}

			byte freezeAmount = 0;
			this.mTimeSinceLastFreeze += evt.TimeSinceLastFrame;

			// find out how much to freeze the plane based on time passed
			while ( this.mTimeSinceLastFreeze >= 0.1 )
			{
				this.mTimeSinceLastFreeze -= 0.1;
				freezeAmount += 0x04;
			}

			_updateTexture( freezeAmount ); // rebuild texture contents

			this.mPenguinAnimState.AddTime( evt.TimeSinceLastFrame ); // increment penguin idle animation time
			this.mPenguinNode.Yaw( (Real)( new Radian( (Real)evt.TimeSinceLastFrame ) ) ); // spin the penguin around

			return base.FrameRenderingQueued( evt ); // don't forget the parent class updates!
		}
		public override void MakeOrthoMatrix( Radian fovy, Real aspectRatio, Real near, Real far, out Matrix4 dest,
		                                      bool forGpuPrograms )
		{
			var thetaY = fovy/2.0f;
			var tanThetaY = Utility.Tan( thetaY );
			var tanThetaX = tanThetaY*aspectRatio;

			var half_w = tanThetaX*near;
			var half_h = tanThetaY*near;

			var iw = 1.0f/( half_w );
			var ih = 1.0f/( half_h );
			Real q = 0.0f;

			if ( far != 0 )
			{
				q = 1.0/( far - near );
			}

			dest = Matrix4.Zero;
			dest.m00 = iw;
			dest.m11 = ih;
			dest.m22 = q;
			dest.m23 = -near/( far - near );
			dest.m33 = 1;

			if ( forGpuPrograms )
			{
				dest.m22 = -dest.m22;
			}
		}
示例#6
0
		//		public Quaternion()
		//		{
		//			this.w = 1.0f;
		//		}

		/// <summary>
		///		Creates a new Quaternion.
		/// </summary>
		public Quaternion( Real w, Real x, Real y, Real z )
		{
			this.w = w;
			this.x = x;
			this.y = y;
			this.z = z;
		}
示例#7
0
		/// <summary>
		///		Creates a new 4 dimensional Vector.
		/// </summary>
		public Vector4( Real x, Real y, Real z, Real w )
		{
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}
示例#8
0
		public UniformParameter( GpuProgramParameters.AutoConstantType autoConstantType, Real autoConstantData, int size,
		                         GpuProgramParameters.GpuConstantType type )
			: base(
				Parameter.AutoParameters[ autoConstantType ].Type, Parameter.AutoParameters[ autoConstantType ].Name,
				SemanticType.Unknown, -1, ContentType.Unknown, size )
		{
			AutoShaderParameter parameterDef = Parameter.AutoParameters[ autoConstantType ];
			_name = parameterDef.Name;
			if ( autoConstantData != 0.0 )
			{
				_name += autoConstantData.ToString();
				//replace possible illegal point character in name
				_name = _name.Replace( '.', '_' );
			}
			_type = type;
			_semantic = SemanticType.Unknown;
			_index = -1;
			_content = Parameter.ContentType.Unknown;
			this.isAutoConstantReal = true;
			this.isAutoConstantInt = false;
			this.autoConstantType = autoConstantType;
			this.autoConstantRealData = autoConstantData;
			this.variability = (int)GpuProgramParameters.GpuParamVariability.Global;
			this._params = null;
			this.physicalIndex = -1;
			_size = size;
		}
		public void Reset()
		{
			aabb.IsNull = true;
			receiverAabb.IsNull = true;
			minDistance = float.NegativeInfinity;
			maxDistance = 0;
		}
示例#10
0
        public override void MakeOrthoMatrix(Radian fov, Real aspectRatio, Real near, Real far, out Matrix4 dest, bool forGpuPrograms)
        {
            float thetaY = Utility.DegreesToRadians(fov / 2.0f);
            float tanThetaY = Utility.Tan(thetaY);
            float tanThetaX = tanThetaY * aspectRatio;

            float halfW = tanThetaX * near;
            float halfH = tanThetaY * near;

            var w = 1.0f / (halfW);
            var h = 1.0f / (halfH);
            var q = 0.0f;

            if (far != 0)
            {
                q = 1.0f / (far - near);
            }

            dest = Matrix4.Zero;
            dest.m00 = w;
            dest.m11 = h;
            dest.m22 = q;
            dest.m23 = -near / (far - near);
            dest.m33 = 1;

            if (forGpuPrograms)
            {
                dest.m22 = -dest.m22;
            }
        }
示例#11
0
		public override void AffectParticles( ParticleSystem system, Real timeElapsed )
		{
			float ds;

			// Scale adjustments by time
			ds = this.scaleAdjust*timeElapsed;

			float newWide, newHigh;

			// loop through the particles

			for ( int i = 0; i < system.Particles.Count; i++ )
			{
				var p = (Particle)system.Particles[ i ];

				if ( p.HasOwnDimensions == false )
				{
					newHigh = system.DefaultHeight + ds;
					newWide = system.DefaultWidth + ds;
				}
				else
				{
					newWide = p.Width + ds;
					newHigh = p.Height + ds;
				}
				p.SetDimensions( newWide, newHigh );
			}
		}
示例#12
0
		public override void AffectParticles( ParticleSystem system, Real timeElapsed )
		{
			Vector3 scaledVector = Vector3.Zero;

			if ( this.forceApp == ForceApplication.Add )
			{
				// scale force by time
				scaledVector = this.forceVector*timeElapsed;
			}

			// affect each particle
			for ( int i = 0; i < system.Particles.Count; i++ )
			{
				var p = (Particle)system.Particles[ i ];

				if ( this.forceApp == ForceApplication.Add )
				{
					p.Direction += scaledVector;
				}
				else
				{
					// Average
					p.Direction = ( p.Direction + this.forceVector )/2;
				}
			}
		}
示例#13
0
		public ReflectionMap()
		{
			this.maskMapSamplerIndex = 0;
			this.reflectionMapSamplerIndex = 0;
			this.reflectionMapType = TextureType.TwoD;
			this.reflectionPowerChanged = true;
			this.reflectionPowerValue = 0.05f;
		}
		public void Merge( AxisAlignedBox boxBounds, Sphere sphereBounds, Camera cam, bool receiver )
		{
			aabb.Merge( boxBounds );
			if ( receiver )
				receiverAabb.Merge( boxBounds );
			Real camDistToCenter = ( cam.DerivedPosition - sphereBounds.Center ).Length;
			minDistance = System.Math.Min( minDistance, System.Math.Max( (Real)0, camDistToCenter - sphereBounds.Radius ) );
			maxDistance = System.Math.Max( maxDistance, camDistToCenter + sphereBounds.Radius );
		}
示例#15
0
        protected override void DrawInternal(object threadParams)
        {
            var tParams = (MandelThreadParams)threadParams;
            double ratio = (double)screenWidth / (double)screenHeight;
            xmin = xorigin;
            ymin = yorigin;
            xmax = xmin + xextent;
            ymax = ymin + xextent / ratio;

            int maxY = tParams.startY + tParams.startHeight;
            int maxX = tParams.startX + tParams.startWidth;
            Real x, y, x0, y0, temp = new Real();
            Real xscale = (xmax - xmin) / screenWidth;
            Real yscale = (ymax - ymin) / screenHeight;
            int iteration;
            int iterScale = 1;
            int px, py;

            if (numIterations < colorPaletteSize) { iterScale = colorPaletteSize / numIterations; }

            for (py = tParams.startY; py < maxY; py++)
            {
                y0 = ymin + py * yscale;

                for (px = tParams.startX; px < maxX; px++)
                {
                    x0 = xmin + px * xscale;

                    iteration = 0;
                    x = new Real(x0);
                    y = new Real(y0);

                    while ((iteration < numIterations) && (x.DoubleValue * x.DoubleValue + y.DoubleValue * y.DoubleValue <= 4))
                    {
                        Real.MandelbrotOperations(ref x, ref y, ref x0, ref y0, ref temp);
                        iteration++;
                    }

                    if (iteration >= numIterations)
                    {
                        bitmapBits[py * screenWidth + px] = 0xFF000000;
                    }
                    else
                    {
                        bitmapBits[py * screenWidth + px] = colorPalette[(iteration * iterScale) % colorPaletteSize];
                    }
                }

                if (terminateThreads) { break; }
            }

            tParams.parentForm.BeginInvoke(new MethodInvoker(delegate()
            {
                tParams.parentForm.Invalidate();
            }));
        }
示例#16
0
        public override BaseVariable[] CreateVariables()
        {
            var variables = new BaseVariable[Problema.NumberOfVariables];

            for (var var = 0; var < Problema.NumberOfVariables; var++)
            {
                variables[var] = new Real(Problema.LowerLimit[var], Problema.UpperLimit[var]);
            }

            return variables;
        }
示例#17
0
		/// <summary>
		/// Do not instantiate any widgets directly. Use SdkTrayManager.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="width"></param>
		public Separator( String name, Real width )
		{
			element = OverlayManager.Instance.Elements.CreateElementFromTemplate( "SdkTrays/Separator", "Panel", name );
			if ( width <= 0 )
				this.IsFitToTray = true;
			else
			{
				this.IsFitToTray = false;
				element.Width = width;
			}
		}
示例#18
0
 private void ChangeValue(dynamic calculator, Operations operation)
 {
     dynamic addvalue = null;
     if (CurrentVal.Text != "Write your Value:")
     {
         if (state.CalcEnum == CalcEnum.IntCalc)
         {
             addvalue = new Real<int>(int.Parse(CurrentVal.Text));
         }
         if (state.CalcEnum == CalcEnum.FloatCalc)
         {
             addvalue = new Real<double>(double.Parse(CurrentVal.Text));
         }
         if (state.CalcEnum == CalcEnum.ComCalc)
         {
             addvalue = new Complecs(CurrentVal.Text);
         }
         switch (operation)
         {
             case Operations.Add:
                 calculator.Add(addvalue);
                 break;
             case Operations.Remove:
                 calculator.Remove(addvalue);
                 break;
             case Operations.Divide:
                 calculator.Divide(addvalue);
                 break;
             case Operations.Multiply:
                 calculator.Multiply(addvalue);
                 break;
             case Operations.Clear:
                 calculator.Clear(addvalue);
                 break;
             case Operations.Sqrt:
                 try
                 {
                     calculator.Sqrt(addvalue);
                 }
                 catch (Exception)
                 {
                     MessageBox.Show("Eror: Divide at 0");
                 }
                 break;
             case Operations.Modul:
                 calculator.Modul(addvalue);
                 break;
         }
     }
     else
     {
         MessageBox.Show("Write Value!!!!");
     }
 }
示例#19
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="slices"></param>
		/// <param name="size"></param>
		/// <param name="texture"></param>
		public VolumeRendable( int slices, int size, string texture )
		{
			this.slices = slices;
			this.size = size;
			this.texture = texture;

			this.radius = Utility.Sqrt( size*size + size*size + size*size )/2.0f;
			box = new AxisAlignedBox( new Vector3( -size, -size, -size ), new Vector3( size, size, size ) );

			CastShadows = false;

			Initialize();
		}
示例#20
0
		/// <summary>
		/// Do not instantiate any widgets directly. Use SdkTrayManager.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="caption"></param>
		/// <param name="width"></param>
		public CheckBox( String name, String caption, Real width )
		{
			this.IsCursorOver = false;
			this.isFitToContents = width <= 0;
			element = OverlayManager.Instance.Elements.CreateElementFromTemplate( "SdkTrays/CheckBox", "BorderPanel", name );
			var c = (OverlayElementContainer)element;
			this.textArea = (TextArea)c.Children[ Name + "/CheckBoxCaption" ];
			this.square = (BorderPanel)c.Children[ Name + "/CheckBoxSquare" ];
			this.x = this.square.Children[ this.square.Name + "/CheckBoxX" ];
			this.x.Hide();
			element.Width = width;
			Caption = caption;
		}
示例#21
0
文件: Label.cs 项目: WolfgangSt/axiom
		/// <summary>
		/// Do not instantiate any widgets directly. Use SdkTrayManager.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="caption"></param>
		/// <param name="width"></param>
		public Label( String name, String caption, Real width )
		{
			element = OverlayManager.Instance.Elements.CreateElementFromTemplate( "SdkTrays/Label", "BorderPanel", name );
			this.textArea = (TextArea)( (OverlayElementContainer)element ).Children[ Name + "/LabelCaption" ];
			this.textArea.Text = caption;
			this.Caption = caption;
			if ( width <= 0 )
				this.isFitToTray = true;
			else
			{
				this.isFitToTray = false;
				element.Width = width;
			}
		}
示例#22
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;
		}
示例#23
0
        public override void Zoom(int posX, int posY, double factor)
        {
            Real xpos = xmin + ((Real)posX * (xmax - xmin) / (Real)screenWidth);
            Real ypos = ymin + ((Real)posY * (ymax - ymin) / (Real)screenHeight);
            Real xOffsetRatio = (xpos - xmin) / (xmax - xmin);
            Real yOffsetRatio = (ypos - ymin) / (ymax - ymin);

            Real newXextent = (xmax - xmin);
            newXextent *= factor;

            Real newYextent = (ymax - ymin);
            newYextent *= factor;

            TerminateThreads();
            xextent = newXextent;
            xorigin = xpos - xextent * xOffsetRatio;
            yorigin = ypos - newYextent * yOffsetRatio;
            Draw(numIterations, numThreads);
        }
示例#24
0
		/// <summary>
		///   Resolve uniform auto constant parameter with associated real data of this program
		/// </summary>
		/// <param name="autoType"> The auto type of the desired parameter </param>
		/// <param name="data"> The data to associate with the auto parameter </param>
		/// <param name="size"> number of elements in the parameter </param>
		/// <returns> parameter instance in case of that resolve operation succeeded, otherwise null </returns>
		public UniformParameter ResolveAutoParameterReal( GpuProgramParameters.AutoConstantType autoType, Real data,
		                                                  int size )
		{
			UniformParameter param = null;

			//check if parameter already exists.
			param = GetParameterByAutoType( autoType );
			if ( param != null )
			{
				if ( param.IsAutoConstantRealParameter && param.AutoConstantRealData == data )
				{
					param.Size = Axiom.Math.Utility.Max( size, param.Size );
					return param;
				}
			}

			//Create new parameter
			param = new UniformParameter( autoType, data, size );
			AddParameter( param );

			return param;
		}
		public override void AffectParticles( ParticleSystem system, Real timeElapsed )
		{
			// loop through the particles
			for ( int i = 0; i < system.Particles.Count; i++ )
			{
				var p = (Particle)system.Particles[ i ];

				float lifeTime = p.totalTimeToLive;
				float particleTime = 1.0f - ( p.timeToLive/lifeTime );

				if ( particleTime <= this.timeAdj[ 0 ] )
				{
					p.Color = this.colorAdj[ 0 ];
				}
				else if ( particleTime >= this.timeAdj[ MAX_STAGES - 1 ] )
				{
					p.Color = this.colorAdj[ MAX_STAGES - 1 ];
				}
				else
				{
					for ( int k = 0; k < MAX_STAGES - 1; k++ )
					{
						if ( particleTime >= this.timeAdj[ k ] && particleTime < this.timeAdj[ k + 1 ] )
						{
							particleTime -= this.timeAdj[ k ];
							particleTime /= ( this.timeAdj[ k + 1 ] - this.timeAdj[ k ] );
							p.Color.r = ( ( this.colorAdj[ k + 1 ].r*particleTime ) + ( this.colorAdj[ k ].r*( 1.0f - particleTime ) ) );
							p.Color.g = ( ( this.colorAdj[ k + 1 ].g*particleTime ) + ( this.colorAdj[ k ].g*( 1.0f - particleTime ) ) );
							p.Color.b = ( ( this.colorAdj[ k + 1 ].b*particleTime ) + ( this.colorAdj[ k ].b*( 1.0f - particleTime ) ) );
							p.Color.a = ( ( this.colorAdj[ k + 1 ].a*particleTime ) + ( this.colorAdj[ k ].a*( 1.0f - particleTime ) ) );

							break;
						}
					}
				}
			}
		}
示例#26
0
        public override void MakeProjectionMatrix(Radian fov, Real aspectRatio, Real near, Real far, out Matrix4 dest, bool forGpuProgram)
        {
            float theta = Utility.DegreesToRadians((float)fov * 0.5f);
            float h = 1.0f / Utility.Tan(theta);
            float w = h / aspectRatio;
            float q, qn;

            if (far == 0)
            {
                q = 1 - Frustum.InfiniteFarPlaneAdjust;
                qn = near * (Frustum.InfiniteFarPlaneAdjust - 1);
            }
            else
            {
                q = far / (far - near);
                qn = -q * near;
            }

            dest = Matrix4.Zero;

            dest.m00 = w;
            dest.m11 = h;

            if (forGpuProgram)
            {
                dest.m22 = -q;
                dest.m32 = -1.0f;
            }
            else
            {
                dest.m22 = q;
                dest.m32 = 1.0f;
            }

            dest.m23 = qn;
        }
示例#27
0
            private void ComputeNormal(ref Vec3 norm)
            {
                var v = _mesh._vHead._next;

                var minVal = new Real[3] {
                    v._coords.X, v._coords.Y, v._coords.Z
                };
                var minVert = new MeshUtils.Vertex[3] {
                    v, v, v
                };
                var maxVal = new Real[3] {
                    v._coords.X, v._coords.Y, v._coords.Z
                };
                var maxVert = new MeshUtils.Vertex[3] {
                    v, v, v
                };

                for (; v != _mesh._vHead; v = v._next)
                {
                    if (v._coords.X < minVal[0])
                    {
                        minVal[0] = v._coords.X; minVert[0] = v;
                    }
                    if (v._coords.Y < minVal[1])
                    {
                        minVal[1] = v._coords.Y; minVert[1] = v;
                    }
                    if (v._coords.Z < minVal[2])
                    {
                        minVal[2] = v._coords.Z; minVert[2] = v;
                    }
                    if (v._coords.X > maxVal[0])
                    {
                        maxVal[0] = v._coords.X; maxVert[0] = v;
                    }
                    if (v._coords.Y > maxVal[1])
                    {
                        maxVal[1] = v._coords.Y; maxVert[1] = v;
                    }
                    if (v._coords.Z > maxVal[2])
                    {
                        maxVal[2] = v._coords.Z; maxVert[2] = v;
                    }
                }

                // Find two vertices separated by at least 1/sqrt(3) of the maximum
                // distance between any two vertices
                int i = 0;

                if (maxVal[1] - minVal[1] > maxVal[0] - minVal[0])
                {
                    i = 1;
                }
                if (maxVal[2] - minVal[2] > maxVal[i] - minVal[i])
                {
                    i = 2;
                }
                if (minVal[i] >= maxVal[i])
                {
                    // All vertices are the same -- normal doesn't matter
                    norm = new Vec3 {
                        X = 0, Y = 0, Z = 1
                    };
                    return;
                }

                // Look for a third vertex which forms the triangle with maximum area
                // (Length of normal == twice the triangle area)
                Real maxLen2 = 0, tLen2;
                var  v1 = minVert[i];
                var  v2 = maxVert[i];
                Vec3 d1, d2, tNorm;

                Vec3.Sub(ref v1._coords, ref v2._coords, out d1);
                for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
                {
                    Vec3.Sub(ref v._coords, ref v2._coords, out d2);
                    tNorm.X = d1.Y * d2.Z - d1.Z * d2.Y;
                    tNorm.Y = d1.Z * d2.X - d1.X * d2.Z;
                    tNorm.Z = d1.X * d2.Y - d1.Y * d2.X;
                    tLen2   = tNorm.X * tNorm.X + tNorm.Y * tNorm.Y + tNorm.Z * tNorm.Z;
                    if (tLen2 > maxLen2)
                    {
                        maxLen2 = tLen2;
                        norm    = tNorm;
                    }
                }

                if (maxLen2 <= 0.0f)
                {
                    // All points lie on a single line -- any decent normal will do
                    norm    = Vec3.Zero;
                    i       = Vec3.LongAxis(ref d1);
                    norm[i] = 1;
                }
            }
示例#28
0
文件: Font.cs 项目: axiom3d/axiom
 public void SetGlyphTexCoords(CodePoint c, Real u1, Real v1, Real u2, Real v2)
 {
     SetGlyphTexCoords(c, u1, v1, u2, v2, (u2 - u1) / (v2 - v1));
 }
示例#29
0
 public FloatingLimit(Real referenceValue, StatusFlags statusFlags, Real setpointValue, Real errorLimit)
 {
     ReferenceValue = referenceValue;
     StatusFlags    = statusFlags;
     SetpointValue  = setpointValue;
     ErrorLimit     = errorLimit;
 }
示例#30
0
        protected override void NeedPreviousBackwardGpu(NdArray y, NdArray x)
        {
            Real[] gx          = new Real[x.Data.Length];
            Real[] activatedgy = this.Activator != null?GetActivatedgy(y) : y.Grad;

            if (!NoBias)
            {
                CalcBiasGrad(activatedgy, y.BatchCount);
            }

            using (ComputeBuffer <Real> gpugY = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, activatedgy))
            {
                using (ComputeBuffer <Real> gpugW = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.CopyHostPointer, this.Weight.Grad))
                    using (ComputeBuffer <Real> gpuX = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, x.Data))
                    {
                        BackwardgWKernel.SetMemoryArgument(0, gpugY);
                        BackwardgWKernel.SetMemoryArgument(1, gpuX);
                        BackwardgWKernel.SetMemoryArgument(2, gpugW);
                        BackwardgWKernel.SetValueArgument(3, y.BatchCount);
                        BackwardgWKernel.SetValueArgument(4, this.OutputCount);
                        BackwardgWKernel.SetValueArgument(5, this.InputCount);

                        Weaver.CommandQueue.Execute
                        (
                            BackwardgWKernel,
                            null,
                            new long[] { this.InputCount, this.OutputCount },
                            null,
                            null
                        );

                        Weaver.CommandQueue.Finish();
                        Weaver.CommandQueue.ReadFromBuffer(gpugW, ref this.Weight.Grad, true, null);
                    }

                using (ComputeBuffer <Real> gpugX = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.WriteOnly | ComputeMemoryFlags.AllocateHostPointer, gx.Length))
                    using (ComputeBuffer <Real> gpuW = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, this.Weight.Data))
                    {
                        BackwardgXKernel.SetMemoryArgument(0, gpugY);
                        BackwardgXKernel.SetMemoryArgument(1, gpuW);
                        BackwardgXKernel.SetMemoryArgument(2, gpugX);
                        BackwardgXKernel.SetValueArgument(3, y.BatchCount);
                        BackwardgXKernel.SetValueArgument(4, this.OutputCount);
                        BackwardgXKernel.SetValueArgument(5, this.InputCount);

                        Weaver.CommandQueue.Execute
                        (
                            BackwardgXKernel,
                            null,
                            new long[] { this.InputCount, y.BatchCount },
                            null,
                            null
                        );

                        Weaver.CommandQueue.Finish();
                        Weaver.CommandQueue.ReadFromBuffer(gpugX, ref gx, true, null);
                    }
            }

            for (int i = 0; i < x.Grad.Length; i++)
            {
                x.Grad[i] += gx[i];
            }
        }
示例#31
0
        //public Plane()
        //{
        //    this.Normal = Vector3.Zero;
        //    this.D = Real.NaN;
        //}

        public Plane(Plane plane)
        {
            this.Normal = plane.Normal;
            this.D      = plane.D;
        }
示例#32
0
        public static void Run()
        {
            _outputStream = File.Create(LogPath);

            _logWriter = new HistogramLogWriter(_outputStream);
            _logWriter.Write(DateTime.Now);

            var recorder = HistogramFactory
                           .With64BitBucketSize()
                           ?.WithValuesFrom(1)
                           ?.WithValuesUpTo(2345678912345)
                           ?.WithPrecisionOf(3)
                           ?.WithThreadSafeWrites()
                           ?.WithThreadSafeReads()
                           ?.Create();

            var accumulatingHistogram = new LongHistogram(2345678912345, 3);

            var size = accumulatingHistogram.GetEstimatedFootprintInBytes();

            RILogManager.Default?.SendDebug("Histogram size = {0} bytes ({1:F2} MB)", size, size / 1024.0 / 1024.0);


            RILogManager.Default?.SendDebug("Recorded latencies [in system clock ticks]");
            accumulatingHistogram.OutputPercentileDistribution(Console.Out, outputValueUnitScalingRatio: OutputScalingFactor.None, useCsvFormat: true);
            Console.WriteLine();

            RILogManager.Default?.SendDebug("Recorded latencies [in usec]");
            accumulatingHistogram.OutputPercentileDistribution(Console.Out, outputValueUnitScalingRatio: OutputScalingFactor.TimeStampToMicroseconds, useCsvFormat: true);
            Console.WriteLine();

            RILogManager.Default?.SendDebug("Recorded latencies [in msec]");
            accumulatingHistogram.OutputPercentileDistribution(Console.Out, outputValueUnitScalingRatio: OutputScalingFactor.TimeStampToMilliseconds, useCsvFormat: true);
            Console.WriteLine();

            RILogManager.Default?.SendDebug("Recorded latencies [in sec]");
            accumulatingHistogram.OutputPercentileDistribution(Console.Out, outputValueUnitScalingRatio: OutputScalingFactor.TimeStampToSeconds, useCsvFormat: true);

            DocumentResults(accumulatingHistogram, recorder);

            RILogManager.Default?.SendDebug("Build Vocabulary.");

            DocumentResults(accumulatingHistogram, recorder);

            Vocabulary vocabulary = new Vocabulary();

            DocumentResults(accumulatingHistogram, recorder);

            string trainPath = InternetFileDownloader.Download(DOWNLOAD_URL + TRAIN_FILE, TRAIN_FILE);

            DocumentResults(accumulatingHistogram, recorder);

            string validPath = InternetFileDownloader.Download(DOWNLOAD_URL + VALID_FILE, VALID_FILE);

            DocumentResults(accumulatingHistogram, recorder);

            string testPath = InternetFileDownloader.Download(DOWNLOAD_URL + TEST_FILE, TEST_FILE);

            DocumentResults(accumulatingHistogram, recorder);


            int[] trainData = vocabulary.LoadData(trainPath);
            DocumentResults(accumulatingHistogram, recorder);

            int[] validData = vocabulary.LoadData(validPath);
            DocumentResults(accumulatingHistogram, recorder);

            int[] testData = vocabulary.LoadData(testPath);
            DocumentResults(accumulatingHistogram, recorder);

            int nVocab = vocabulary.Length;

            RILogManager.Default?.SendDebug("Network Initializing.");
            FunctionStack model = new FunctionStack("Test10",
                                                    new EmbedID(nVocab, N_UNITS, name: "l1 EmbedID"),
                                                    new Dropout(),
                                                    new LSTM(true, N_UNITS, N_UNITS, name: "l2 LSTM"),
                                                    new Dropout(),
                                                    new LSTM(true, N_UNITS, N_UNITS, name: "l3 LSTM"),
                                                    new Dropout(),
                                                    new Linear(true, N_UNITS, nVocab, name: "l4 Linear")
                                                    );

            DocumentResults(accumulatingHistogram, recorder);

            // Do not cease at the given threshold, correct the rate by taking the rate from L2Norm of all parameters
            GradientClipping gradientClipping = new GradientClipping(threshold: GRAD_CLIP);
            SGD sgd = new SGD(learningRate: 1);

            model.SetOptimizer(gradientClipping, sgd);
            DocumentResults(accumulatingHistogram, recorder);

            Real wholeLen = trainData.Length;
            int  jump     = (int)Math.Floor(wholeLen / BATCH_SIZE);
            int  epoch    = 0;

            Stack <NdArray[]> backNdArrays = new Stack <NdArray[]>();

            RILogManager.Default?.SendDebug("Train Start.");
            double  dVal;
            NdArray x = new NdArray(new[] { 1 }, BATCH_SIZE, (Function)null);
            NdArray t = new NdArray(new[] { 1 }, BATCH_SIZE, (Function)null);

            for (int i = 0; i < jump * N_EPOCH; i++)
            {
                for (int j = 0; j < BATCH_SIZE; j++)
                {
                    x.Data[j] = trainData[(int)((jump * j + i) % wholeLen)];
                    t.Data[j] = trainData[(int)((jump * j + i + 1) % wholeLen)];
                }

                NdArray[] result  = model.Forward(true, x);
                Real      sumLoss = new SoftmaxCrossEntropy().Evaluate(result, t);
                backNdArrays.Push(result);
                RILogManager.Default?.SendDebug("[{0}/{1}] Loss: {2}", i + 1, jump, sumLoss);

                //Run truncated BPTT
                if ((i + 1) % BPROP_LEN == 0)
                {
                    for (int j = 0; backNdArrays.Count > 0; j++)
                    {
                        RILogManager.Default?.SendDebug("backward" + backNdArrays.Count);
                        model.Backward(true, backNdArrays.Pop());
                    }

                    model.Update();
                    model.ResetState();
                }

                if ((i + 1) % jump == 0)
                {
                    epoch++;
                    RILogManager.Default?.SendDebug("evaluate");
                    dVal = Evaluate(model, validData);
                    RILogManager.Default?.SendDebug($"validation perplexity: {dVal}");

                    if (epoch >= 6)
                    {
                        sgd.LearningRate /= 1.2;
                        RILogManager.Default?.SendDebug("learning rate =" + sgd.LearningRate);
                    }
                }
                DocumentResults(accumulatingHistogram, recorder);
            }

            RILogManager.Default?.SendDebug("test start");
            dVal = Evaluate(model, testData);
            RILogManager.Default?.SendDebug("test perplexity:" + dVal);
            DocumentResults(accumulatingHistogram, recorder);

            _logWriter.Dispose();
            _outputStream.Dispose();


            RILogManager.Default?.SendDebug("Log contents");
            RILogManager.Default?.SendDebug(File.ReadAllText(LogPath));
            Console.WriteLine();
            RILogManager.Default?.SendDebug("Percentile distribution (values reported in milliseconds)");
            accumulatingHistogram.OutputPercentileDistribution(Console.Out, outputValueUnitScalingRatio: OutputScalingFactor.TimeStampToMilliseconds, useCsvFormat: true);

            RILogManager.Default?.SendDebug("Mean: " + BytesToString(accumulatingHistogram.GetMean()) + ", StdDev: " +
                                            BytesToString(accumulatingHistogram.GetStdDeviation()));
        }
示例#33
0
 /// <summary>
 ///		Returns an interpolated point based on a parametric value over the whole series.
 /// </summary>
 /// <remarks>
 ///		Given a t value between 0 and 1 representing the parametric distance along the
 ///		whole length of the spline, this method returns an interpolated point.
 /// </remarks>
 /// <param name="t">Parametric value.</param>
 /// <returns>An interpolated point along the spline.</returns>
 public abstract T Interpolate(Real t);
示例#34
0
        public static void Run()
        {
            Stopwatch sw = new Stopwatch();

            //MNISTのデータを用意する
            Console.WriteLine("MNIST Data Loading...");
            MnistData mnistData = new MnistData();

            //ネットワークの構成を FunctionStack に書き連ねる
            FunctionStack nn = new FunctionStack(
                new Convolution2D(1, 32, 5, pad: 2, name: "l1 Conv2D", gpuEnable: true),
                new ReLU(name: "l1 ReLU"),
                //new AveragePooling(2, 2, name: "l1 AVGPooling"),
                new MaxPooling(2, 2, name: "l1 MaxPooling", gpuEnable: true),
                new Convolution2D(32, 64, 5, pad: 2, name: "l2 Conv2D", gpuEnable: true),
                new ReLU(name: "l2 ReLU"),
                //new AveragePooling(2, 2, name: "l2 AVGPooling"),
                new MaxPooling(2, 2, name: "l2 MaxPooling", gpuEnable: true),
                new Linear(7 * 7 * 64, 1024, name: "l3 Linear", gpuEnable: true),
                new ReLU(name: "l3 ReLU"),
                new Dropout(name: "l3 DropOut"),
                new Linear(1024, 10, name: "l4 Linear", gpuEnable: true)
                );

            //optimizerを宣言
            nn.SetOptimizer(new Adam());

            Console.WriteLine("Training Start...");

            //三世代学習
            for (int epoch = 1; epoch < 3; epoch++)
            {
                Console.WriteLine("epoch " + epoch);

                //全体での誤差を集計
                Real totalLoss      = 0;
                long totalLossCount = 0;

                //何回バッチを実行するか
                for (int i = 1; i < TRAIN_DATA_COUNT + 1; i++)
                {
                    sw.Restart();

                    Console.WriteLine("\nbatch count " + i + "/" + TRAIN_DATA_COUNT);

                    //訓練データからランダムにデータを取得
                    TestDataSet datasetX = mnistData.GetRandomXSet(BATCH_DATA_COUNT);

                    //バッチ学習を並列実行する
                    Real sumLoss = Trainer.Train(nn, datasetX.Data, datasetX.Label, new SoftmaxCrossEntropy());
                    totalLoss += sumLoss;
                    totalLossCount++;

                    //結果出力
                    Console.WriteLine("total loss " + totalLoss / totalLossCount);
                    Console.WriteLine("local loss " + sumLoss);

                    sw.Stop();
                    Console.WriteLine("time" + sw.Elapsed.TotalMilliseconds);

                    //20回バッチを動かしたら精度をテストする
                    if (i % 20 == 0)
                    {
                        Console.WriteLine("\nTesting...");

                        //テストデータからランダムにデータを取得
                        TestDataSet datasetY = mnistData.GetRandomYSet(TEACH_DATA_COUNT);

                        //テストを実行
                        Real accuracy = Trainer.Accuracy(nn, datasetY.Data, datasetY.Label);
                        Console.WriteLine("accuracy " + accuracy);
                    }
                }
            }
        }
示例#35
0
 public static void Dot(ref Vec3 u, ref Vec3 v, out Real dot)
 {
     dot = u.X * v.X + u.Y * v.Y + u.Z * v.Z;
 }
		public override Real Execute( Real source )
		{
			return AdjustInput( source );
		}
示例#37
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="evt"></param>
		public override void FrameRenderingQueued( object sender, FrameEventArgs evt )
		{
			// don't do all these calculations when sample's running or when in configuration screen or when no samples loaded
			if ( !( this.LoadedSamples.Count == 0 ) && this.TitleLabel.TrayLocation != TrayLocation.None &&
			     ( CurrentSample == null || IsSamplePaused ) )
			{
				// makes the carousel spin smoothly toward its right position
				Real carouselOffset = this.SampleMenu.SelectionIndex - this.CarouselPlace;
				if ( carouselOffset <= 0.001 && ( carouselOffset >= -0.001 ) )
				{
					this.CarouselPlace = this.SampleMenu.SelectionIndex;
				}
				else
				{
					this.CarouselPlace += carouselOffset*Math.Utility.Clamp<Real>( evt.TimeSinceLastFrame*15, 1, -1 );
				}

				// update the thumbnail positions based on carousel state
				for ( int i = 0; i < this.Thumbs.Count; i++ )
				{
					Real thumbOffset = this.CarouselPlace - i;
					Real phase = ( thumbOffset/2 ) - 2.8;

					if ( thumbOffset < -5 || thumbOffset > 4 ) // prevent thumbnails from wrapping around in a circle
					{
						this.Thumbs[ i ].Hide();
						continue;
					}
					else
					{
						this.Thumbs[ i ].Show();
					}

					Real left = System.Math.Cos( phase )*200;
					Real top = System.Math.Sin( phase )*200;
					Real scale = 1.0f/System.Math.Pow( ( System.Math.Abs( thumbOffset ) + 1.0f ), 0.75 );

					OverlayElement[] childs = this.Thumbs[ i ].Children.Values.ToArray();
					if ( this.childIndex >= childs.Length )
					{
						this.childIndex = 0;
					}

					var frame = (Overlays.Elements.BorderPanel)childs[ this.childIndex++ ];

					this.Thumbs[ i ].SetDimensions( 128*scale, 96*scale );
					frame.SetDimensions( this.Thumbs[ i ].Width + 16, this.Thumbs[ i ].Height + 16 );
					this.Thumbs[ i ].SetPosition( (int)( left - 80 - this.Thumbs[ i ].Width/2 ),
					                              (int)( top - 5 - this.Thumbs[ i ].Height/2 ) );

					if ( i == this.SampleMenu.SelectionIndex )
					{
						frame.BorderMaterialName = "SdkTrays/Frame/Over";
					}
					else
					{
						frame.BorderMaterialName = "SdkTrays/Frame";
					}
				}
			}

			this.TrayManager.FrameRenderingQueued( evt );

			try
			{
				base.FrameRenderingQueued( sender, evt );
			}
			catch ( Exception e ) // show error and fall back to menu
			{
				RunSample( null );
				this.TrayManager.ShowOkDialog( "Error!", e.ToString() + "\nSource: " + e.StackTrace.ToString() );
			}
		}
示例#38
0
 public Degree(Real r)
 {
     this._value = r;
 }
示例#39
0
 public int CompareTo(Real other)
 {
     return(this._value.CompareTo(other));
 }
示例#40
0
文件: Slider.cs 项目: axiom3d/axiom
        /// <summary>
        /// Do not instantiate any widgets directly. Use SdkTrayManager.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="caption"></param>
        /// <param name="width"></param>
        /// <param name="trackWidth"></param>
        /// <param name="valueBoxWidth"></param>
        /// <param name="minValue"></param>
        /// <param name="maxValue"></param>
        /// <param name="snaps"></param>
        public Slider(String name, String caption, Real width, Real trackWidth, Real valueBoxWidth, Real minValue,
                      Real maxValue, int snaps)
        {
            this.isDragging      = false;
            this.isFitToContents = false;
            element       = OverlayManager.Instance.Elements.CreateElementFromTemplate("SdkTrays/Slider", "BorderPanel", name);
            element.Width = width;
            var c = (OverlayElementContainer)element;

            this.textArea = (TextArea)c.Children[Name + "/SliderCaption"];
            var valueBox = (OverlayElementContainer)c.Children[Name + "/SliderValueBox"];

            valueBox.Width     = valueBoxWidth;
            valueBox.Left      = -(valueBoxWidth + 5);
            this.valueTextArea = (TextArea)valueBox.Children[valueBox.Name + "/SliderValueText"];
            this.track         = (BorderPanel)c.Children[Name + "/SliderTrack"];
            this.handle        = (Panel)this.track.Children[this.track.Name + "/SliderHandle"];

            if (trackWidth <= 0) // tall style
            {
                this.track.Width = width - 16;
            }
            else // long style
            {
                if (width <= 0)
                {
                    this.isFitToContents = true;
                }
                element.Height    = 34;
                this.textArea.Top = 10;
                valueBox.Top      = 2;
                this.track.Top    = -23;
                this.track.Width  = trackWidth;
                this.track.HorizontalAlignment = HorizontalAlignment.Right;
                this.track.Left = -(trackWidth + valueBoxWidth + 5);
            }

            Caption = caption;
            SetRange(minValue, maxValue, snaps, false);
        }
示例#41
0
 /// <summary>
 /// Gets the position of a point t units along the ray.
 /// </summary>
 /// <param name="t"></param>
 /// <returns></returns>
 public Vector3 this[Real t] {
     get { return(origin + (direction * t)); }
 }
示例#42
0
文件: Slider.cs 项目: axiom3d/axiom
 /// <summary>
 /// Sets the minimum value, maximum value, and the number of snapping points.
 /// </summary>
 /// <param name="minValue"></param>
 /// <param name="maxValue"></param>
 /// <param name="snaps"></param>
 public void SetRange(Real minValue, Real maxValue, int snaps)
 {
     SetRange(minValue, maxValue, snaps, true);
 }
示例#43
0
 /// <summary>
 ///		Interpolates a single segment of the spline given a parametric value.
 /// </summary>
 /// <param name="index">The point index to treat as t=0. index + 1 is deemed to be t=1</param>
 /// <param name="t">Parametric value</param>
 /// <returns>An interpolated point along the spline.</returns>
 public abstract T Interpolate(int index, Real t);
示例#44
0
        protected override NdArray NeedPreviousForwardCpu(NdArray input)
        {
            int outputHeight = (input.Shape[1] - 1) * this._subSampleY + this._kHeight - this._trimY * 2;
            int outputWidth  = (input.Shape[2] - 1) * this._subSampleX + this._kWidth - this._trimX * 2;

            Real[] result = new Real[input.BatchCount * this.OutputCount * outputWidth * outputHeight];

            int outSizeOffset   = outputWidth * outputHeight;
            int inputSizeOffset = input.Shape[1] * input.Shape[2];
            int kSizeOffset     = this.Weight.Shape[2] * this.Weight.Shape[3];

            for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
            {
                for (int och = 0; och < this.OutputCount; och++)
                {
                    for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
                    {
                        int iyLimit = oy / this._subSampleY + 1 < input.Shape[1] ? oy / this._subSampleY + 1 : input.Shape[1];
                        int iyStart = oy - this.Weight.Shape[2] < 0 ? 0 : (oy - this.Weight.Shape[2]) / this._subSampleY + 1;

                        for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
                        {
                            int ixLimit = ox / this._subSampleX + 1 < input.Shape[2] ? ox / this._subSampleX + 1 : input.Shape[2];
                            int ixStart = ox - this.Weight.Shape[3] < 0 ? 0 : (ox - this.Weight.Shape[3]) / this._subSampleX + 1;

                            int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;

                            for (int ich = 0; ich < input.Shape[0]; ich++)
                            {
                                int inputIndexOffset  = batchCount * input.Length + ich * inputSizeOffset;
                                int kernelIndexOffset = och * this.Weight.Shape[1] * kSizeOffset + ich * kSizeOffset;

                                for (int iy = iyStart; iy < iyLimit; iy++)
                                {
                                    for (int ix = ixStart; ix < ixLimit; ix++)
                                    {
                                        int inputIndex  = inputIndexOffset + iy * input.Shape[2] + ix;
                                        int kernelIndex = kernelIndexOffset + (oy - iy * this._subSampleY) * this.Weight.Shape[3] + (ox - ix * this._subSampleX);

                                        result[outputIndex] += input.Data[inputIndex] * this.Weight.Data[kernelIndex];
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (this.Activator != null && !NoBias)
            {
                for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
                {
                    for (int och = 0; och < this.OutputCount; och++)
                    {
                        for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
                        {
                            for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
                            {
                                int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;

                                result[outputIndex] += this.Bias.Data[och];
                                result[outputIndex]  = this.Activator.ForwardActivate(result[outputIndex]);
                            }
                        }
                    }
                }
            }
            else if (!NoBias)
            {
                for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
                {
                    for (int och = 0; och < this.OutputCount; och++)
                    {
                        for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
                        {
                            for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
                            {
                                int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;

                                result[outputIndex] += this.Bias.Data[och];
                            }
                        }
                    }
                }
            }
            else if (this.Activator != null)
            {
                for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
                {
                    for (int och = 0; och < this.OutputCount; och++)
                    {
                        for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
                        {
                            for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
                            {
                                int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;

                                result[outputIndex] = this.Activator.ForwardActivate(result[outputIndex]);
                            }
                        }
                    }
                }
            }

            return(NdArray.Convert(result, new[] { this.OutputCount, outputHeight, outputWidth }, input.BatchCount, this));
        }
示例#45
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);
 }
示例#46
0
文件: Font.cs 项目: axiom3d/axiom
 public GlyphInfo(CodePoint id, UVRect rect, Real aspect)
 {
     this.codePoint   = id;
     this.uvRect      = rect;
     this.aspectRatio = aspect;
 }
示例#47
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;
 }
示例#48
0
文件: Font.cs 项目: axiom3d/axiom
        public void SetGlyphTexCoords(CodePoint c, Real u1, Real v1, Real u2, Real v2, Real aspect)
        {
            var glyph = new GlyphInfo(c, new UVRect(v1, u1, v2, u2), aspect * (u2 - u1) / (v2 - v1));

            if (this.codePoints.ContainsKey(c))
            {
                this.codePoints[c] = glyph;
            }
            else
            {
                this.codePoints.Add(c, glyph);
            }
        }
示例#49
0
文件: Font.cs 项目: axiom3d/axiom
 public void GetGlyphTexCoords(CodePoint c, out Real u1, out Real v1, out Real u2, out Real v2)
 {
     if (this.codePoints.ContainsKey(c))
     {
         var glyph = this.codePoints[c];
         u1 = glyph.uvRect.Top;
         v1 = glyph.uvRect.Left;
         u2 = glyph.uvRect.Bottom;
         v2 = glyph.uvRect.Right;
     }
     else
     {
         u1 = v1 = u2 = v2 = 0.0f;
     }
 }
示例#50
0
 public Real ForwardActivate(Real x)
 {
     return(Math.Tanh(x * 0.5) * 0.5 + 0.5);
 }
示例#51
0
            private void ProjectPolygon()
            {
                var norm = _normal;

                bool computedNormal = false;

                if (norm.X == 0.0f && norm.Y == 0.0f && norm.Z == 0.0f)
                {
                    ComputeNormal(ref norm);
                    _normal        = norm;
                    computedNormal = true;
                }

                int i = Vec3.LongAxis(ref norm);

                _sUnit[i]           = 0;
                _sUnit[(i + 1) % 3] = SUnitX;
                _sUnit[(i + 2) % 3] = SUnitY;

                _tUnit[i]           = 0;
                _tUnit[(i + 1) % 3] = norm[i] > 0.0f ? -SUnitY : SUnitY;
                _tUnit[(i + 2) % 3] = norm[i] > 0.0f ? SUnitX : -SUnitX;

                // Project the vertices onto the sweep plane
                for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
                {
                    Vec3.Dot(ref v._coords, ref _sUnit, out v._s);
                    Vec3.Dot(ref v._coords, ref _tUnit, out v._t);
                }
                if (computedNormal)
                {
                    CheckOrientation();
                }

                // Compute ST bounds.
                bool first = true;

                for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next)
                {
                    if (first)
                    {
                        _bminX = _bmaxX = v._s;
                        _bminY = _bmaxY = v._t;
                        first  = false;
                    }
                    else
                    {
                        if (v._s < _bminX)
                        {
                            _bminX = v._s;
                        }
                        if (v._s > _bmaxX)
                        {
                            _bmaxX = v._s;
                        }
                        if (v._t < _bminY)
                        {
                            _bminY = v._t;
                        }
                        if (v._t > _bmaxY)
                        {
                            _bmaxY = v._t;
                        }
                    }
                }
            }
示例#52
0
 public Real BackwardActivate(Real gy, Real y)
 {
     return(gy * y * (1.0 - y));
 }
示例#53
0
        protected override void NeedPreviousBackwardGpu(NdArray y, NdArray x)
        {
            Real[] gx          = new Real[x.Data.Length];
            Real[] activatedgy = this.Activator != null?GetActivatedgy(y) : (Real[])y.Grad;

            if (!NoBias)
            {
                CalcBiasGrad(activatedgy, y.Shape, y.BatchCount);
            }

            //gyは共通で使用
            using (ComputeBuffer <Real> gpugY = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, activatedgy))
            {
                using (ComputeBuffer <Real> gpugW = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.CopyHostPointer, this.Weight.Grad))
                    using (ComputeBuffer <Real> gpuX = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, x.Data))
                    {
                        this.BackwardgWKernel.SetMemoryArgument(0, gpugY);
                        this.BackwardgWKernel.SetMemoryArgument(1, gpuX);
                        this.BackwardgWKernel.SetMemoryArgument(2, gpugW);
                        this.BackwardgWKernel.SetValueArgument(3, y.BatchCount);
                        this.BackwardgWKernel.SetValueArgument(4, this.InputCount);
                        this.BackwardgWKernel.SetValueArgument(5, y.Length);
                        this.BackwardgWKernel.SetValueArgument(6, y.Shape[1]);
                        this.BackwardgWKernel.SetValueArgument(7, y.Shape[2]);
                        this.BackwardgWKernel.SetValueArgument(8, x.Shape[1]);
                        this.BackwardgWKernel.SetValueArgument(9, x.Shape[2]);
                        this.BackwardgWKernel.SetValueArgument(10, x.Length);
                        this.BackwardgWKernel.SetValueArgument(11, this._subSampleX);
                        this.BackwardgWKernel.SetValueArgument(12, this._subSampleY);
                        this.BackwardgWKernel.SetValueArgument(13, this._trimX);
                        this.BackwardgWKernel.SetValueArgument(14, this._trimY);
                        this.BackwardgWKernel.SetValueArgument(15, this._kHeight);
                        this.BackwardgWKernel.SetValueArgument(16, this._kWidth);

                        Weaver.CommandQueue.Execute
                        (
                            this.BackwardgWKernel,
                            null,
                            new long[] { OutputCount *InputCount, this._kHeight, this._kWidth },
                            null,
                            null
                        );

                        Weaver.CommandQueue.Finish();
                        //TODO
                        //Weaver.CommandQueue.ReadFromBuffer(gpugW, ref this.Weight.Grad, true, null);
                    }

                using (ComputeBuffer <Real> gpugX = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.WriteOnly | ComputeMemoryFlags.AllocateHostPointer, gx.Length))
                    using (ComputeBuffer <Real> gpuW = new ComputeBuffer <Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, this.Weight.Data))
                    {
                        this.BackwardgXKernel.SetMemoryArgument(0, gpugY);
                        this.BackwardgXKernel.SetMemoryArgument(1, gpuW);
                        this.BackwardgXKernel.SetMemoryArgument(2, gpugX);
                        this.BackwardgXKernel.SetValueArgument(3, this.OutputCount);
                        this.BackwardgXKernel.SetValueArgument(4, this.InputCount);
                        this.BackwardgXKernel.SetValueArgument(5, y.Length);
                        this.BackwardgXKernel.SetValueArgument(6, y.Shape[1]);
                        this.BackwardgXKernel.SetValueArgument(7, y.Shape[2]);
                        this.BackwardgXKernel.SetValueArgument(8, x.Shape[1]);
                        this.BackwardgXKernel.SetValueArgument(9, x.Shape[2]);
                        this.BackwardgXKernel.SetValueArgument(10, x.Length);
                        this.BackwardgXKernel.SetValueArgument(11, this._subSampleX);
                        this.BackwardgXKernel.SetValueArgument(12, this._subSampleY);
                        this.BackwardgXKernel.SetValueArgument(13, this._trimX);
                        this.BackwardgXKernel.SetValueArgument(14, this._trimY);
                        this.BackwardgXKernel.SetValueArgument(15, this._kHeight);
                        this.BackwardgXKernel.SetValueArgument(16, this._kWidth);

                        Weaver.CommandQueue.Execute
                        (
                            this.BackwardgXKernel,
                            null,
                            new long[] { y.BatchCount *x.Shape[0], x.Shape[1], x.Shape[2] },
                            null,
                            null
                        );

                        Weaver.CommandQueue.Finish();
                        Weaver.CommandQueue.ReadFromBuffer(gpugX, ref gx, true, null);
                    }
            }

            for (int i = 0; i < x.Grad.Length; i++)
            {
                x.Grad[i] += gx[i];
            }
        }
示例#54
0
 /// <summary>
 /// Gets the position of a point t units along the ray.
 /// </summary>
 /// <param name="t"></param>
 /// <returns></returns>
 public Vector3 GetPoint(Real t)
 {
     return(origin + (direction * t));
 }
示例#55
0
 public Degree(Degree d)
 {
     this._value = d._value;
 }
示例#56
0
 private Degree(SerializationInfo info, StreamingContext context)
 {
     this._value = (Real)info.GetValue("value", typeof(Real));
 }
示例#57
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="menu"></param>
		public virtual void ItemSelected( SelectMenu menu )
		{
			if ( menu == this.CategoryMenu ) // category changed, so update the sample menu, carousel, and slider
			{
				for ( int i = 0; i < this.Thumbs.Count; i++ ) // destroy all thumbnails in carousel
				{
					MaterialManager.Instance.Remove( this.Thumbs[ i ].Name );
					Widget.NukeOverlayElement( this.Thumbs[ i ] );
				}
				this.Thumbs.Clear();

				OverlayManager om = OverlayManager.Instance;
				String selectedCategory = string.Empty;

				if ( menu.SelectionIndex != -1 )
				{
					selectedCategory = menu.SelectedItem;
				}
				else
				{
					this.TitleLabel.Caption = "";
					this.DescBox.Text = "";
				}

				bool all = selectedCategory == "All";
				var sampleTitles = new List<string>();
				var templateMat = (Material)MaterialManager.Instance.GetByName( "SampleThumbnail" );

				// populate the sample menu and carousel with filtered samples
				foreach ( Sample i in this.LoadedSamples )
				{
					Collections.NameValuePairList info = i.Metadata;

					if ( all || info[ "Category" ] == selectedCategory )
					{
						String name = "SampleThumb" + sampleTitles.Count + 1;

						// clone a new material for sample thumbnail
						Material newMat = templateMat.Clone( name );

						TextureUnitState tus = newMat.GetTechnique( 0 ).GetPass( 0 ).GetTextureUnitState( 0 );
						if ( ResourceGroupManager.Instance.ResourceExists( "Essential", info[ "Thumbnail" ] ) )
						{
							tus.SetTextureName( info[ "Thumbnail" ] );
						}
						else
						{
							tus.SetTextureName( "thumb_error.png" );
						}

						// create sample thumbnail overlay
						var bp =
							(Overlays.Elements.BorderPanel)om.Elements.CreateElementFromTemplate( "SdkTrays/Picture", "BorderPanel", name );
						bp.HorizontalAlignment = HorizontalAlignment.Right;
						bp.VerticalAlignment = VerticalAlignment.Center;
						bp.MaterialName = name;
						bp.UserData = i;
						this.TrayManager.TraysLayer.AddElement( bp );

						// add sample thumbnail and title
						this.Thumbs.Add( bp );
						sampleTitles.Add( i.Metadata[ "Title" ] );
					}
				}

				this.CarouselPlace = 0; // reset carousel

				this.SampleMenu.Items = sampleTitles;
				if ( this.SampleMenu.ItemsCount != 0 )
				{
					ItemSelected( this.SampleMenu );
				}

				this.SampleSlider.SetRange( 1, sampleTitles.Count, sampleTitles.Count );
			}
			else if ( menu == this.SampleMenu ) // sample changed, so update slider, label and description
			{
				if ( this.SampleSlider.Value != menu.SelectionIndex + 1 )
				{
					this.SampleSlider.Value = menu.SelectionIndex + 1;
				}

				var s = (Sample)( this.Thumbs[ menu.SelectionIndex ].UserData );
				this.TitleLabel.Caption = menu.SelectedItem;
				this.DescBox.Text = "Category: " + s.Metadata[ "Category" ] + "\nDescription: " + s.Metadata[ "Description" ];

				if ( CurrentSample != s )
				{
					( (Button)this.TrayManager.GetWidget( "StartStop" ) ).Caption = "Start Sample";
				}
				else
				{
					( (Button)this.TrayManager.GetWidget( "StartStop" ) ).Caption = "Stop Sample";
				}
			}
			else if ( menu == this.RendererMenu ) // renderer selected, so update all settings
			{
				while ( this.TrayManager.GetWidgetCount( this.RendererMenu.TrayLocation ) > 3 )
				{
					this.TrayManager.DestroyWidget( this.RendererMenu.TrayLocation, 3 );
				}

				var options = Root.RenderSystems[ menu.SelectionIndex ].ConfigOptions;

				int i = 0;

				// create all the config option select menus
				foreach ( Configuration.ConfigOption it in options )
				{
					SelectMenu optionMenu = this.TrayManager.CreateLongSelectMenu( TrayLocation.Left, "ConfigOption" + i++, it.Name,
					                                                               450,
					                                                               240, 10 );
					optionMenu.Items = (List<string>)it.PossibleValues.Values.ToList();

					// if the current config value is not in the menu, add it
					try
					{
						optionMenu.SelectItem( it.Value );
					}
					catch ( Exception )
					{
						optionMenu.AddItem( it.Value );
						optionMenu.SelectItem( it.Value );
					}
				}

				WindowResized( RenderWindow );
			}
		}
示例#58
0
 public Degree(Radian r)
 {
     this._value = r.InDegrees;
 }
示例#59
0
		/// <summary>
		///    Sets a level-of-detail bias for the material detail of this entity.
		/// </summary>
		/// <remarks>
		///    Level of detail reduction is normally applied automatically based on the Material
		///    settings. However, it is possible to influence this behavior for this entity
		///    by adjusting the LOD bias. This 'nudges' the material level of detail used for this
		///    entity up or down depending on your requirements. You might want to use this
		///    if there was a particularly important entity in your scene which you wanted to
		///    detail better than the others, such as a player model.
		///    <p/>
		///    There are three parameters to this method; the first is a factor to apply; it
		///    defaults to 1.0 (no change), by increasing this to say 2.0, this model would
		///    take twice as long to reduce in detail, whilst at 0.5 this entity would use lower
		///    detail versions twice as quickly. The other 2 parameters are hard limits which
		///    let you set the maximum and minimum level-of-detail version to use, after all
		///    other calculations have been made. This lets you say that this entity should
		///    never be simplified, or that it can only use LODs below a certain level even
		///    when right next to the camera.
		/// </remarks>
		/// <param name="factor">Proportional factor to apply to the distance at which LOD is changed.
		///    Higher values increase the distance at which higher LODs are displayed (2.0 is
		///    twice the normal distance, 0.5 is half).</param>
		/// <param name="maxDetailIndex">The index of the maximum LOD this entity is allowed to use (lower
		///    indexes are higher detail: index 0 is the original full detail model).</param>
		/// <param name="minDetailIndex">The index of the minimum LOD this entity is allowed to use (higher
		///    indexes are lower detail. Use something like 99 if you want unlimited LODs (the actual
		///    LOD will be limited by the number in the material)</param>
		public void SetMaterialLodBias( Real factor, int maxDetailIndex, int minDetailIndex )
		{
			Debug.Assert( factor > 0.0f, "Bias factor must be > 0!" );
			this.materialLodFactor = factor;
			this.materialLodFactorTransformed = this.mesh.LodStrategy.TransformBias( factor );
			this.maxMaterialLodIndex = maxDetailIndex;
			this.minMaterialLodIndex = minDetailIndex;
		}
示例#60
0
        public static AxisAlignedBox2 FromRect(Vector2 min, Real w, Real h)
        {
            var max = new Vector2(w, h) + min;

            return(new AxisAlignedBox2(min, max));
        }