• Main Page
  • Packages
  • Classes
  • Files
  • File List

trunk/visLU/FlowData.cs

Go to the documentation of this file.
00001 #region Using Statements
00002 using System;
00003 using System.Text.RegularExpressions;
00004 using System.Collections.Generic;
00005 using System.Linq;
00006 using System.Text;
00007 using System.IO;
00008 using Microsoft.Xna.Framework;
00009 using Microsoft.Xna.Framework.Audio;
00010 using Microsoft.Xna.Framework.Content;
00011 using Microsoft.Xna.Framework.GamerServices;
00012 using Microsoft.Xna.Framework.Graphics;
00013 using Microsoft.Xna.Framework.Input;
00014 using Microsoft.Xna.Framework.Media;
00015 using Microsoft.Xna.Framework.Net;
00016 using Microsoft.Xna.Framework.Storage;
00017 using Microsoft.Xna.Framework.Graphics.PackedVector;
00018 using visLU2.Effects;
00019 #endregion
00020 
00021 
00022 namespace visLU2
00023 {
00024     class FlowData: DrawableGameComponent
00025     {
00026         private Game game;
00027         private GraphicsDevice device;
00028         private SpriteBatch spriteBatch;
00029         private FlowShader shader;
00030 
00031         private string griFileName;
00032         private List<string> datFileNames;
00033 
00034         #region flow data header
00035         //header information
00036         string headerName;
00037         int sizeX, sizeY, sizeZ; //==SX, SY, SZ in the file header definition
00038         int channelNumber; // == NF 
00039         int timestepNumber; // == NT
00040         float timestepDuration; // == DT
00041         #endregion
00042 
00043         #region flow data geometry
00044         //min and max vertex values in this geometry data, size = max - min
00045         Vector2 boundaryMin;
00046         Vector2 boundaryMax;
00047         Vector2 boundaryLength;
00048         //save all vertices in the grid
00049         Vector2[] gridData;
00050         Vector2[] normalizedGridData;
00051 
00052         //if the x and y axes have to be swaped
00053         bool isFlipped = false;
00054         bool bigEndian = false;
00055         #endregion
00056 
00057         #region flow data channels
00058         //all channels data, 
00059         //each element in the array represents all channels in a single time step(the next time step)
00060         // == channelData[i] storage channels from a single .dat file
00061         FlowChannel[] channelData; 
00062         #endregion
00063 
00064         #region vertex buffer
00065         Camera camera;
00066         BasicEffect basicEffect;
00067         BasicEffect basicEffect2;
00068         Matrix world;
00069 
00070         VertexDeclaration vertexDeclr; //custom vertex declaration
00071         VertexBuffer vertexBuffer; //stores mesh vertices 
00072         IndexBuffer indexBuffer; //and mesh indices
00073         
00074         GridVertices[] meshVertices; //mesh vertices in custom format
00075         int[] meshIndices; //mesh indices
00076         #endregion
00077 
00078         #region other variables
00079         int currTimeStep = 0;
00080         public List<TransferControlPoint> colorControlPoints;
00081         private Texture2D transferTexture;
00082         bool initialControPoints = true;
00083 
00084         Texture2D arrow;
00085         ArrowPlot arrowPlot;
00086         RenderTarget2D arrowTarget;
00087         Texture2D arrowsTexture;
00088         DepthStencilBuffer stencilArrow;
00089         VertexBuffer vertexBuffer_arrow; //stores mesh vertices 
00090         IndexBuffer indexBuffer_arrow; //and mesh indices
00091         int[] arrowIndices;
00092         VertexPositionTexture[] verticeArray_arrows;
00093         float stepsizeX = 0.8f;
00094         float stepsizeY = 0.8f;
00095         float minMagnitude;
00096         float maxMagnitude;
00097         DepthStencilBuffer stencilData;
00098         #endregion
00099 
00100         #region streamline variables
00101         private float dt = 0.1f;//TODO: move to Streamlines
00102         Streamlines streamlines_euler;
00103         Streamlines streamlines_rungeKutta;
00104         int startSeedPointSearchAtIndex = 0;
00105         CartesianGrid cGrid;
00106         #endregion
00107 
00108         #region Properties
00109         public Camera Camera
00110         {
00111             set { camera = value; }
00112             get { return camera; }
00113         }
00114 
00115         public Vector2 BoundaryLength
00116         {
00117             get { return boundaryLength; }
00118         }
00119         public Vector2 BoundaryMin
00120         {
00121             get { return boundaryMin; }
00122         }
00123         public Vector2 BoundaryMax
00124         {
00125             get { return boundaryMax; }
00126         }
00127         #endregion
00128 
00129         #region Constructor
00130         public FlowData(string rootFileName, bool relativePath, Game game)
00131             : base(game)
00132         {
00133 
00134             this.game = game;
00135             colorControlPoints = new List<TransferControlPoint>();
00136 
00137             if (relativePath)
00138             {
00139 
00140                 string a = "" + Directory.GetParent((string)Directory.GetCurrentDirectory());
00141                 string b = "" + Directory.GetParent(a);
00142                 string c = "" + Directory.GetParent(b);
00143 
00144                 //get .gri file
00145                 griFileName = c + "\\" + rootFileName;
00146             }
00147             else 
00148             {
00149                 griFileName = rootFileName;
00150             }
00151 
00152             if (string.IsNullOrEmpty(griFileName))
00153             {
00154                 throw new ArgumentNullException(griFileName);
00155             }
00156 
00157             if (!File.Exists(griFileName))
00158             {
00159                 Console.WriteLine(griFileName);
00160                 throw new ArgumentException("file not found: " + griFileName);
00161             }
00162 
00163             //get all add .dat files
00164             datFileNames = new List<string>();
00165             DirectoryInfo currDir = Directory.GetParent(griFileName);
00166             string filename = griFileName.Substring((griFileName.LastIndexOf("\\") + 1));
00167             filename = filename.Substring(0,(filename.Length - 4));
00168             FileInfo[] datFileNamesTmp = currDir.GetFiles("*.dat");
00169            
00170 
00171             foreach (FileInfo datFileNextTmp in datFileNamesTmp)
00172             {
00173                 //string [] extractName = datFileNextTmp.Name.Split('.');
00174                 if (datFileNextTmp.Name.Split('.')[0].Equals(filename))
00175                 {
00176                     datFileNames.Add(currDir + "\\" + datFileNextTmp.Name);
00177                 }
00178             }
00179 
00180             if (datFileNames.Count() == 0)
00181             {
00182                 throw new ArgumentException(".dat files are missing");
00183             }
00184 
00185             datFileNames.Sort();
00186 
00187         }
00188         #endregion
00189 
00190         #region Initialize
00191 
00192 
00193 
00194 
00195 
00196         public override void Initialize()
00197         {
00198             spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
00199             if (spriteBatch == null)
00200                 throw new InvalidOperationException("SpriteBatch Service not found");
00201 
00202             device = Game.GraphicsDevice;
00203 
00204             base.Initialize();
00205         }
00206         #endregion
00207 
00208         #region LoadContent
00209 
00210 
00211 
00212         protected override void LoadContent()
00213         {
00214 
00215             loadDatafromFile();
00216             //createUniformGrid();
00217 
00218             #region initialize control points and channels
00219             //init gui information
00220             if (GameProperties.Instance.channelControlPoints.Count() > 0) GameProperties.Instance.channelControlPoints.Clear();
00221             if (GameProperties.Instance.channelNames.Count() > 0) GameProperties.Instance.channelNames.Clear();
00222             switch (GameProperties.Instance.dataFilename.Substring(GameProperties.Instance.dataFilename.LastIndexOf("\\") + 1))
00223             {
00224                 case "c_block.gri":
00225                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.blockDataChannels[0]);
00226                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.blockDataChannels[1]);
00227                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.blockDataChannels[2]);
00228                     break;
00229                 case "hurricane_p_tc_singletime48.gri":
00230                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.hurricaneDataChannels[0]);
00231                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.hurricaneDataChannels[1]);
00232                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.hurricaneDataChannels[2]);
00233                     break;
00234                 case "hurricane_p_tc_singletime10.gri":
00235                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.hurricaneDataChannels[0]);
00236                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.hurricaneDataChannels[1]);
00237                     GameProperties.Instance.channelNames.Add(GameProperties.Instance.hurricaneDataChannels[2]);
00238                     break;
00239                 default:
00240                     GameProperties.Instance.channelNames.Add("Channel 1");
00241                     GameProperties.Instance.channelNames.Add("Channel 2");
00242                     GameProperties.Instance.channelNames.Add("Channel 3");
00243                     break;
00244             }
00245             GameProperties.Instance.currentChannelIdx = 0;
00246 
00247             //set initial control points for the arrow plot
00248             if (GameProperties.Instance.arrowControlPoints.Count() > 0) GameProperties.Instance.arrowControlPoints.Clear();
00249             GameProperties.Instance.arrowControlPoints.Add(new TransferControlPoint(255, 255, 130, 0));
00250             GameProperties.Instance.arrowControlPoints.Add(new TransferControlPoint(200, 0, 0, 130));
00251             GameProperties.Instance.arrowControlPoints.Add(new TransferControlPoint(130, 255, 255, 256));
00252             GameProperties.Instance.arrowColorArray = new Color[256];
00253 
00254             //set initial control points and 
00255             //init color array for each channel
00256             if (GameProperties.Instance.colorArray.Count() > 0) GameProperties.Instance.colorArray.Clear();
00257             for (int i = 0; i < GameProperties.Instance.channelNames.Count(); i++)
00258             {
00259                 List<TransferControlPoint> cpList = new List<TransferControlPoint>();
00260                 cpList.Add(new TransferControlPoint(255, 255, 130, 0));
00261                 cpList.Add(new TransferControlPoint(200, 0, 0, 130));
00262                 cpList.Add(new TransferControlPoint(130, 255, 255, 256));
00263                 GameProperties.Instance.channelControlPoints.Add(cpList);
00264                 GameProperties.Instance.colorArray.Add(new Color[256]);
00265             }
00266             initialControPoints = true;
00267             #endregion
00268 
00269             #region initialize vertex buffer
00270             //load vertex declaration for custom vertex format GridVertices
00271             vertexDeclr = new VertexDeclaration(GraphicsDevice, GridVertices.VertexElements);
00272 
00273             basicEffect = new BasicEffect(GraphicsDevice, null);
00274             basicEffect2 = new BasicEffect(GraphicsDevice, null);
00275             //basicEffect.VertexColorEnabled = true;
00276             Effect flowEffect = Game.Content.Load<Effect>("Effects\\flowShader");
00277             shader = new FlowShader(Game, GraphicsDevice, flowEffect);
00278             world = Matrix.Identity;
00279             #region depricated (scale to window width or height)
00280             /*float scaleValue = Math.Max(boundaryLength.X, boundaryLength.Y);
00281 
00282             //float scaleHeight = GameProperties.Instance.XNADrawSurfaceHeight / scaleValue;
00283             //float scaleWidth = GameProperties.Instance.XNADrawSurfaceWidth / scaleValue;
00284 
00285             Console.WriteLine("scaleValue=" + scaleValue);
00286             scaleValue = (GameProperties.Instance.XNADrawSurfaceHeight/65.0f) / scaleValue;
00287             Console.WriteLine("boundaryMax.X="+boundaryMax.X+ " boundaryMax.Y=" + boundaryMax.Y +
00288                 " scaleValue=" + scaleValue + " window=" +
00289                 GameProperties.Instance.XNADrawSurfaceHeight);*/
00290             #endregion
00291 
00292             generateGridMesh();
00293             #endregion
00294 
00295             initalizeArrowPlot();
00296 
00297             initalizeStreamlines();
00298           
00299             base.LoadContent();
00300         }
00301 
00302         #region initialize Streamlines
00303         private void initalizeStreamlines()
00304         {
00305             // create Cartesian Grid for stream line sample points:
00306             
00307             //stepsizeX = boundaryLength.X / GameProperties.Instance.apStepsize;
00308             //stepsizeY = boundaryLength.Y / GameProperties.Instance.apStepsize;
00309 
00310             GameProperties.Instance.maxLineLength = (int)MathHelper.Max(boundaryLength.X, boundaryLength.Y);
00311             GameProperties.Instance.maxDsep = (int)(MathHelper.Max(boundaryLength.X, boundaryLength.Y));
00312             GameProperties.Instance.Dt = 0.01f;
00313             GameProperties.Instance.Dsep = GameProperties.Instance.maxDsep * 0.1f;
00314             GameProperties.Instance.Dtest = GameProperties.Instance.Dsep * 0.15f;
00315             GameProperties.Instance.lineWidth = GameProperties.Instance.Dtest * 0.5f;
00316               
00317         }
00318 
00319 
00320 
00321         #region SeedPoints
00322         private Vector2 findNewSeedPoint(Streamlines streamelines)
00323         {
00324             Vector2 seedPoint;
00325             bool accept = false;
00326             // start at first streamline where there are still seed points possible
00327             for (int k = startSeedPointSearchAtIndex; k < streamelines.StreamlineList.Count; k++)
00328             {
00329                 Streamline line = streamelines.StreamlineList[k];
00330                 #region search for seed point next to line
00331                 for (int i = line.StartSeedPointSearchAtIndex; i < line.Points.Count-1; i++)
00332                 {
00333                     Vector2 currentPosition = line.Points[i];
00334                     Vector2 direction = line.Points[i + 1] - currentPosition;
00335                     Vector2 normal = new Vector2(direction.Y, -direction.X);
00336                     normal.Normalize();
00337 
00338                     // - X
00339                     seedPoint = currentPosition + (normal * streamelines.Dsep);
00340                     accept = acceptSeedPoint(streamelines, line, seedPoint);
00341                     if (accept)
00342                     {
00343                         line.setStartSeedPointSearchAtIndex(i);
00344                         streamelines.StreamlineList[k] = line;
00345                         return seedPoint;
00346                     }
00347 
00348                     // - Y
00349                     seedPoint = currentPosition - (normal * streamelines.Dsep);
00350                     accept = acceptSeedPoint(streamelines, line, seedPoint);
00351                     if (accept)
00352                     {
00353                         line.setStartSeedPointSearchAtIndex(i);
00354                         streamelines.StreamlineList[k] = line; 
00355                         return seedPoint;
00356                     }
00357                 }
00358                 #endregion
00359                 startSeedPointSearchAtIndex++;
00360             }
00361             return new Vector2(-1000.0f, -1000.0f); // no more seed points possible!
00362         }
00363 
00364         private bool acceptSeedPoint(Streamlines streamlines, Streamline line, Vector2 position)
00365         {
00374             // seed point leaves flow domain
00375             if ((position.X > gridData[gridData.Length - 1].X) || (position.Y > gridData[0].Y)
00376                 || (position.X < gridData[0].X) || (position.Y < gridData[gridData.Length - 1].Y))
00377             {
00378                 return false;
00379             }
00380 
00381             // seed point is fixed point (v=0)
00382             Vector3 velocity = getInterpolatedVector(position.X, position.Y);
00383             if ((velocity.X == 0.0f) || (velocity.Y == 0.0f))
00384             {
00385                 return false;
00386             }
00387 
00388             // dist. to neighboring streamline ≤ DSep
00389             //check all previous lines
00390             for (int i = 0; i < streamlines.StreamlineList.Count; i++)
00391             {
00392                 //compare to every point of every line
00393                 for (int j = 0; j < streamlines.StreamlineList[i].Points.Count; j++)
00394                 {
00395                     float dist = Vector2.Distance(position, streamlines.StreamlineList[i].Points[j]);
00396                     if (dist < streamlines.Dtest)
00397                     {
00398                         return false;
00399                     }
00400                 }
00401             }
00402 
00403             return true;
00404         }
00405         #endregion SeedPoints
00406 
00407         private Boolean streamlineStop(int index, Vector2 position, Streamline line)
00408         {
00419             // streamline leaves flow domain
00420             if ((position.X > gridData[gridData.Length - 1].X) || (position.Y > gridData[0].Y)
00421                 || (position.X < gridData[0].X) || (position.Y < gridData[gridData.Length - 1].Y))
00422             {
00423                 return true;
00424             }
00425 
00426             // after a certain amount of maximal steps
00427             if (line.Points.Count*dt > streamlines_euler.MaxLength)
00428             {
00429                 return true;
00430             }
00431 
00432             // streamline runs into fixed point (v=0)
00433             Vector3 velocity = getInterpolatedVector(position.X, position.Y);
00434             if ((velocity.X == 0.0f)||(velocity.Y == 0.0f))
00435             {
00436                 return true;
00437             }
00438 
00439             // dist. to neighboring streamline ≤ dtest
00440             List<SamplePoint> pointsToCheck = cGrid.getPointsToCheck(position);
00441             //compare to every point in surrounding cells!
00442             for (int i = 0; i < pointsToCheck.Count; i++)
00443             {
00444 
00445                 float dist = Vector2.Distance(position, pointsToCheck[i].Position);
00446                 if (pointsToCheck[i].StreamLineIndex == index)
00447                 {
00448                     
00449                     //streamlines.StreamlineList[index].Points
00450                     if (dist < dt*0.75f)
00451                     {
00452                         return true;
00453                     }
00454                     continue;
00455                     /*// streamline gets too near to itself
00456                     int countNearestPoints = (int)(streamlines.Dtest / dt) * 2;
00457                     float dist = Vector2.Distance(line.Points[i], position);
00458                     if ((i < countNearestPoints) && (dist < streamlines.Dtest))
00459                     {
00460                         return true;
00461                     }
00462                     if ((i >= countNearestPoints) && (dist < 2 * dt))
00463                     {
00464                         return true;
00465                     }*/
00466                     
00467                 }
00468                 //float dist = Vector2.Distance(position, pointsToCheck[i].Position);
00469                 if (dist < streamlines_euler.Dtest)
00470                 {
00471                     return true;
00472                 }
00473             }
00474 
00475             return false;
00476         }
00477 
00478         private float calculateTickness(Vector2 position)
00479         {
00480             float tickness = 1.0f;
00481 
00482             float dist = 10000; //get distance to the closest streamline
00483 
00484             List<SamplePoint> pointsToCheck = cGrid.getPointsToCheck(position);
00485             //compare to every point in surrounding cells!
00486             for (int i = 0; i < pointsToCheck.Count; i++)
00487             {
00488                 float dist1 = Vector2.Distance(position, pointsToCheck[i].Position);
00489                 dist = Math.Min(dist, dist1);
00490             }
00491 
00492             if (dist < GameProperties.Instance.Dsep)
00493             {
00494                 tickness = (dist - GameProperties.Instance.Dtest) / (GameProperties.Instance.Dsep - GameProperties.Instance.Dtest);
00495             }
00496             else
00497             {
00498                 tickness = 1.0f;
00499             }
00500 
00501             return tickness;
00502         }
00503         #endregion
00504 
00505        
00506 
00507 
00512         private void loadDatafromFile()
00513         {
00514             //bigEndian = !BitConverter.IsLittleEndian;
00515             //reverse byte order if bigEndian = true
00516 
00517             #region read .gri
00518 
00519             Stream file = new FileStream(griFileName, FileMode.Open);
00520             BinaryReader reader = new BinaryReader(file);
00521 
00522             #region read header
00523             byte[] headerBuffer = new byte[40];
00524             reader.Read(headerBuffer, 0, 40);
00525 
00526             string header = System.Text.ASCIIEncoding.ASCII.GetString(headerBuffer);
00527      
00528             Regex stringSeq = new Regex("[a-zA-Z0-9]+");
00529             Regex positiveInt = new Regex("0*[1-9][0-9]*");
00530             Regex positiveFloat = new Regex("[0-9]+[.][0-9]*");
00531             Regex emptySpace = new Regex(" ");
00532 
00533             int pos = 0;
00534 
00535             try
00536             {
00537                 Match match_strName = stringSeq.Match(header, pos);
00538                 if (match_strName.Success)
00539                 {
00540                     headerName = match_strName.ToString();
00541                     pos += match_strName.Length;
00542                 }
00543 
00544                 if (emptySpace.Match(header, pos).Success) { pos++; }
00545 
00546 
00547                 Match match_strX = positiveInt.Match(header, pos);
00548                 if (match_strX.Success)
00549                 {
00550                     sizeX = int.Parse(match_strX.ToString());
00551                     pos += match_strX.Length;
00552                 }
00553 
00554                 if (emptySpace.Match(header, pos).Success) { pos++; }
00555 
00556                 Match match_strY = positiveInt.Match(header, pos);
00557                 if (match_strY.Success)
00558                 {
00559                     sizeY = int.Parse(match_strY.ToString());
00560                     pos += match_strY.Length;
00561                 }
00562 
00563                 if (emptySpace.Match(header, pos).Success) { pos++; }
00564 
00565                 Match match_strZ = positiveInt.Match(header, pos);
00566                 if (match_strZ.Success)
00567                 {
00568                     sizeZ = int.Parse(match_strZ.ToString());
00569                     pos += match_strZ.Length;
00570                 }
00571 
00572                 if (emptySpace.Match(header, pos).Success) { pos++; }
00573 
00574                 Match match_strNumber1 = positiveInt.Match(header, pos);
00575                 if (match_strNumber1.Success)
00576                 {
00577                     channelNumber = int.Parse(match_strNumber1.ToString());
00578                     pos += match_strNumber1.Length;
00579                 }
00580 
00581                 if (emptySpace.Match(header, pos).Success) { pos++; }
00582 
00583                 Match match_strNumber2 = positiveInt.Match(header, pos);
00584                 if (match_strNumber2.Success)
00585                 {
00586                     timestepNumber = int.Parse(match_strNumber2.ToString());
00587                     pos += match_strNumber2.Length;
00588                 }
00589 
00590                 if (emptySpace.Match(header, pos).Success) { pos++; }
00591 
00592                 Match match_strDur = positiveFloat.Match(header, pos);
00593                 if (match_strDur.Success)
00594                 {
00595                     timestepDuration = float.Parse(match_strDur.ToString());
00596                     pos += match_strDur.Length;
00597                 }
00598 
00599             }catch(Exception e)
00600             
00601             {
00602                 Console.WriteLine("Some header information is missing");
00603             }
00604 
00605             #endregion
00606 
00607             #region read geometry data
00608             gridData = new Vector2[sizeX * sizeY];
00609             int nextPos = 0;
00610             try
00611             {
00612 
00613                 for (int y = 0; y < sizeY; y++)
00614                 {
00615                     for (int x = 0; x < sizeX; x++)
00616                     {
00617                   
00618                         gridData[nextPos].X = BitConverter.ToSingle(reader.ReadBytes(4), 0);
00619                         gridData[nextPos].Y = BitConverter.ToSingle(reader.ReadBytes(4), 0);
00620                         float Z_unused = BitConverter.ToSingle(reader.ReadBytes(4), 0);
00621 
00622                         nextPos++;
00623 
00624                     }
00625                 }
00626 
00627             }
00628             catch (EndOfStreamException e)
00629             {
00630                 Console.WriteLine(e.Message);
00631             }
00632             finally
00633             {
00634                 reader.Close();
00635                 file.Close();
00636             }
00637 
00638             #endregion
00639              
00640             reader.Close();
00641             file.Close();
00642             #endregion
00643 
00644             #region initialize dimensions
00645             int firstIdx = 0;
00646             int lastIdx = (sizeX * sizeY) - 1;
00647             boundaryMin = gridData[firstIdx];
00648             boundaryMax = gridData[lastIdx];
00649             boundaryLength = boundaryMax - boundaryMin;
00650 
00651 
00652             //if X and Y are swapped... meaning that going in a row the y value increases and x stays the same
00653             if (gridData[sizeX - 1].Y > (boundaryMin.Y + boundaryMax.Y) * 0.5)
00654             {
00655                 isFlipped = true;
00656                 for (int i = 0; i < gridData.Length; i++)
00657                 {
00658                     float x = gridData[i].X;
00659                     float y = gridData[i].Y;
00660                     gridData[i].X = y;
00661                     gridData[i].Y = x;
00662                 }
00663             }
00664             else isFlipped = false;
00665 
00666             #endregion
00667 
00668             #region read .dat
00669             channelData = new FlowChannel[datFileNames.Count];
00670             channelNumber += 1; //store velocity magnitude as channel too
00671 
00672             for (int i = 0; i < datFileNames.Count; i++)
00673             {
00674                 channelData[i] = new FlowChannel(sizeX, sizeY, channelNumber, i);
00675             }
00676 
00677             for(int i = 0; i < datFileNames.Count; i++)
00678             {
00679                 Stream datFile = new FileStream(datFileNames[i], FileMode.Open);
00680                 BinaryReader datReader = new BinaryReader(datFile);
00681 
00682                 Vector3 minVelocity = new Vector3();
00683                 Vector3 maxVelocity = new Vector3();
00684                 float[] minChannel = new float[channelNumber];
00685                 float[] maxChannel = new float[channelNumber];
00686                 bool firstLoop = true;
00687                 bool firstInnerLoop = true;
00688                 int nextPos1 = 0;
00689                 for (int y = 0; y < sizeY; y++)
00690                     {
00691                         for (int x = 0; x < sizeX; x++)
00692                         {
00693 
00694                             Vector3 velocity = new Vector3();
00695                             if (isFlipped)
00696                             {
00697                                 velocity.Y = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
00698                                 velocity.X = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
00699                             }
00700                             else 
00701                             {
00702                                 velocity.X = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
00703                                 velocity.Y = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
00704                             }
00705                             velocity.Z = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
00706 
00707                             channelData[i].Velocity.VelocityValues[nextPos1] = velocity;
00708 
00709                             if (!firstLoop)
00710                             {
00711                                 minVelocity = Vector3.Min(minVelocity, velocity);
00712                                 maxVelocity = Vector3.Max(maxVelocity, velocity);
00713                                 minMagnitude = MathHelper.Min(velocity.Length(), minMagnitude);
00714                                 maxMagnitude = MathHelper.Max(velocity.Length(), maxMagnitude);
00715                             }
00716                             else 
00717                             {
00718                                 minVelocity = velocity;
00719                                 maxVelocity = velocity;
00720                                 minMagnitude = MathHelper.Min(velocity.Length(), minMagnitude);
00721                                 maxMagnitude = MathHelper.Max(velocity.Length(), maxMagnitude);
00722                                 firstLoop = false;
00723                             }
00724 
00725                             for (int j = 0; j < channelNumber; j++)
00726                             {
00727                                 float channelVal;
00728                                 if (j == 0)
00729                                 {
00730                                     channelVal = velocity.Length(); //velocity magnitude
00731                                 }
00732                                 else 
00733                                 {
00734                                     channelVal = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
00735                                 }
00736                                 channelData[i].AddChannels[j].ChannelValues[nextPos1] = channelVal;
00737                                 if (!firstInnerLoop)
00738                                 {
00739                                     minChannel[j] = Math.Min(minChannel[j], channelVal);
00740                                     maxChannel[j] = Math.Max(maxChannel[j], channelVal);
00741                                 }
00742                                 else 
00743                                 {
00744                                     minChannel[j] = channelVal;
00745                                     maxChannel[j] = channelVal;
00746                                     firstInnerLoop = false;
00747                                 }
00748                             }//end channel loop
00749 
00750                             nextPos1++;
00751                         }
00752 
00753                         
00754                     }//end current file loop  
00755 
00756               
00757                 channelData[i].setMinVelocity(minVelocity);
00758                 channelData[i].setMaxVelocity(maxVelocity);
00759                 for (int j = 0; j < channelNumber; j++)
00760                 {
00761                     channelData[i].setChannelMinVal(j,minChannel[j]);
00762                     channelData[i].setChannelMaxVal(j,maxChannel[j]);
00763                 }
00764                 firstLoop = true;
00765                 firstInnerLoop = true;
00766 
00767                 datReader.Close();
00768                 datFile.Close();
00769             }//end outer loop
00770 
00771             #endregion
00772 
00773             
00774 
00775         }
00776 
00777         #region grid
00778 
00779 
00780 
00781 
00782         private void generateGridMesh()
00783         {
00784             int vertCount = sizeX * sizeY;
00785             int trianglesCount = (sizeX - 1) * (sizeY - 1) * 2;
00786 
00787             //generate indices
00788             meshIndices = generateMeshIndices(trianglesCount);
00789             indexBuffer = new IndexBuffer(device, trianglesCount * 3 * sizeof(int), BufferUsage.WriteOnly, IndexElementSize.ThirtyTwoBits);
00790             indexBuffer.SetData<int>(meshIndices);
00791 
00792             //generate vertices
00793             //meshVertices = generateTestVertices();
00794             meshVertices = generateMeshVertices();
00795             vertexBuffer = new VertexBuffer(GraphicsDevice, vertCount * GridVertices.SizeInBytes, BufferUsage.WriteOnly);
00796             vertexBuffer.SetData<GridVertices>(meshVertices);
00797 
00798         }
00799 
00805         private int[] generateMeshIndices(int trianglesCount)
00806         {
00807             int[] meshIndices = new int[trianglesCount * 3];
00808             int nextIdx = 0;
00809 
00810             for (int row = 0; row < (sizeY-1); row++)
00811             {
00812                 for (int col = 0; col < (sizeX-1); col++)
00813                 {
00814                     int idx = col + row * sizeX;
00815 
00816                     meshIndices[nextIdx++] = idx;
00817                     meshIndices[nextIdx++] = idx + 1;
00818                     meshIndices[nextIdx++] = idx + sizeX + 1;
00819                     meshIndices[nextIdx++] = idx + sizeX + 1;
00820                     meshIndices[nextIdx++] = idx + sizeX;
00821                     meshIndices[nextIdx++] = idx;
00822 
00823                 }
00824             }
00825             return meshIndices;
00826 
00827         }
00828 
00835         private GridVertices[] generateMeshVertices()
00836         {
00837             GridVertices[] meshVert = new GridVertices[sizeX * sizeY];
00838             for (int i = 0; i < sizeX * sizeY; i++)
00839             {
00840                 //convert to xna vertex coord system
00841                 gridData[i].Y = boundaryMin.Y + boundaryLength.Y - gridData[i].Y;
00842                 //gridData[i].Y = gridData[i].Y * (-1.0f);
00843                 meshVert[i].Position = gridData[i];
00844                 meshVert[i].Velocity = channelData[currTimeStep].Velocity.VelocityValues[i];
00845                 meshVert[i].AddChannels = new Vector3(
00846                     channelData[currTimeStep].AddChannels[0].NormValues[i], //velocity magnitude
00847                     channelData[currTimeStep].AddChannels[1].NormValues[i],
00848                     channelData[currTimeStep].AddChannels[2].NormValues[i]);
00849             }
00850 
00851             //meshVert = generateTextureCoord(meshVert);  
00852             //meshVert = generateNormals(meshIndices, meshVert);
00853             return meshVert;
00854 
00855         }
00856 
00857         private GridVertices[] generateTestVertices()
00858         {
00859             GridVertices[] meshVert = new GridVertices[sizeX * sizeY];
00860 
00861             int nextVert = 0;
00862             for (float row = 0; row <= sizeY; row +=3)
00863             {
00864                 for (float col = 0; col <=sizeX; col += 2.0f)
00865                 {
00866                     
00867                     meshVert[nextVert].Position = new Vector2(col, row);
00868                     //meshVert[i].Velocity = channelData[currTimeStep].Velocity.VelocityValues[i];
00869                     //meshVert[i].AddChannels = new Vector2(channelData[currTimeStep].AddChannels[0].ChannelValues[i], channelData[currTimeStep].AddChannels[1].ChannelValues[i]);
00870          
00871                     nextVert++;
00872                 }
00873 
00874             }
00875             return meshVert;
00876         }
00877         #endregion
00878 
00879         #region arrow plot
00880 
00881         private void initalizeArrowPlot()
00882         {
00883             arrow = game.Content.Load<Texture2D>("Sprites\\arrow1");
00884             arrowPlot = new ArrowPlot(sizeX, sizeY);
00885             
00886             device.PresentationParameters.MultiSampleType = device.DepthStencilBuffer.MultiSampleType;
00887 
00888             PresentationParameters pp = device.PresentationParameters;
00889             //pp.BackBufferWidth = (int)(boundaryLength.X*50.0f);
00890             //pp.BackBufferHeight = (int)(boundaryLength.Y * 50.0f);
00891 
00892             // define Stencil Buffer for Arrows
00893             stencilArrow = new DepthStencilBuffer(device, (int)(boundaryLength.X * 50.0f), (int)(boundaryLength.Y * 50.0f),
00894                 device.DepthStencilBuffer.Format, device.DepthStencilBuffer.MultiSampleType,
00895                 device.PresentationParameters.MultiSampleQuality);
00896 
00897             arrowTarget = new RenderTarget2D(device, (int)(boundaryLength.X * 50.0f),
00898                 (int)(boundaryLength.Y * 50.0f), 1, device.DisplayMode.Format,
00899                 device.DepthStencilBuffer.MultiSampleType,
00900                 device.PresentationParameters.MultiSampleQuality);
00901 
00902             //vertex buffer
00903             VertexPositionTexture v1 = new VertexPositionTexture(
00904                 new Vector3(gridData[0], 0.0f), new Vector2(0.0f, 0.0f));
00905             VertexPositionTexture v2 = new VertexPositionTexture(
00906                 new Vector3(gridData[sizeX-1], 0.0f), new Vector2(1.0f, 0.0f));
00907             VertexPositionTexture v3 = new VertexPositionTexture(
00908                 new Vector3(gridData[sizeX*(sizeY-1)], 0.0f), new Vector2(0.0f, 1.0f));
00909             VertexPositionTexture v4 = new VertexPositionTexture(
00910                 new Vector3(gridData[gridData.Length - 1], 0.0f), new Vector2(1.0f, 1.0f));
00911             verticeArray_arrows = new VertexPositionTexture[] { v1, v2, v3, v4 };
00912             vertexBuffer_arrow = new VertexBuffer(GraphicsDevice, 4 * VertexPositionTexture.SizeInBytes, BufferUsage.WriteOnly);
00913             vertexBuffer_arrow.SetData<VertexPositionTexture>(verticeArray_arrows);
00914 
00915             Console.WriteLine("min=" + boundaryMin + " max=" + BoundaryMax);
00916 
00917             //index buffer
00918             //generate indices
00919             arrowIndices = new int[] { 0, 1, 2, 2, 3, 1 };
00920             indexBuffer_arrow = new IndexBuffer(device, 2 * 3 * sizeof(int), BufferUsage.WriteOnly, IndexElementSize.ThirtyTwoBits);
00921             indexBuffer.SetData<int>(arrowIndices);
00922 
00923 
00924             //updateArrowPlot();
00925 
00926         }
00927 
00928         private void updateArrowPlot()
00929         {
00930             
00931             #region generate plot attributes
00932             //generate plot positions
00933             
00934             stepsizeX = boundaryLength.X / GameProperties.Instance.apStepsize;
00935             stepsizeY = boundaryLength.Y / GameProperties.Instance.apStepsize;
00936 
00937             float magnitudeRange = maxMagnitude - minMagnitude;
00938 
00939             arrowPlot.clear();
00940 
00941             for (float y = gridData[gridData.Length - 1].Y + (stepsizeY / 2.0f);
00942                 y < gridData[0].Y; y += stepsizeY)
00943             {
00944                 for (float x = gridData[0].X + (stepsizeX / 2.0f);
00945                     x < gridData[gridData.Length - 1].X; x += stepsizeX)
00946                 {
00947 
00948                     #region interpolate velocity and calculate magnitude
00949                     Vector3 interpolatedVelocity = getInterpolatedVector(x, y);
00950 
00951                     //calculate angle between interpolatedVelocity and x- (or y-) axis
00952                     Vector2 vec1 = new Vector2(interpolatedVelocity.X, interpolatedVelocity.Y);
00953                     //Console.WriteLine("ohne normalisieren: " + vec1);
00954                     vec1.Normalize();
00955                     float rotAngle = (float)Math.Acos((double)Vector2.Dot(vec1, new Vector2(1.0f, 0.0f)));
00956                     if (interpolatedVelocity.Y < 0)
00957                     {
00958                         rotAngle = MathHelper.ToRadians(360) - rotAngle;
00959                     }
00960                     //calculate magnitude of interpolatedVelocity
00961                     float defaultMagnitude = 1.0f;
00962                     //float magnitude = defaultMagnitude;
00963                     float magnitude = interpolatedVelocity.Length() / (maxMagnitude);
00964                     magnitude /= 3.0f;
00965                     #endregion
00966 
00967                     #region color and alpha
00968                     Color color;
00969                     if (GameProperties.Instance.enableArrowTransferFunction)
00970                     {
00971                         //get color from transferfunction in respect to magnitude
00972                         color = GameProperties.Instance.arrowColorArray[(int)(magnitude * 255)];
00973                         //color = Color.White;
00974                     }
00975                     else
00976                     {
00977                         //get default color
00978                         color = Color.White;
00979                     }
00980 
00981                     //set alpha 
00982                     float alpha = MathHelper.Lerp((color.A / 255), GameProperties.Instance.apAlpha, 1.0f);
00983                     color.A = (byte)(alpha * 255);
00984                     #endregion
00985 
00986                     #region scale arrow in respect to magnitude
00987                     if (GameProperties.Instance.scaleArrowLength)
00988                     {
00989                         arrowPlot.Scale.Add(magnitude);
00990                     }
00991                     else
00992                     {
00993                         arrowPlot.Scale.Add(0.25f);
00994                     }
00995                     #endregion
00996 
00997                     //save data
00998                     //arrowPlot.Position.Add(new Vector2(x, y));
00999                     arrowPlot.Position.Add(new Vector2(x, boundaryLength.Y - y));
01000                     //arrowPlot.Position.Add(new Vector2(x, y));
01001                     //arrowPlot.Position.Add(new Vector2(transX + x, transY + y));
01002                     arrowPlot.Orientation.Add(rotAngle);
01003                     arrowPlot.Magnitude.Add(magnitude);
01004                     arrowPlot.Color.Add(color);
01005 
01006                 }
01007             }
01008             #endregion
01009 
01010             CreateArrowTexture();
01011         }
01012 
01013         private void updateStreameLines()
01014         {
01015             //reset
01016             if (GameProperties.Instance.enableRungeKutta)
01017             {
01018                 streamlines_rungeKutta.resetStreamlines();
01019                 //int maxLength = (int)MathHelper.Max(boundaryLength.X, boundaryLength.Y);
01020                 streamlines_rungeKutta = new Streamlines(GameProperties.Instance.Dsep, GameProperties.Instance.Dtest,
01021                     (int)GameProperties.Instance.lineLength);
01022             }
01023             else
01024             {
01025                 streamlines_euler.resetStreamlines();
01026                 //int maxLength = (int)MathHelper.Max(boundaryLength.X, boundaryLength.Y);
01027                 streamlines_euler = new Streamlines(GameProperties.Instance.Dsep, GameProperties.Instance.Dtest,
01028                     (int)GameProperties.Instance.lineLength);
01029             }
01030             
01031             startSeedPointSearchAtIndex = 0;
01032             cGrid = null;
01033             
01034             cGrid = new CartesianGrid(GameProperties.Instance.Dsep,
01035                 gridData[gridData.Length - 1].X - gridData[0].X,
01036                 gridData[0].Y - gridData[gridData.Length - 1].Y);
01037             
01038 
01039             if (!GameProperties.Instance.enableRungeKutta)
01040             {
01041                 #region euler integration 1st order
01042 
01048                 Vector2 stepsize = new Vector2(stepsizeX, stepsizeY);
01049 
01050                 int streamLineIndex = 0;
01051                 // start position of first streamline:
01052                 Vector2 currentPosition = new Vector2(gridData[0].X + (float)(stepsizeX * 0.5),
01053                     gridData[gridData.Length - 1].Y + (stepsizeY * 0.5f));
01054                 Vector2 currentPosition_backward = currentPosition;
01055                 bool finished = false; // finished when no more seedpoints possible            
01056                 while (!finished)
01057                 {
01058                     Streamline currentLine = new Streamline(currentPosition);
01059                     bool forwardIntegration = true;
01060                     bool backwardIntegration = true;
01061                     while ((currentPosition.X < gridData[gridData.Length - 1].X)
01062                         && (currentPosition.Y < gridData[0].Y))
01063                     {
01064                         #region forward integration
01065                         if (forwardIntegration)
01066                         {
01067                             Vector3 interpolatedVelocity = getInterpolatedVector(currentPosition.X, currentPosition.Y);
01068                             Vector2 velocity = new Vector2(interpolatedVelocity.X, -interpolatedVelocity.Y);
01069                             //Vector2 velocity = new Vector2(-interpolatedVelocity.Y,interpolatedVelocity.X);//hurricane
01070                             velocity.Normalize();
01071                             currentPosition = currentPosition + dt * velocity;
01072                             if (streamlineStop(streamLineIndex, currentPosition, currentLine))
01073                             {
01074                                 forwardIntegration = false;
01075                             }
01076                         }
01077                         #endregion
01078 
01079                         #region backward integration
01080                         if (backwardIntegration)
01081                         {
01082                             Vector3 interpolatedVelocity = getInterpolatedVector(currentPosition_backward.X, currentPosition_backward.Y);
01083                             Vector2 velocity = new Vector2(interpolatedVelocity.X, -interpolatedVelocity.Y);
01084                             //Vector2 velocity = new Vector2(-interpolatedVelocity.Y,interpolatedVelocity.X);//hurricane
01085                             velocity.Normalize();
01086                             currentPosition_backward = currentPosition_backward - dt * velocity;
01087                             if (streamlineStop(streamLineIndex, currentPosition_backward, currentLine))
01088                             {
01089                                 backwardIntegration = false;
01090                             }
01091                         }
01092                         #endregion
01093                         if ((forwardIntegration == false) && (backwardIntegration == false))
01094                         {
01095                             break;
01096                         }
01097 
01098                         if (forwardIntegration)
01099                         {
01100                             currentLine.Points.Add(currentPosition);
01101                             cGrid.AddPoint(new SamplePoint(currentPosition, streamLineIndex, currentLine.Points.Count - 1));
01102                         }
01103 
01104                         if (backwardIntegration)
01105                         {
01106                             currentLine.Points.Insert(0, currentPosition_backward);
01107                             cGrid.AddPoint(new SamplePoint(currentPosition_backward, streamLineIndex, currentLine.Points.Count - 1));
01108                         }
01109                     }
01110 
01111                     streamlines_euler.StreamlineList.Add(currentLine);
01112                     streamLineIndex++;
01113                     currentPosition = findNewSeedPoint(streamlines_euler);
01114                     currentPosition_backward = currentPosition;
01115                     //finished = true;//delete this! only for debug TODO
01116                     if (currentPosition == new Vector2(-1000.0f, -1000.0f))
01117                     {
01118                         finished = true;
01119                         break;
01120                     }
01121                 }
01122                 Console.WriteLine("streamlines calculated");
01123                 //DrawStreamLines();
01124 
01125                 #region calculate tickness coef for tapering
01126                 foreach (Streamline nextStreamline in streamlines_euler.StreamlineList)
01127                 {
01128                     foreach (Vector2 nextPoint in nextStreamline.Points)
01129                     {
01130                         nextStreamline.Tickness.Add(calculateTickness(nextPoint));
01131                     }
01132                 }
01133                 #endregion
01134                 #endregion
01135             }
01136             else
01137             {
01138                 #region runge-kutta integration 2nd order
01139 
01146                 Vector2 stepsize = new Vector2(stepsizeX, stepsizeY);
01147 
01148                 int streamLineIndex = 0;
01149                 // start position of first streamline:
01150                 Vector2 currentPosition = new Vector2(gridData[0].X + (float)(stepsizeX * 0.5),
01151                     gridData[gridData.Length - 1].Y + (stepsizeY * 0.5f));
01152                 Vector2 currentPosition_backward = currentPosition;
01153                 bool finished = false; // finished when no more seedpoints possible            
01154                 while (!finished)
01155                 {
01156                     Streamline currentLine = new Streamline(currentPosition);
01157                     bool forwardIntegration = true;
01158                     bool backwardIntegration = true;
01159                     while ((currentPosition.X < gridData[gridData.Length - 1].X)
01160                         && (currentPosition.Y < gridData[0].Y))
01161                     {
01162                         #region forward integration
01163                         if (forwardIntegration)
01164                         {
01165                             Vector3 interpolatedVelocity = getInterpolatedVector(currentPosition.X, currentPosition.Y);
01166                             Vector2 velocity = new Vector2(interpolatedVelocity.X, -interpolatedVelocity.Y);
01167                             //Vector2 velocity = new Vector2(-interpolatedVelocity.Y,interpolatedVelocity.X);//hurricane
01168                             velocity.Normalize();
01169 
01170                             // 1.: do half a Euler step
01171                             Vector2 halfEuler = currentPosition + dt*0.5f * velocity;
01172 
01173                             // 2.: evaluate flow vector there
01174                             interpolatedVelocity = getInterpolatedVector(halfEuler.X, halfEuler.Y);
01175                             velocity = new Vector2(interpolatedVelocity.X, -interpolatedVelocity.Y);
01176                             //Vector2 velocity = new Vector2(-interpolatedVelocity.Y,interpolatedVelocity.X);//hurricane
01177                             if (velocity.Length() <= 0)
01178                             {
01179                                 forwardIntegration = false;
01180                                 continue;
01181                             }
01182                             else
01183                             {
01184                                 velocity.Normalize();
01185                             }                            
01186 
01187                             // 3.: use it in the origin
01188                             currentPosition = currentPosition + dt * velocity;
01189 
01190                             if (streamlineStop(streamLineIndex, currentPosition, currentLine))
01191                             {
01192                                 forwardIntegration = false;
01193                             }
01194                         }
01195                         #endregion
01196 
01197                         #region backward integration
01198                         if (backwardIntegration)
01199                         {
01200                             Vector3 interpolatedVelocity = getInterpolatedVector(currentPosition_backward.X, currentPosition_backward.Y);
01201                             Vector2 velocity = new Vector2(interpolatedVelocity.X, -interpolatedVelocity.Y);
01202                             //Vector2 velocity = new Vector2(-interpolatedVelocity.Y,interpolatedVelocity.X);//hurricane
01203                             velocity.Normalize();
01204 
01205                             // 1.: do half a Euler step
01206                             Vector2 halfEuler = currentPosition_backward - dt * 0.5f * velocity;
01207 
01208                             // 2.: evaluate flow vector there
01209                             interpolatedVelocity = getInterpolatedVector(halfEuler.X, halfEuler.Y);
01210                             velocity = new Vector2(interpolatedVelocity.X, -interpolatedVelocity.Y);
01211                             //Vector2 velocity = new Vector2(-interpolatedVelocity.Y,interpolatedVelocity.X);//hurricane
01212                             if (velocity.Length() <= 0)
01213                             {
01214                                 backwardIntegration = false;
01215                                 continue;
01216                             }
01217                             velocity.Normalize();
01218 
01219                             // 3.: use it in the origin
01220                             currentPosition_backward = currentPosition_backward - dt * velocity;
01221 
01222                             if (streamlineStop(streamLineIndex, currentPosition_backward, currentLine))
01223                             {
01224                                 backwardIntegration = false;
01225                             }
01226                         }
01227                         #endregion
01228 
01229                         if ((forwardIntegration == false) && (backwardIntegration == false))
01230                         {
01231                             break;
01232                         }
01233 
01234                         if (forwardIntegration)
01235                         {
01236                             currentLine.Points.Add(currentPosition);
01237                             cGrid.AddPoint(new SamplePoint(currentPosition, streamLineIndex, currentLine.Points.Count - 1));
01238                         }
01239 
01240                         if (backwardIntegration)
01241                         {
01242                             currentLine.Points.Insert(0, currentPosition_backward);
01243                             cGrid.AddPoint(new SamplePoint(currentPosition_backward, streamLineIndex, currentLine.Points.Count - 1));
01244                         }
01245                     }
01246 
01247                     streamlines_rungeKutta.StreamlineList.Add(currentLine);
01248                     streamLineIndex++;
01249                     currentPosition = findNewSeedPoint(streamlines_rungeKutta);
01250                     currentPosition_backward = currentPosition;
01251                     //finished = true;//delete this! only for debug TODO
01252                     if (currentPosition == new Vector2(-1000.0f, -1000.0f))
01253                     {
01254                         finished = true;
01255                         break;
01256                     }
01257                 }
01258                 Console.WriteLine("streamlines calculated");
01259                 //DrawStreamLines();
01260 
01261                 #region calculate tickness coef for tapering
01262                 foreach (Streamline nextStreamline in streamlines_rungeKutta.StreamlineList)
01263                 {
01264                     foreach (Vector2 nextPoint in nextStreamline.Points)
01265                     {
01266                         nextStreamline.Tickness.Add(calculateTickness(nextPoint));
01267                     }
01268                 }
01269                 #endregion
01270 
01271                 #endregion
01272             }
01273 
01274 
01275         }
01276 
01277         private Vector3 getInterpolatedVector(float x, float y)
01278         {
01279             //indices
01280             int leftXIndex = 0;
01281             int rightXIndex = 0;
01282             int upYIndex = 0;
01283             int downYIndex = 0;
01284 
01285             //find y-neighbours
01286             for (int i = 0; i < sizeY * sizeX; i += sizeX)
01287             {
01288                 if (y > gridData[i].Y)
01289                 {
01290                     //Console.WriteLine("index y=" + i);
01291                     upYIndex = i - sizeX;
01292                     downYIndex = i;
01293                     break;
01294                 }
01295             }
01296             //find x-neighbours
01297             for (int i = 0; i < sizeX; i++)
01298             {
01299                 if (x < gridData[i].X)
01300                 {
01301                     //Console.WriteLine("index x=" + i);
01302                     leftXIndex = i - 1;
01303                     rightXIndex = i;
01304                     break;
01305                 }
01306             }
01307             
01308             #region depricated (find neighbour indices)
01309             /*if (isFlipped == true)
01310             {
01311                 #region flipped version
01312                 //find y-neighbours
01313                 for (int i = 0; i < sizeY; i++)
01314                 {
01315                     if (gridData[i].Y < y)
01316                     {
01317                         //Console.WriteLine("index y=" + i);
01318                         upYIndex = i - 1;
01319                         downYIndex = i;
01320                         break;
01321                     }
01322                 }
01323                 //find x-neighbours
01324                 for (int i = 0; i < sizeX * sizeY; i += sizeY)
01325                 {
01326                     if (gridData[i].X > x)
01327                     {
01328                         //Console.WriteLine("index x=" + i);
01329                         leftXIndex = i - sizeY;
01330                         rightXIndex = i;
01331                         break;
01332                     }
01333                 }
01334                 #endregion
01335             }
01336             else
01337             {
01338                 #region non flipped version
01339                 //find y-neighbours
01340                 for (int i = 0; i < sizeY * sizeX; i+= sizeX)
01341                 {
01342                     if (gridData[i].Y < y)
01343                     {
01344                         //Console.WriteLine("index y=" + i);
01345                         upYIndex = i - sizeX;
01346                         downYIndex = i;
01347                         break;
01348                     }
01349                 }
01350                 //find x-neighbours
01351                 for (int i = 0; i < sizeX; i ++)
01352                 {
01353                     if (gridData[i].X > x)
01354                     {
01355                         //Console.WriteLine("index x=" + i);
01356                         leftXIndex = i - 1;
01357                         rightXIndex = i;
01358                         break;
01359                     }
01360                 }
01361             #endregion
01362             }*/
01363             #endregion
01364             
01365             #region get PositionVectors
01366             if ((upYIndex + leftXIndex > gridData.Length)
01367                 || (upYIndex + rightXIndex > gridData.Length)
01368                 || (downYIndex + leftXIndex > gridData.Length)
01369                 || (downYIndex + rightXIndex > gridData.Length)
01370                 || (upYIndex + leftXIndex < 0)
01371                 || (upYIndex + rightXIndex < 0)
01372                 || (downYIndex + leftXIndex < 0)
01373                 || (downYIndex + rightXIndex < 0))
01374             {
01375                 return new Vector3(0.0f);
01376             }
01377 
01378             Vector2 leftUp = gridData[upYIndex + leftXIndex];
01379             Vector2 rightUp = gridData[upYIndex + rightXIndex];
01380             Vector2 leftDown = gridData[downYIndex + leftXIndex];
01381             Vector2 rightDown = gridData[downYIndex + rightXIndex];
01382             #endregion
01383 
01384             #region calculate Distances
01385             float leftDist = Math.Abs(leftUp.X - x);
01386             float rightDist = Math.Abs(rightUp.X - x);
01387             float upDist = Math.Abs(leftUp.Y - y);
01388             float downDist = Math.Abs(leftDown.Y - y);
01389             float width = leftDist + rightDist;
01390             float height = upDist + downDist;
01391             #endregion
01392 
01393             #region get Velocity Vectors
01394             Vector3 leftUp_velocity = channelData[0].Velocity.VelocityValues[upYIndex + leftXIndex];
01395             Vector3 rightUp_velocity = channelData[0].Velocity.VelocityValues[upYIndex + rightXIndex];
01396             Vector3 leftDown_velocity = channelData[0].Velocity.VelocityValues[downYIndex + leftXIndex];
01397             Vector3 rightDown_velocity = channelData[0].Velocity.VelocityValues[downYIndex + rightXIndex];
01398             #endregion
01399 
01400             #region interpolate
01401             //don't interpolate positions, we want the interpolated Velocity!
01402             Vector3 interpolatedXUp = Vector3.Lerp(leftUp_velocity, rightUp_velocity, rightDist / width);
01403             Vector3 interpolatedXDown = Vector3.Lerp(leftDown_velocity, rightDown_velocity, rightDist / width);
01404             Vector3 interpolated = Vector3.Lerp(interpolatedXUp, interpolatedXDown, downDist / height);
01405             #endregion
01406 
01407             /*Console.WriteLine("lu=" + leftUp_velocity);
01408             Console.WriteLine("ru=" + rightUp_velocity);
01409             Console.WriteLine("ld=" + leftDown_velocity);
01410             Console.WriteLine("rd=" + rightDown_velocity);*/
01411 
01412             //Console.WriteLine(isFlipped);
01413             //Console.WriteLine("interpolated=" + interpolated);
01414             return interpolated;
01415         }
01416 
01417      
01418 
01419         #endregion
01420         #endregion
01421 
01422         #region Update
01423         public override void Update(GameTime gameTime)
01424         {
01425             updateArrowPlotControlPoints();
01426             #region update arrow plot
01427             if (GameProperties.Instance.enableArrowPlot &&
01428                 (GameProperties.Instance.activeTab.Equals(ActiveTab.ArrowTab) || GameProperties.Instance.activeTab.Equals(ActiveTab.Default)))
01429             {
01430                 //updateArrowPlotControlPoints();
01431                 updateArrowPlot();
01432             }
01433             #endregion
01434 
01435 
01436             #region update channels
01437             if (GameProperties.Instance.enableChannels &&
01438                 (GameProperties.Instance.activeTab.Equals(ActiveTab.ChannelsTab) || GameProperties.Instance.activeTab.Equals(ActiveTab.Default)))
01439             {
01440                 setControlpoints();
01441             }
01442             #endregion
01443 
01444 
01445             #region update streamlines
01446             if (GameProperties.Instance.enableStreamlines &&
01447                 (GameProperties.Instance.activeTab.Equals(ActiveTab.StreamlinesTab) || GameProperties.Instance.activeTab.Equals(ActiveTab.Default)))
01448             {
01449                 updateStreameLines(); // not if integration-mode changes!
01450             }
01451             #endregion
01452 
01453             base.Update(gameTime);
01454         }
01455         #endregion
01456 
01457         #region Draw
01458         public override void Draw(GameTime gameTime)
01459         {
01460 
01461             DrawData(GameProperties.Instance.currentChannelIdx); // tell which channel to draw: 0, 1, or 2
01462             
01463             if (GameProperties.Instance.enableStreamlines)
01464             {
01465                 Console.WriteLine("1 draw streamlines");
01466                 DrawStreamLines(); }
01467 
01468             if (GameProperties.Instance.enableArrowPlot)
01469             { 
01470                 device.RenderState.AlphaBlendEnable = true;
01471                 device.RenderState.SourceBlend = Blend.BlendFactor;
01472                 device.RenderState.DestinationBlend = Blend.SourceAlpha;
01473             
01474                 DrawArrowTexture();
01475 
01476                 device.RenderState.AlphaBlendEnable = false;
01477                 device.RenderState.SourceBlend = Blend.One;
01478                 device.RenderState.DestinationBlend = Blend.Zero;
01479             }
01480 
01481             // debug:
01482             //DrawGrid();
01483 
01484             base.Draw(gameTime);
01485         }
01486 
01487         #region Draw Arrow Texture
01488         private void DrawArrowTexture()
01489         {
01490             device.RenderState.FillMode = FillMode.Solid;
01491 
01492             GraphicsDevice.RenderState.DepthBufferEnable = false;
01493             GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
01494 
01495             //device.RenderState.CullMode = CullMode.None;//delete this!
01496 
01497             GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements);
01498             basicEffect2.World = world;
01499             basicEffect2.View = camera.View;
01500             basicEffect2.Projection = camera.Projection;
01501             basicEffect2.TextureEnabled = true;
01502             basicEffect2.Texture = arrowsTexture;
01503             basicEffect2.EnableDefaultLighting();
01504 
01505             GraphicsDevice.Indices = indexBuffer_arrow;
01506             GraphicsDevice.Vertices[0].SetSource(vertexBuffer_arrow, 0, VertexPositionTexture.SizeInBytes);
01507 
01508             int vertCount = 4;
01509             int trianglesCount = 2;
01510 
01511 
01512             #region Draw
01513             basicEffect2.Begin();
01514             foreach (EffectPass pass in basicEffect2.CurrentTechnique.Passes)
01515             {
01516                 pass.Begin();
01517 
01518                 GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
01519                         PrimitiveType.TriangleList, verticeArray_arrows, 0, vertCount, arrowIndices, 0, 2);
01520                 // Draw the mesh
01521                 //GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertCount, 0, trianglesCount);
01522 
01523                 pass.End();
01524             }
01525             basicEffect2.End();
01526             #endregion
01527 
01528             GraphicsDevice.RenderState.DepthBufferEnable = true;
01529             GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
01530         }
01531         #endregion Draw Arrow Texture - end
01532 
01533 
01534         #region DrawData
01535         private void DrawData(int channelNr)
01536         {
01537             device.RenderState.FillMode = FillMode.Solid;
01538 
01539             GraphicsDevice.VertexDeclaration = vertexDeclr;
01540             shader.SetEffectParameter(world * camera.ViewProjection, world, channelNr);
01541 
01542             GraphicsDevice.Indices = indexBuffer;
01543             GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, GridVertices.SizeInBytes);
01544 
01545             int vertCount = sizeX * sizeY;
01546             int trianglesCount = (sizeX - 1) * (sizeY - 1) * 2;
01547 
01548             shader.CurrentTechnique = shader.Techniques["Technique1"];
01549 
01550             #region Draw
01551             shader.Begin();
01552             foreach (EffectPass pass in shader.CurrentTechnique.Passes)
01553             {
01554                 pass.Begin();
01555 
01556                 // Draw the mesh
01557                 GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertCount, 0, trianglesCount);
01558 
01559                 pass.End();
01560             }
01561             shader.End();
01562 
01563             #endregion
01564 
01565             /*if (GameProperties.Instance.enableStreamlines)
01566             {
01567                 updateStreameLines();
01568             }*/
01569 
01570         }
01571         #endregion
01572 
01573         #region Create Arrow Texture
01574         private void CreateArrowTexture()
01575         {
01576             stencilData = device.DepthStencilBuffer;
01577 
01578             device.SetRenderTarget(0, arrowTarget);
01579             // save Stencil Buffer for Scene
01580             //stencil_scene = device.DepthStencilBuffer;
01581 
01582             // assign Stencil Buffer for Arrows
01583             device.DepthStencilBuffer = stencilArrow;
01584 
01585             #region draw to texture
01586             spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
01587             
01588             for (int i = 0; i < arrowPlot.Position.Count; i++)
01589             {
01590                 //transform positions to screen space
01591                 Vector2 pos = arrowPlot.Position[i] - boundaryMin;
01592                 pos *= 50.0f;
01593 
01594                 spriteBatch.Draw(arrow, new Vector2(pos.X, pos.Y), null, arrowPlot.Color[i],
01595                    arrowPlot.Orientation[i], Vector2.Zero, arrowPlot.Scale[i],
01596                    SpriteEffects.None, 0);
01597 
01598             }
01599 
01600             spriteBatch.End();
01601             #endregion draw to texture - end
01602 
01603             device.SetRenderTarget(0, null);
01604             device.DepthStencilBuffer = stencilData;
01605             arrowsTexture = arrowTarget.GetTexture();
01606 
01607             //debug:
01608             //arrowsTexture.Save("arrowsTexture.bmp", ImageFileFormat.Bmp);
01609 
01610             #region depricated
01611             /*GraphicsDevice.RenderState.DepthBufferEnable = false;
01612             GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
01613             spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
01614  
01615             float height = GameProperties.Instance.XNADrawSurfaceHeight;
01616             float width = GameProperties.Instance.XNADrawSurfaceWidth;
01617             float scaleValue = Math.Max(boundaryLength.X, boundaryLength.Y);
01618             float scaleValue_height = (height / scaleValue);
01619             float scaleValue_width = (width / scaleValue);
01620             Vector2 translateToCenter = new Vector2( (width/2.0f)-(boundaryLength.X/2.0f)*scaleValue_width, 
01621                 (height/2.0f)-(boundaryLength.Y/2.0f)*scaleValue_height);
01622 
01623            for(int i = 0; i < arrowPlot.Position.Count; i++)
01624            {
01625                //transform positions to screen space
01626                Vector4 pos = new Vector4(arrowPlot.Position[i], 1.0f, 1.0f);
01627                //TODO: move to center (x,y)
01628                pos.X *= scaleValue_width;
01629                pos.Y *= scaleValue_height;
01630                pos.X += translateToCenter.X;// -arrow.Width * arrowPlot.Magnitude[i] / 2.0f;
01631                pos.Y += translateToCenter.Y;// -arrow.Height * arrowPlot.Magnitude[i] / 2.0f;
01632                //pos = Vector4.Transform(pos, worldViewProjection);
01633                /*spriteBatch.Draw(arrow, new Vector2(pos.X, pos.Y), null, arrowPlot.Color[i], 
01634                    arrowPlot.Orientation[i], Vector2.Zero, arrowPlot.Magnitude[i], 
01635                    SpriteEffects.None, 0);*/
01636             /* spriteBatch.Draw(arrow, new Vector2(pos.X, pos.Y), null, arrowPlot.Color[i],
01637                 arrowPlot.Orientation[i], Vector2.Zero, arrowPlot.Scale[i],
01638                 SpriteEffects.None, 0);
01639 
01640           }
01641 
01642           spriteBatch.End();
01643           GraphicsDevice.RenderState.DepthBufferEnable = true;
01644           GraphicsDevice.RenderState.DepthBufferWriteEnable = true;*/
01645             #endregion depricated - end
01646         }
01647         
01648         #endregion
01649 
01650         #region Draw Streamlines
01651         private void DrawStreamLines()
01652         {
01653             Console.WriteLine("Drawing streamlines");
01654             #region initialize draw
01655             device.RenderState.FillMode = FillMode.WireFrame;
01656             GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);
01657             basicEffect.World = world;
01658             //basicEffect.World = Matrix.Identity;
01659             basicEffect.View = camera.View;
01660             basicEffect.Projection = camera.Projection;
01661             #endregion
01662 
01663             
01664             GraphicsDevice.RenderState.DepthBufferEnable = false;
01665             GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
01666 
01667             //foreach(Streamline nextLine in streamlines.StreamlineList)
01668 
01669 
01670             List<Streamline> linesToDraw = new List<Streamline>();
01671 
01672             if (GameProperties.Instance.enableRungeKutta)
01673 
01674             {
01675                 if (streamlines_rungeKutta.StreamlineList == null) 
01676                 {
01677                     // if this is the first time drawing and the Streamline-List is still empty
01678                     updateStreameLines();
01679                 }
01680                 linesToDraw = streamlines_rungeKutta.StreamlineList;
01681             }
01682             else
01683             {
01684                 if (streamlines_euler.StreamlineList == null)
01685                 {
01686                     // if this is the first time drawing and the Streamline-List is still empty
01687                     updateStreameLines();
01688                 }
01689                 linesToDraw = streamlines_euler.StreamlineList;
01690             }
01691 
01692             
01693             #region draw with line width or normal
01694 
01695             if (GameProperties.Instance.lineWidth <= 0.1f) //draw normal
01696             {
01697                 foreach (Streamline nextLine in linesToDraw)
01698                 {
01699 
01700                     int vertCount = nextLine.Points.Count();
01701 
01702                     if (vertCount > 1)
01703                     {
01704 
01705                         #region initialize vertex and index buffer
01706                         VertexPositionColor[] streamlineVert = new VertexPositionColor[vertCount];
01707 
01708                         //linestrip
01709                         short[] streamlineIdx = new short[vertCount];
01710                         for (int i = 0; i < vertCount; i++)
01711                         {
01712                             streamlineVert[i] = new VertexPositionColor(new Vector3(nextLine.Points[i].X, nextLine.Points[i].Y, 0.0f), Color.White);
01713                             streamlineIdx[i] = (short)i;
01714                         }
01715                         #endregion
01716 
01717 
01718                         #region draw
01719                         basicEffect.Begin();
01720 
01721                         foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
01722                         {
01723                             pass.Begin();
01724 
01725                             // Draw stripline
01726                             GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
01727                                 PrimitiveType.LineStrip, streamlineVert, 0, vertCount, streamlineIdx, 0, (vertCount - 1));
01728 
01729                             pass.End();
01730                         }
01731 
01732                         basicEffect.End();
01733                         #endregion
01734                     }
01735 
01736                 }//end foreach
01737             }
01738             else //apply line width
01739             {
01740                 foreach (Streamline nextLine in linesToDraw)
01741                 {
01742                     int vertCount = nextLine.Points.Count();
01743 
01744                     if (vertCount > 1)
01745                     {
01746                         device.RenderState.FillMode = FillMode.Solid;
01747 
01748                         #region initialize vertex and index buffer
01749                         VertexPositionColor[] streamlineVert = calculateTriangleStrip(nextLine.Points, nextLine.Tickness);
01750 
01751                         vertCount = streamlineVert.Length;
01752 
01753                         //triangle strip
01754                         short[] streamlineIdx = new short[vertCount];
01755 
01756                         for (int i = 0; i < vertCount; i++)
01757                         {
01758                             streamlineIdx[i] = (short)i;
01759                         }
01760                         #endregion
01761 
01762 
01763                         #region draw
01764                         basicEffect.Begin();
01765 
01766                         foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
01767                         {
01768                             pass.Begin();
01769 
01770                             GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
01771                         PrimitiveType.TriangleStrip, streamlineVert, 0, vertCount, streamlineIdx, 0, (vertCount - 2));
01772 
01773                             pass.End();
01774                         }
01775 
01776                         basicEffect.End();
01777                         #endregion
01778                     }
01779 
01780                 }//end foreach
01781  
01782             }
01783 
01784             #endregion
01785 
01786             
01787 
01788             GraphicsDevice.RenderState.DepthBufferEnable = true;
01789             GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
01790         }
01791 
01792         /*private void DrawStreamLines1()
01793         {
01794             Console.WriteLine("Drawing streamlines");
01795             #region initialize draw
01796             device.RenderState.FillMode = FillMode.WireFrame;
01797             GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);
01798             basicEffect.World = world;
01799             //basicEffect.World = Matrix.Identity;
01800             basicEffect.View = camera.View;
01801             basicEffect.Projection = camera.Projection;
01802             #endregion
01803 
01804 
01805             GraphicsDevice.RenderState.DepthBufferEnable = false;
01806             GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
01807 
01808             //foreach(Streamline nextLine in streamlines.StreamlineList)
01809 
01810 
01811             List<Streamline> linesToDraw = new List<Streamline>();
01812 
01813             if (GameProperties.Instance.enableRungeKutta)
01814             {
01815                 if (streamlines_rungeKutta.StreamlineList == null)
01816                 {
01817                     // if this is the first time drawing and the Streamline-List is still empty
01818                     updateStreameLines();
01819                 }
01820                 linesToDraw = streamlines_rungeKutta.StreamlineList;
01821             }
01822             else
01823             {
01824                 if (streamlines_euler.StreamlineList == null)
01825                 {
01826                     // if this is the first time drawing and the Streamline-List is still empty
01827                     updateStreameLines();
01828                 }
01829                 linesToDraw = streamlines_euler.StreamlineList;
01830             }
01831 
01832 
01833             #region draw with line width or normal
01834 
01835             if (GameProperties.Instance.lineWidth <= 0.1f) //draw normal
01836             {
01837                 foreach (Streamline nextLine in linesToDraw)
01838                 {
01839 
01840                     int vertCount = nextLine.Points.Count();
01841 
01842                     if (vertCount > 1)
01843                     {
01844 
01845                         #region initialize vertex and index buffer
01846                         VertexPositionColor[] streamlineVert = new VertexPositionColor[vertCount];
01847 
01848                         //linestrip
01849                         short[] streamlineIdx = new short[vertCount];
01850                         for (int i = 0; i < vertCount; i++)
01851                         {
01852                             streamlineVert[i] = new VertexPositionColor(new Vector3(nextLine.Points[i].X, nextLine.Points[i].Y, 0.0f), Color.White);
01853                             streamlineIdx[i] = (short)i;
01854                         }
01855                         #endregion
01856 
01857 
01858                         #region draw
01859                         basicEffect.Begin();
01860 
01861                         foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
01862                         {
01863                             pass.Begin();
01864 
01865                             // Draw stripline
01866                             GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
01867                                 PrimitiveType.LineStrip, streamlineVert, 0, vertCount, streamlineIdx, 0, (vertCount - 1));
01868 
01869                             pass.End();
01870                         }
01871 
01872                         basicEffect.End();
01873                         #endregion
01874                     }
01875 
01876                 }//end foreach
01877             }
01878             else //apply line width
01879             {
01880                 foreach (Streamline nextLine in linesToDraw)
01881                 {
01882                     int vertCount = nextLine.Points.Count();
01883 
01884                     if (vertCount > 1)
01885                     {
01886                         device.RenderState.FillMode = FillMode.Solid;
01887 
01888                         #region initialize vertex and index buffer
01889                         VertexPositionColor[] streamlineVert = calculateTriangleStrip(nextLine.Points, nextLine.Tickness);
01890 
01891                         vertCount = streamlineVert.Length;
01892 
01893                         //triangle strip
01894                         short[] streamlineIdx = new short[vertCount];
01895 
01896                         for (int i = 0; i < vertCount; i++)
01897                         {
01898                             streamlineIdx[i] = (short)i;
01899                         }
01900                         #endregion
01901 
01902 
01903                         #region draw
01904                         basicEffect.Begin();
01905 
01906                         foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
01907                         {
01908                             pass.Begin();
01909 
01910                             GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
01911                         PrimitiveType.TriangleStrip, streamlineVert, 0, vertCount, streamlineIdx, 0, (vertCount - 2));
01912 
01913                             pass.End();
01914                         }
01915 
01916                         basicEffect.End();
01917                         #endregion
01918                     }
01919 
01920                 }//end foreach
01921 
01922             }
01923 
01924             #endregion
01925 
01926 
01927 
01928             GraphicsDevice.RenderState.DepthBufferEnable = true;
01929             GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
01930         }*/
01931         #endregion
01932 
01933         #region debug
01934         private void DrawStreamLinesTapering()
01935         {
01936             //test
01937             //calculateTriangleStrip(new Vector2(10, 20), new Vector2(10, 5));
01938 
01939 
01940             //calculateTriangleStrip(new Vector2(10, 5), new Vector2(10, 20));
01941 
01942             //calculateTriangleStrip(new Vector2(10, 20), new Vector2(20, 20));
01943             //calculateTriangleStrip(new Vector2(20, 20), new Vector2(10, 20));
01944 
01945             //calculateTriangleStrip(new Vector2(10, 5), new Vector2(30, 30));
01946             //calculateTriangleStrip(new Vector2(10, 5), new Vector2(0, 30));
01947 
01948             Console.WriteLine("Drawing streamlines");
01949             #region initialize draw
01950             device.RenderState.FillMode = FillMode.WireFrame;
01951             //device.RenderState.FillMode = FillMode.Solid;
01952             GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);
01953             basicEffect.World = world;
01954             //basicEffect.World = Matrix.Identity;
01955             basicEffect.View = camera.View;
01956             basicEffect.Projection = camera.Projection;
01957             #endregion
01958 
01959 
01960             GraphicsDevice.RenderState.DepthBufferEnable = false;
01961             GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
01962 
01963             #region initialize vertex and index buffer
01964 
01965             //test array
01966             Vector2[] points = new Vector2[4];
01967 
01968             points[0] = new Vector2(10, 20);
01969             points[1] = new Vector2(10, 5);
01970             points[2] = new Vector2(10, -5);
01971             points[3] = new Vector2(10, -9);
01972 
01973             VertexPositionColor[] streamlineVert = calculateTriangleStrip(points.ToList<Vector2>(), new List<float>());
01974 
01975             int vertCount = streamlineVert.Length;
01976 
01977             //triangle strip
01978             short[] streamlineIdx = new short[vertCount];
01979                 
01980             for (int i = 0; i < vertCount; i++)
01981             {
01982                     //streamlineVert[i].Color = Color.White;
01983                     streamlineIdx[i] = (short)i;
01984             }
01985             #endregion
01986 
01987             #region draw
01988             basicEffect.Begin();
01989 
01990                 foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
01991                 {
01992                     pass.Begin();
01993 
01994                     // Draw line
01995                     //GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
01996                     //  PrimitiveType.LineList, streamlineVert, 0, vertCount, streamlineIdx, 0, (vertCount - 1));
01997 
01998                     // Draw stripline
01999                     GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
02000                         PrimitiveType.TriangleStrip, streamlineVert, 0, vertCount, streamlineIdx, 0, (vertCount - 2));
02001 
02002                     pass.End();
02003                 }
02004 
02005                 basicEffect.End();
02006                 #endregion
02007 
02008             
02009           
02010 
02011             GraphicsDevice.RenderState.DepthBufferEnable = true;
02012             GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
02013         }
02014        
02015 
02016         private VertexPositionColor[] calculateTriangleStrip(Vector2 point1, Vector2 point2)
02017         {
02018             //float lineWidth = GameProperties.Instance.lineWidth;//to do relative to dtest
02019             float lineWidth = 6.0f;
02020             float distance = lineWidth * 0.5f;
02021             int countVert = 4;
02022 
02023             //calculate triangle strip
02024             VertexPositionColor[] vertices = new VertexPositionColor[4];
02025             //short[] indices = new short[countVert];
02026 
02027             //float angle = calculateAngle(point1, point2);
02028             Vector2 direction = point2 - point1;
02029             Vector2 normal = new Vector2(direction.Y, -direction.X);
02030             normal.Normalize();
02031 
02032             Vector2 point1_left = point1 + (normal * distance);
02033             Vector2 point1_right = point1 - (normal * distance);
02034             Vector2 point2_left = point2 + (normal * distance);
02035             Vector2 point2_right = point2 - (normal * distance);
02036 
02037             vertices[0].Position = new Vector3(point2_left.X, point2_left.Y, 0.0f);
02038             vertices[1].Position = new Vector3(point1_left.X, point1_left.Y, 0.0f);
02039             vertices[2].Position = new Vector3(point2_right.X, point2_right.Y, 0.0f);
02040             vertices[3].Position = new Vector3(point1_right.X, point1_right.Y, 0.0f);
02041 
02042 
02043             /*for (int i = 0; i < countVert; i++)
02044             {
02045                 indices[i] = (short)i;
02046             }*/
02047 
02048             return vertices;
02049         }
02050         #endregion
02051 
02052         #region line width and tapering 
02053         private VertexPositionColor[] calculateTriangleStrip(List<Vector2> pointList, List<float> ticknessList)
02054         {
02055             float distance = GameProperties.Instance.lineWidth * 0.5f;
02056             if (GameProperties.Instance.enableTapering) distance = (GameProperties.Instance.lineWidth * 2) * 0.5f;
02057             
02058             float thick1 = 1.0f;
02059             float thick2 = 1.0f;
02060 
02061             //calculate triangle strip
02062             List<VertexPositionColor> vertices = new List<VertexPositionColor>();
02063 
02064             for (int i = 0; i < pointList.Count() - 1; i++)
02065             {
02066                 Vector2 point1 = pointList[i];
02067                 Vector2 point2 = pointList[i + 1];
02068                 Vector2 direction = point2 - point1;
02069                 Vector2 normal = new Vector2(direction.Y, -direction.X);
02070                 normal.Normalize();
02071 
02072                 if (GameProperties.Instance.enableTapering)
02073                 {
02074                     thick1 = ticknessList[i];
02075                     thick2 = ticknessList[i + 1];
02076                 }
02077 
02078                 Vector2 point1_left = point1 + (normal * distance * thick1);
02079                 Vector2 point1_right = point1 - (normal * distance * thick1);
02080                 Vector2 point2_left = point2 + (normal * distance * thick2);
02081                 Vector2 point2_right = point2 - (normal * distance * thick2);
02082 
02083                 vertices.Add(new VertexPositionColor(new Vector3(point2_left.X, point2_left.Y, 0.0f), Color.White));
02084                 vertices.Add(new VertexPositionColor(new Vector3(point1_left.X, point1_left.Y, 0.0f), Color.White));
02085                 vertices.Add(new VertexPositionColor(new Vector3(point2_right.X, point2_right.Y, 0.0f), Color.White));
02086                 vertices.Add(new VertexPositionColor(new Vector3(point1_right.X, point1_right.Y, 0.0f), Color.White));
02087  
02088             }
02089           
02090             return vertices.ToArray();
02091         }
02092 
02093         private float calculateAngle(Vector2 point1, Vector2 point2)
02094         {
02095             float x = point2.X - point1.X;
02096             float y = point2.Y - point1.Y;
02097 
02098             float angle = MathHelper.ToDegrees((float)Math.Atan2(y, x));
02099   
02100             return angle;
02101         }
02102         #endregion
02103 
02104 
02105         #region debug: draw grid
02106         private void DrawGrid()
02107         {
02108             device.RenderState.FillMode = FillMode.WireFrame;
02109 
02110             GraphicsDevice.VertexDeclaration = vertexDeclr;
02111             basicEffect.World = world;
02112             basicEffect.View = camera.View;
02113             basicEffect.Projection = camera.Projection;
02114 
02115             GraphicsDevice.Indices = indexBuffer;
02116             GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, GridVertices.SizeInBytes);
02117 
02118             int vertCount = sizeX * sizeY;
02119             int trianglesCount = (sizeX - 1) * (sizeY - 1) * 2;
02120 
02121             basicEffect.Begin();
02122 
02123             foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
02124             {
02125                 pass.Begin();
02126 
02127                 // Draw the mesh
02128                 GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertCount, 0, trianglesCount);
02129 
02130                 pass.End();
02131             }
02132 
02133             basicEffect.End();
02134         }
02135         #endregion
02136 
02137         #endregion
02138 
02139         #region transfer function
02140 
02141 
02142 
02143 
02144         private void setControlpoints()
02145         {
02146             colorControlPoints = GameProperties.Instance.channelControlPoints[GameProperties.Instance.currentChannelIdx];
02147        
02148             float amount = 0.0f;
02149             Color[] colorArray = new Color[256];
02150 
02151             #region interpolate between ControlPoints
02152 
02153             // sort ControlPoints by isoValue
02154             colorControlPoints.Sort(delegate(TransferControlPoint p1,
02155                 TransferControlPoint p2) { return p1.isoValue.CompareTo(p2.isoValue); });
02156 
02157             // before first ControlPoint: fill with black and alpha 0.0f
02158             for (int i = 0; i < colorControlPoints[0].isoValue; i++)
02159             {
02160                 colorArray[i] = Color.Black;
02161             }
02162 
02163             for (int j = 0; j < colorControlPoints.Count - 1; j++)
02164             {
02165                 for (int i = colorControlPoints[j].isoValue; i < colorControlPoints[j + 1].isoValue; i++)
02166                 {
02167                     amount = (((float)i - colorControlPoints[j].isoValue) /
02168                         (colorControlPoints[j + 1].isoValue - colorControlPoints[j].isoValue));
02169                     Vector4 value = Vector4.Lerp(colorControlPoints[j].color,
02170                         colorControlPoints[j + 1].color, amount);
02171                     Color newColor = new Color();
02172                     newColor.R = (byte)value.X;
02173                     newColor.G = (byte)value.Y;
02174                     newColor.B = (byte)value.Z;
02175                     //newColor.A = (byte)(255.0f);
02176                     newColor.A = (byte)(value.W * 255.0f); 
02177                     colorArray[i] = newColor;
02178 
02179                 }
02180             }
02181 
02182             // after last ControlPoint: fill with black
02183             for (int i = colorControlPoints[colorControlPoints.Count - 1].isoValue + 1; i < 256; i++)
02184             {
02185                 colorArray[i] = Color.Black;
02186             }
02187 
02188             //for gui
02189             if (initialControPoints)
02190             {
02191                 for (int j = 0; j < GameProperties.Instance.channelControlPoints.Count(); j++)
02192                 {
02193                     GameProperties.Instance.colorArray[j] = colorArray;
02194                 }
02195                 initialControPoints = false;
02196                 GameProperties.Instance.updateChannelColor = true;
02197             }
02198             else 
02199             {
02200                 GameProperties.Instance.colorArray[GameProperties.Instance.currentChannelIdx] = colorArray;
02201                 GameProperties.Instance.updateChannelColor = true;
02202             }
02203             #endregion
02204 
02205             #region write to textures
02206             //write to a textures
02207             //transferTexture = new Texture2D(Game.GraphicsDevice, 256, 1, 1, TextureUsage.Linear, SurfaceFormat.Color);
02208             transferTexture = new Texture2D(Game.GraphicsDevice, colorArray.Length, 1, 1, TextureUsage.Linear, SurfaceFormat.Color);
02209            
02210             Byte4[] transferValues = new Byte4[256];
02211             //Vector4[] transferValues = new Vector4[colorArray.Length];
02212             for (int i = 0; i < 256; i++)
02213             {
02214                 Vector4 color = new Vector4(colorArray[i].R, colorArray[i].G, colorArray[i].B, colorArray[i].A);
02215                 //color *= 255.0f;
02216                 //store bgra, but why?
02217                 //transferValues[i] = new Vector4(color.Z, color.Y, color.X, color.W);
02218                 transferValues[i] = new Byte4(color.Z, color.Y, color.X, color.W);
02219             }
02220             //transferTexture.SetData<Vector4>(transferValues);
02221             transferTexture.SetData<Byte4>(transferValues);
02222             //transferTexture.Save("transfer.jpg", ImageFileFormat.Jpg);
02223             try
02224             {
02225                 transferTexture.Save("transfer.jpg", ImageFileFormat.Jpg);
02226             }
02227             catch (Exception e)
02228             {
02229                 Console.WriteLine("******************************************************************");
02230                 Console.WriteLine(e);
02231             } 
02232             #endregion
02233 
02234             shader.TransferTexture = this.transferTexture; // TODO: only set if values changed!
02235 
02236         }
02237 
02238         private void updateArrowPlotControlPoints()
02239         {
02240 
02241             List<TransferControlPoint> colorControlPoints = GameProperties.Instance.arrowControlPoints;
02242 
02243             float amount = 0.0f;
02244             Color[] colorArray = new Color[256];
02245 
02246             #region interpolate between ControlPoints
02247 
02248             // sort ControlPoints by isoValue
02249             colorControlPoints.Sort(delegate(TransferControlPoint p1,
02250                 TransferControlPoint p2) { return p1.isoValue.CompareTo(p2.isoValue); });
02251 
02252             // before first ControlPoint: fill with black and alpha 0.0f
02253             for (int i = 0; i < colorControlPoints[0].isoValue; i++)
02254             {
02255                 colorArray[i] = Color.Black;
02256             }
02257 
02258             for (int j = 0; j < colorControlPoints.Count - 1; j++)
02259             {
02260                 for (int i = colorControlPoints[j].isoValue; i < colorControlPoints[j + 1].isoValue; i++)
02261                 {
02262                     amount = (((float)i - colorControlPoints[j].isoValue) /
02263                         (colorControlPoints[j + 1].isoValue - colorControlPoints[j].isoValue));
02264                     Vector4 value = Vector4.Lerp(colorControlPoints[j].color,
02265                         colorControlPoints[j + 1].color, amount);
02266                     Color newColor = new Color();
02267                     newColor.R = (byte)value.X;
02268                     newColor.G = (byte)value.Y;
02269                     newColor.B = (byte)value.Z;
02270                     //newColor.A = (byte)(255.0f);
02271                     newColor.A = (byte)(value.W * 255.0f);
02272                     colorArray[i] = newColor;
02273 
02274                 }
02275             }
02276 
02277             // after last ControlPoint: fill with black
02278             for (int i = colorControlPoints[colorControlPoints.Count - 1].isoValue + 1; i < 256; i++)
02279             {
02280                 colorArray[i] = Color.Black;
02281             }
02282             GameProperties.Instance.arrowColorArray = colorArray;
02283             GameProperties.Instance.updateArrowColor = true;
02284             #endregion
02285         }
02286         #endregion
02287 
02288         #region Other Methods
02289 
02290 
02291 
02292 
02293         private void createUniformGrid()
02294         {
02295             normalizedGridData = new Vector2[sizeX * sizeY];
02296             //scale values
02297             for (int i = 0; i < sizeX * sizeY; i++)
02298             {
02299                 normalizedGridData[i] = Vector2.Divide((gridData[i] - boundaryMin), boundaryLength);
02300             }
02301         }
02302 
02308         private GridVertices[] GenerateTextureCoord(GridVertices[] meshVert)
02309         {
02310             float tu = 0;
02311             float tv = 0;
02312             float tuDerivative = 1.0f / (sizeX - 1);
02313             float tvDerivative = 1.0f / (sizeY - 1);
02314 
02315             int nextVert = 0;
02316             for (float row = 0; row <= sizeY; row++)
02317             {
02318                 tu = 0.0f;
02319                 for (float col = 0; col <= sizeX; col++)
02320                 {
02321                     //meshVert[nextVert].TextureCoordinate = new Vector2(tu, tv); //todo add def to the custom vertex format
02322                     tu += tuDerivative;
02323                     nextVert++;
02324                 }
02325                 tv += tvDerivative;
02326             }
02327 
02328             return meshVert;
02329         }
02330 
02336        /* private GridVertices[] generateNormals(int[] meshIndices, GridVertices[] meshVert)
02337         {
02338             for (int i = 0; i < meshIndices.Length; i += 3)
02339             {
02340                 //get vertices for each triangle 
02341                 Vector2 vert1 = meshVert[meshIndices[i]].Position;
02342                 Vector2 vert2 = meshVert[meshIndices[i + 1]].Position;
02343                 Vector2 vert3 = meshVert[meshIndices[i + 2]].Position;
02344                 //calculate a normal vector for that triangle
02345                 Vector2 norm = Vector3.Cross(vert3 - vert1, vert2 - vert1);
02346                 norm.Normalize();
02347                 //calculate mean //todo: if we use it add definition in the custom vertex def, and make vertices 3d
02348                 meshVert[meshIndices[i]].Normal += norm;
02349                 meshVert[meshIndices[i + 1]].Normal += norm;
02350                 meshVert[meshIndices[i + 2]].Normal += norm;
02351             }
02352 
02353             for (int i = 0; i < meshVert.Length; i++)
02354             {
02355                 meshVert[i].Normal.Normalize();
02356             }
02357 
02358             return meshVert;
02359         }*/
02360 
02361 
02362         #endregion
02363 
02364         #region Helper Functions
02365         private void loadDatafromFileExtend()
02366         {
02367             #region read .gri
02368 
02369             Stream file = new FileStream(griFileName, FileMode.Open);
02370             BinaryReader reader = new BinaryReader(file);
02371 
02372             #region read header
02373             byte[] headerBuffer = new byte[40];
02374             reader.Read(headerBuffer, 0, 40);
02375 
02376             string header = System.Text.ASCIIEncoding.ASCII.GetString(headerBuffer);
02377             //string[] header_str = System.Text.ASCIIEncoding.ASCII.GetString(headerBuffer).Split(' ');
02378             //char[] headerChars = System.Text.ASCIIEncoding.ASCII.GetChars(headerBuffer);
02379 
02380             Regex stringSeq = new Regex("[a-zA-Z0-9]+");
02381             Regex positiveInt = new Regex("0*[1-9][0-9]*");
02382             Regex positiveFloat = new Regex("[0-9]+[.][0-9]*");
02383             Regex emptySpace = new Regex(" ");
02384 
02385             int pos = 0;
02386 
02387             try
02388             {
02389                 Match match_strName = stringSeq.Match(header, pos);
02390                 if (match_strName.Success)
02391                 {
02392                     headerName = match_strName.ToString();
02393                     pos += match_strName.Length;
02394                 }
02395 
02396                 if (emptySpace.Match(header, pos).Success) { pos++; }
02397 
02398 
02399                 Match match_strX = positiveInt.Match(header, pos);
02400                 if (match_strX.Success)
02401                 {
02402                     sizeX = int.Parse(match_strX.ToString());
02403                     pos += match_strX.Length;
02404                 }
02405 
02406                 if (emptySpace.Match(header, pos).Success) { pos++; }
02407 
02408                 Match match_strY = positiveInt.Match(header, pos);
02409                 if (match_strY.Success)
02410                 {
02411                     sizeY = int.Parse(match_strY.ToString());
02412                     pos += match_strY.Length;
02413                 }
02414 
02415                 if (emptySpace.Match(header, pos).Success) { pos++; }
02416 
02417                 Match match_strZ = positiveInt.Match(header, pos);
02418                 if (match_strZ.Success)
02419                 {
02420                     sizeZ = int.Parse(match_strZ.ToString());
02421                     pos += match_strZ.Length;
02422                 }
02423 
02424                 if (emptySpace.Match(header, pos).Success) { pos++; }
02425 
02426                 Match match_strNumber1 = positiveInt.Match(header, pos);
02427                 if (match_strNumber1.Success)
02428                 {
02429                     channelNumber = int.Parse(match_strNumber1.ToString());
02430                     pos += match_strNumber1.Length;
02431                 }
02432 
02433                 if (emptySpace.Match(header, pos).Success) { pos++; }
02434 
02435                 Match match_strNumber2 = positiveInt.Match(header, pos);
02436                 if (match_strNumber2.Success)
02437                 {
02438                     timestepNumber = int.Parse(match_strNumber2.ToString());
02439                     pos += match_strNumber2.Length;
02440                 }
02441 
02442                 if (emptySpace.Match(header, pos).Success) { pos++; }
02443 
02444                 Match match_strDur = positiveFloat.Match(header, pos);
02445                 if (match_strDur.Success)
02446                 {
02447                     timestepDuration = float.Parse(match_strDur.ToString());
02448                     pos += match_strDur.Length;
02449                 }
02450 
02451             }
02452             catch (Exception e)
02453             {
02454                 Console.WriteLine("Some header information is missing");
02455             }
02456 
02457             #endregion
02458 
02459             #region read geometry data
02460 
02461             int sizeXOld = sizeX;
02462             int sizeYOld = sizeY;
02463             int sizeZOld = sizeZ;
02464 
02465             sizeX = calculatePowerOfTwo((int)sizeX);
02466             sizeY = calculatePowerOfTwo((int)sizeY);
02467             sizeZ = calculatePowerOfTwo((int)sizeZ);
02468 
02469             gridData = new Vector2[sizeX * sizeY];
02470             int nextPos = 0;
02471             try
02472             {
02473 
02474                 for (int y = 0; y < sizeY; y++)
02475                 {
02476                     for (int x = 0; x < sizeX; x++)
02477                     {
02478                         if (x >= sizeXOld || y >= sizeYOld)
02479                         {
02480                             gridData[nextPos].X = 0.0f;
02481                             gridData[nextPos].Y = 0.0f;
02482 
02483                         }
02484                         else
02485                         {
02486 
02487                             float xVal = BitConverter.ToSingle(reader.ReadBytes(4), 0);
02488                             float yVal = BitConverter.ToSingle(reader.ReadBytes(4), 0);
02489                             float Z_unused = BitConverter.ToSingle(reader.ReadBytes(4), 0);
02490 
02491                             gridData[nextPos].X = xVal;
02492                             gridData[nextPos].Y = yVal;
02493 
02494                             nextPos++;
02495                         }
02496 
02497                     }
02498                 }
02499 
02500             }
02501             catch (EndOfStreamException e)
02502             {
02503                 Console.WriteLine(e.Message);
02504             }
02505             finally
02506             {
02507                 reader.Close();
02508                 file.Close();
02509             }
02510 
02511             #endregion
02512 
02513             reader.Close();
02514             file.Close();
02515 
02516             #endregion
02517 
02518             #region read .dat
02519             channelData = new FlowChannel[datFileNames.Count];
02520 
02521             for (int i = 0; i < channelNumber; i++)
02522             {
02523                 channelData[i] = new FlowChannel(sizeX, sizeY, channelNumber, i);
02524             }
02525 
02526             for (int i = 0; i < datFileNames.Count; i++)
02527             {
02528                 Stream datFile = new FileStream(datFileNames[i], FileMode.Open);
02529                 BinaryReader datReader = new BinaryReader(datFile);
02530 
02531                 int nextPos1 = 0;
02532                 for (int y = 0; y < sizeYOld; y++)
02533                 {
02534                     for (int x = 0; x < sizeXOld; x++)
02535                     {
02536 
02537                         Vector3 gridPos = new Vector3();
02538                         gridPos.X = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
02539                         gridPos.Y = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
02540                         gridPos.Z = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
02541 
02542                         channelData[i].Velocity.VelocityValues[nextPos1] = gridPos;
02543 
02544                         for (int j = 0; j < channelNumber; j++)
02545                         {
02546                             channelData[i].AddChannels[j].ChannelValues[nextPos1] = BitConverter.ToSingle(datReader.ReadBytes(4), 0);
02547                         }
02548                     }
02549                 }
02550                 datReader.Close();
02551                 datFile.Close();
02552             }
02553 
02554             #endregion
02555 
02556             #region initialize dimensions
02557             int firstIdx = 0;
02558             int lastIdx = (sizeXOld * sizeYOld) - 1;
02559             boundaryMin = gridData[firstIdx];
02560             boundaryMax = gridData[lastIdx];
02561             boundaryLength = boundaryMax - boundaryMin;
02562 
02563             //if this work!?
02564             //if X and Y are swapped... meaning that going in a row the y value increases and x stays the same
02565             if (gridData[sizeX - 1].Y > (boundaryMin.Y + boundaryMax.Y) * 0.5)
02566             {
02567                 //this flag will fix that, anywhere where it's neccerasy... watch it :)
02568                 isFlipped = true;
02569                 Console.WriteLine("Flipped Y and X dimensions.");
02570             }
02571             else isFlipped = false;
02572 
02573             #endregion
02574 
02575         }
02576 
02583         private ushort calculatePowerOfTwo(int value)
02584         {
02585             //check if value is power of to
02586             if (value > 0)
02587             {
02588                 if ((value & (value - 1)) == 0) return (ushort)value;
02589 
02590                 //calculate the next highest power of two
02591                 else
02592                 {
02593                     value--;
02594                     for (int i = 1; i < sizeof(int) * 8; i <<= 1)
02595                     {
02596                         value = value | value >> 1;
02597                     }
02598 
02599                     ushort returnValue = (ushort)(value + 1);
02600                     return returnValue;
02601                 }
02602             }
02603             else
02604             {
02605                 return 1;
02606             }
02607         }
02608         #endregion
02609 
02610         #region depricated
02611         /*private void createUniformGrid()
02612         {
02613             GraphicsDevice device = Game.GraphicsDevice;
02614             PresentationParameters param = Game.GraphicsDevice.PresentationParameters;
02615             SurfaceFormat format = param.BackBufferFormat;
02616             int width = device.PresentationParameters.BackBufferWidth;
02617             int height = device.PresentationParameters.BackBufferHeight;*/
02618 
02619         //VertexDeclaration vert = new VertexDeclaration(device, channel1Vertices); 
02620         /*renderTarget = new RenderTarget2D(device, width, height, 1, format,
02621             device.DepthStencilBuffer.MultiSampleType,
02622             device.PresentationParameters.MultiSampleQuality);*/
02623 
02624         /*Vector2 boundaryMin = gridData[0, 0];
02625         Vector2 boundaryMax = gridData[sizeX-1, sizeY-1];
02626 
02627         Vector2 boundaryLength = boundaryMax - boundaryMin;
02628         Vector2 scale = new Vector2(1.0f,1.0f)/boundaryLength;
02629 
02630         scaleValues(scale);
02631         generateMesh();
02632 
02633         grid = new Texture2D(device, width, height);
02634         grid.SetData<VertexPositionColor>(channel1Vertices);
02635 
02636     }*/
02637 
02638         #endregion
02639     }
02640 }

Generated on Wed Jan 19 2011 21:59:17 for flowvis-2 by  doxygen 1.7.2