private bool IsCollision(IGeometry collidableElement, Point startPoint, Point endPoint, string connectionName, string collisionObjectName) { RayTracer rayTrace = new RayTracer(startPoint, endPoint); rayTrace.RayLineCreated = OnRayLineCreated; bool result = false; foreach (var vertex in collidableElement.Vertices) { foreach (var connection in vertex.VertexConnections) { Line line = new Line(connection.Vertex1.Position.Point, connection.Vertex2.Position.Point); rayTrace.Name = collisionObjectName; if (rayTrace.IsCollision(line)) { result = true; } } } if (result) { return(true); } else { return(false); } }
void GenerateMap() { List <Transform> children = new List <Transform>(); foreach (Transform child in transform) { children.Add(child); } foreach (Transform child in children) { if (Application.isPlaying) { Destroy(child.gameObject); } else { DestroyImmediate(child.gameObject); } } if (cellPrefab != null) { for (int i = 0; i < map.w; i++) { for (int j = 0; j < map.h; j++) { Transform instance = Instantiate <Transform>(cellPrefab, RayTracer.GetCellPosition(new Cell(i, j)), Quaternion.identity, transform); instance.transform.localScale = new Vector3(1, Mathf.Max(0.01f, map.GetHeight(i, j)), 1); instance.transform.localRotation = Quaternion.Euler(new Vector3(0, 30, 0)); instance.GetComponent <MapCell>().cell = new Cell(i, j); } } } }
public void Can_save_ppm_as_png() { // Arrange // use a string builder to build a 2d image of a gradient var nx = 200; var ny = 100; var rayTracer = new RayTracer(nx, ny); for (var j = ny - 1; j >= 0; j--) { for (var i = 0; i < nx; i++) { var col = new Vec3( (float)i / (float)nx, (float)j / (float)ny, 51); var ir = Math.Round(255.99 * col.X); var ig = Math.Round(255.99 * col.Y); rayTracer.AddToImageBuffer($"{ir} {ig} {col.Z}"); } } // Act var filename = "test_ppm_as_png.png"; rayTracer.SaveImageFromPPM(filename); // Assert Assert.That(VerifyImage("can_save_ppm_as_png_expected_output.png", filename), Is.True); }
public static void Main(String[] argv) { RayTracer rt = new RayTracer(); rt.size = 0; rt.width = rt.datasizes[rt.size]; rt.height = rt.datasizes[rt.size]; // create the objects to be rendered rt.scene = rt.createScene(); // get lights, objects etc. from scene. rt.setScene(rt.scene); rt.numobjects = rt.scene.Objects.Count; // Set interval to be rendered to the whole picture // (overkill, but will be useful to retain this for parallel versions) Interval interval = new Interval(0, rt.width, rt.height, 0, rt.height, 1); // Do the business! rt.render(interval); rt.validate(); }
public void Moving(MouseEventArgs e) { if (!enable) { return; } Camera camera = RayTracer.GetInstance().GetScene().GetActiveCamera(); if (m_isMouseHandleMoving) { int deltaX = e.X - m_mousePosX; int deltaY = e.Y - m_mousePosY; Vector3 right = camera.right; Vector3 up = camera.up; Vector3 pos = camera.position; pos = pos + up * kMouseMoveSpeed * deltaY - right * kMouseMoveSpeed * deltaX; camera.position = pos; m_mousePosX = e.X; m_mousePosY = e.Y; } else if (m_isMouseHandleRotating) { int deltaX = e.X - m_mousePosX; int deltaY = e.Y - m_mousePosY; Vector3 euler = camera.euler; euler.x -= kMouseRotateSpeed * deltaY; euler.y += kMouseRotateSpeed * deltaX; camera.euler = euler; m_mousePosX = e.X; m_mousePosY = e.Y; } }
private void OnEnable() { if (instance != null) { // Instance already exists. DestroyImmediate(this); return; } instance = this; // Setup accumulate material for denoising. accumulateMat = new Material(accumulateShader); accumulateMat.hideFlags = HideFlags.HideAndDontSave; refreshRenderers = (renderers.Count > 0); refreshPointLights = (pointLights.Count > 0); // Ensure raytracer has proper parameters set up. UpdateRaytracerParams(); // Camera shouldn't be rendering anything. cachedCamera.clearFlags = CameraClearFlags.Nothing; cachedCamera.cullingMask = 0; }
public static void Main(string[] args) { int level = args.Length == 1 ? int.Parse(args[0]) : 6; byte[] pgm = new byte[RayTracer.PgmLength]; RayTracer.Render(pgm, level); File.WriteAllBytes("cs.pgm", pgm); }
public void update(RayTracer rayTracer) { if (doUpdate) { doMove(); doLook(rayTracer); } }
private void RenderLoop(int iterations) { // Create a ray tracer, and create a reference to "sphere2" that we are going to bounce var rayTracer = new RayTracer(_width, _height); var scene = rayTracer.DefaultScene; var sphere2 = (Sphere)scene.Things[0]; // The first item is assumed to be our sphere var baseY = sphere2.Radius; sphere2.Center.Y = sphere2.Radius; // Timing determines how fast the ball bounces as well as diagnostics frames/second info var renderingTime = new Stopwatch(); var totalTime = Stopwatch.StartNew(); // Keep rendering until the iteration count is hit for (_frames = 0; _frames < iterations; _frames++) { // Or the rendering task has been canceled if (_cancellation.IsCancellationRequested) { break; } // Get the next buffer var rgb = _freeBuffers.GetObject(); // Determine the new position of the sphere based on the current time elapsed double dy2 = 0.8 * Math.Abs(Math.Sin(totalTime.ElapsedMilliseconds * Math.PI / 3000)); sphere2.Center.Y = (float)(baseY + dy2); // Render the scene renderingTime.Reset(); renderingTime.Start(); ParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = _degreeOfParallelism, CancellationToken = _cancellation.Token }; if (!_parallel) { rayTracer.RenderSequential(scene, rgb); } else if (_showThreads) { rayTracer.RenderParallelShowingThreads(scene, rgb, options); } else { rayTracer.RenderParallel(scene, rgb, options); } renderingTime.Stop(); _framesPerSecond = (1000.0 / renderingTime.ElapsedMilliseconds); _freeBuffers.PutObject(rgb); } }
private void OpenToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog.Filter = "场景文件|*.scene"; DialogResult result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { RayTracer.GetInstance().GetScene().CreateFromFile(openFileDialog.FileName); } }
public void takeScreenshot(string fileName, Camera camera, HitableList world) { RayTracer rayTracer = new RayTracer(600, 800, 1, 8, (int)camera.vfov, false); rayTracer.camera.origin = camera.origin; rayTracer.camera.lookAt = camera.lookAt; rayTracer.camera.updatePos(); rayTracer.world = world; rayTracer.CreateBitmap(fileName, true, true); }
void UpdateCoords(RayTracer tracer, int *minX, int *maxX, int *minY, int *maxY, ref int count) { tracer.Step(); minX[tracer.Z] = Math.Min(tracer.X, minX[tracer.Z]); minY[tracer.Z] = Math.Min(tracer.Y, minY[tracer.Z]); maxX[tracer.Z] = Math.Max(tracer.X, maxX[tracer.Z]); maxY[tracer.Z] = Math.Max(tracer.Y, maxY[tracer.Z]); count = Math.Max(count, tracer.Z); }
public void Setup() { // create a mock gameobject GameObject gameObj = new GameObject("Source"); source = GameObject.Instantiate(gameObj).transform; // create raytracer instance for the mock tracer = new RayTracer(source.transform); }
private void openToolStripMenuItem_Click( object sender, EventArgs e ) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Scene|*.ssrt"; DialogResult dr = ofd.ShowDialog(); if( dr == DialogResult.OK ) { Model model = new Model(); int ret = model.load( ofd.FileName ); if( ret != 0 ) { MessageBox.Show( string.Format( "Could not load file {0}\nError code: {1}", ofd.FileName, ret ) ); return; } g_renderBitmap = new Bitmap( model.m_width, model.m_height, PixelFormat.Format24bppRgb ); pictureBox1.Image = g_renderBitmap; g_data = new byte[model.m_width * model.m_height][]; tracer = new RayTracer( model, g_data ); DateTime startTime = DateTime.Now; new Thread( () => { while( tracer.isStillTracing() ) { tracer.traceLine(); tracer.updateBitmap(); BitmapData bmpData = g_renderBitmap.LockBits( new Rectangle( 0, 0, g_renderBitmap.Width, g_renderBitmap.Height ), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb ); byte[] imgdata = new byte[model.m_width * model.m_height * 3]; int pos = 0; for( int i = 0; i < g_data.Length; i++ ) { for( int j = 0; j < 3; j++ ) { imgdata[pos++] = g_data[i][j]; } } System.Runtime.InteropServices.Marshal.Copy( imgdata, 0, bmpData.Scan0, imgdata.Length ); g_renderBitmap.UnlockBits( bmpData ); if(this.IsDisposed){ return; } Invoke( new Action( () => { pictureBox1.Refresh(); var elapsed = DateTime.Now - startTime; lblElapsed.Text = elapsed.TotalSeconds.ToString(); } ) ); } } ).Start(); } }
private void doLook(RayTracer rayTracer) { Vec3 strafe = new Vec3(); double strafeSpeed = 0.08; bool changed = false; if (Program.input.IsKeyHeld(OpenTK.Input.Key.Up)) { strafe.x -= strafeSpeed / 2; changed = true; } if (Program.input.IsKeyHeld(OpenTK.Input.Key.Down)) { strafe.x += strafeSpeed / 2; changed = true; } if (Program.input.IsKeyHeld(OpenTK.Input.Key.Left)) { strafe.y -= strafeSpeed; changed = true; } if (Program.input.IsKeyHeld(OpenTK.Input.Key.Right)) { strafe.y += strafeSpeed; changed = true; } if (Program.input.IsKeyRising(OpenTK.Input.Key.P)) { takeScreenshot("ScreenShot0.bmp", this, rayTracer.world); } if (changed) { Vector4 temp = lookAt - origin; if (strafe.y != 0) { temp += Vector4.Transform(temp, Matrix4x4.CreateFromAxisAngle(Vec3.cross(Vec3.cross(vup, (lookAt - origin)), (lookAt - origin)), (float)strafe.y)); } if (strafe.x != 0) { temp += Vector4.Transform(temp, Matrix4x4.CreateFromAxisAngle(Vec3.cross(vup, (lookAt - origin)), (float)strafe.x)); } lookAt = origin + Vec3.unitVector(temp); updatePos(); } }
public void StartRayTrace() { var rayTraceConfguration = new RayTraceConfigurationModel { Width = rayTraceViewModel.BitmapWidth, Height = rayTraceViewModel.BitmapHeight, Samples = rayTraceViewModel.RenderSamples, UpdateRate = rayTraceViewModel.RenderUpdateRate, }; var sceneType = Int32.Parse(rayTraceViewModel.CurrentScene.Number); var aspect = (double)rayTraceConfguration.Width / (double)rayTraceConfguration.Height; IScene scene; switch (sceneType) { default: case 0: scene = new CoverSceneRT1(aspect); break; case 1: scene = new MaterialsScene(aspect); break; case 2: scene = new DefocusBlurScene(aspect); break; case 3: scene = new TestScene1(aspect); break; case 4: scene = new TestScene2(aspect); break; case 5: scene = new CoverSceneRT1Motion(aspect); break; case 6: scene = new CheckerTextureScene(aspect); break; case 7: scene = new NoiseTextureScene(aspect); break; case 8: scene = new GlobeScene(aspect); break; case 9: scene = new SimpleLightScene(aspect); break; case 10: scene = new RoomScene(aspect); break; case 11: scene = new VolumeScene(aspect); break; case 12: scene = new CoverSceneRT2(aspect); break; } var rayTracer = new RayTracer(scene); var rayTraceTarget = new RayTraceTargetAdapter ( progress => rayTraceViewModel.Progress = progress, (x, y, c) => rayTraceViewModel.SetBitmapPixel(x, y, ColorFactory.CreateSquare(c)) ); rayTraceProcess = new RayTraceProcessHandler(rayTraceConfguration, rayTracer, rayTraceTarget); rayTraceProcess.StartAsync(); }
static void Main(string[] args) { Console.WriteLine("Outputing image..."); RayTracer image = new RayTracer(); image.Progress += ProgressHandler; int numberOuptutFiles = Directory.GetFiles(OUTPUT_PATH).Count(); image.Output(OUTPUT_PATH + "image_" + numberOuptutFiles + ".ppm"); Console.WriteLine("Outputing image DONE"); }
public MainWindow() { InitializeComponent(); _shadowQuality = ShadowQuality.Smooth; _grid = new Cell[CellRows, CellCols]; _smoothedIntensities = new float[CellRows, CellCols]; for (int r = 0; r < CellRows; r++) { for (int c = 0; c < CellCols; c++) { _grid[r, c] = new Cell(); } } _gameObjects = new List <IGameObject>(); _rayEmitters = new List <IRayEmitter>(); var player = new Character(new Vector2(400, 200)); _gameObjects.Add(player); _rayEmitters.Add(player); _rayTracer = new RayTracer(_grid); _shadowShader = new ShadowShader(); _caveBrush = new TextureBrush(new Bitmap("Content/background.png")); _background = new Bitmap(Width, Height, PixelFormat.Format32bppPArgb); _frameBuffer = new Bitmap(Width, Height, PixelFormat.Format32bppPArgb); _writeableBitmap = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgr32, null); Canvas.Source = _writeableBitmap; using (Graphics graphics = Graphics.FromImage(_frameBuffer)) { graphics.Clear(Color.Black); } AddSurfaces(); _gameTime = new GameTime(); _controller = new Controller(); _isRendering = true; _renderThread = new Thread(RenderLoop); _renderThread.Start(); }
/// <summary> /// Event occurs when the pixel grid needs to be re-painted. /// </summary> private void pixelGrid_Paint(object sender, PaintEventArgs e) { // Initialize required objects SyntheticCamera c = new SyntheticCamera(_e, _g, _p, 15, 150, 45.0, 1.0, pixelGrid.Grid.Width, pixelGrid.Grid.Height); DrawingController drawer = new DrawingController(e.Graphics); RayTracer ray = new RayTracer(c, 1); int superWidth = pixelGrid.Grid.Width * ray.ResolutionMultiplier; int superHeight = pixelGrid.Grid.Height * ray.ResolutionMultiplier; // Buffer holds the super width and super height colors to eventually avg and render. Color[,] buffer = new Color[superHeight, superWidth]; // Loop through each pixel and trace a ray through it to find an intersection with the object Parallel.For(0, superHeight, (y) => { Parallel.For(0, superWidth, (x) => { PointLight pointLight = new PointLight(Color.FromScRgb(1, 1, 1, 1), new Point3D(1000, 1000, 1000)); DirectionalLight sun = new DirectionalLight(Color.FromScRgb(1, 1, 1, 1), new Vector3D(0, 0, -1)); buffer[y, x] = ray.RayTrace(_objects, x, y, pointLight, sun); }); }); // Calculates the avg's of the super resolution buffer and displys to screen. for (int i = 0; i < buffer.GetLength(0); i += ray.ResolutionMultiplier) { for (int j = 0; j < buffer.GetLength(1); j += ray.ResolutionMultiplier) { // Add all the rbg values for each super resolution block of points. float r = 0, g = 0, b = 0; for (int m = 0; m < ray.ResolutionMultiplier; ++m) { for (int n = 0; n < ray.ResolutionMultiplier; ++n) { r += buffer[i + m, j + n].ScR; g += buffer[i + m, j + n].ScG; b += buffer[i + m, j + n].ScB; } } // Avg the block of points to 1 pixel float avgR = (float)(r / Math.Pow(ray.ResolutionMultiplier, 2)); float avgG = (float)(g / Math.Pow(ray.ResolutionMultiplier, 2)); float avgB = (float)(b / Math.Pow(ray.ResolutionMultiplier, 2)); drawer.Color = Color.FromScRgb(1, avgR, avgG, avgB).ToDColor(); drawer.DrawPoint(new System.Drawing.Point(j / ray.ResolutionMultiplier, i / ray.ResolutionMultiplier)); } } }
private void OnDisable() { instance = null; DestroyImmediate(accumulateMat); if (pointLightBuffer != null) { pointLightBuffer.Dispose(); } if (sphereRenderer != null) { sphereRenderer.Dispose(); } }
private void RayTracerForm_Load(object sender, EventArgs e) { this.Show(); RayTracer rayTracer = new RayTracer(width, height, (int x, int y, System.Drawing.Color color) => { bitmap.SetPixel(x, y, color); if (x == 0) { pictureBox.Refresh(); } }); rayTracer.Render(rayTracer.DefaultScene); pictureBox.Invalidate(); }
public void Scalling(MouseEventArgs e) { if (!enable) { return; } if (e.Button == MouseButtons.None) { Camera camera = RayTracer.GetInstance().GetScene().GetActiveCamera(); Vector3 forward = camera.forward; Vector3 pos = camera.position; pos += forward * kMouseScallingSpeed * e.Delta; camera.position = pos; } }
public void Can_Draw_Background() { // Arrange var rayTracer = new RayTracer(200, 100); // Act rayTracer.RenderScene(); var fileName = "Can_Draw_Background.png"; rayTracer.Frame.SaveFrameBufferToDisk(TestContext.CurrentContext.WorkDirectory + "/" + fileName); // Assert Assert.That(VerifyImage(fileName), Is.True); }
static void Main(string[] args) { var scene = new Scene(); scene.Objects.Add(new SphereObject() { Center = Engine.Point.Origin, Radius = 10, Material = new LightMaterial() { GlowSpectrum = new LightSpectrum() } }); var eye = new PixelEye <Color>() { Width = 100, Height = 100, HorizontalFieldOfView = Math.PI / 2, VerticalFieldOfView = Math.PI / 2, Retina = new DrawingColorRetina(), Gaze = new Gaze(new Ray() { Origin = new Engine.Point(0, 0, -70), Direction = UnitVector.K }, -UnitVector.J) }; var tracer = new RayTracer() { Scene = scene, Eye = eye }; tracer.TraceRays(); var image = new Bitmap(eye.Width, eye.Height); for (int x = 0; x < image.Width; x++) { for (int y = 0; y < image.Height; y++) { image.SetPixel(x, y, eye[x, y]); } } image.Save(@"..\..\..\..\tester.png"); }
private void RenderLoop(int iterations) { // Create a ray tracer, and create a reference to "sphere2" that we are going to bounce var rayTracer = new RayTracer(_width, _height); var scene = rayTracer.DefaultScene; var sphere2 = (Sphere)scene.Things[0]; // The first item is assumed to be our sphere var baseY = sphere2.Radius; sphere2.Center.Y = sphere2.Radius; // Timing determines how fast the ball bounces as well as diagnostics frames/second info var renderingTime = new Stopwatch(); var totalTime = Stopwatch.StartNew(); // Keep rendering until the iteration count is hit for (_frames = 0; _frames < iterations; _frames++) { // Or the rendering task has been canceled if (_cancellation.IsCancellationRequested) { break; } // Get the next buffer var rgb = _freeBuffers.GetObject(); // Determine the new position of the sphere based on the current time elapsed double dy2 = 0.8 * Math.Abs(Math.Sin(totalTime.ElapsedMilliseconds * Math.PI / 3000)); sphere2.Center.Y = (float)(baseY + dy2); // Render the scene renderingTime.Reset(); renderingTime.Start(); ParallelOptions options = new ParallelOptions { MaxDegreeOfParallelism = _degreeOfParallelism, CancellationToken = _cancellation.Token }; if (!_parallel) rayTracer.RenderSequential(scene, rgb); else if (_showThreads) rayTracer.RenderParallelShowingThreads(scene, rgb, options); else rayTracer.RenderParallel(scene, rgb, options); renderingTime.Stop(); _framesPerSecond = (1000.0 / renderingTime.ElapsedMilliseconds); _freeBuffers.PutObject(rgb); } }
public void Can_Draw_sphere_on_background() { // Arrange var rayTracer = new RayTracer(200, 100); var sphere = new Sphere(new Vec3(0, 0, -1), 0.5, new Vec3(1, 0, 0)); rayTracer.SceneObjects.Add(sphere); // Act rayTracer.RenderScene(); var fileName = $"{TestContext.CurrentContext.Test.MethodName}.png"; rayTracer.Frame.SaveFrameBufferToDisk(TestContext.CurrentContext.WorkDirectory + "/" + fileName); // Assert Assert.That(VerifyImage(fileName), Is.True); }
public void Run() { try { Scene scene = UnifiedScenesRepository.Scenes["DistributedRT"]; //Scene scene = Scene.Load(@"D:\Models & Textures\HandAnimation.xml"); //Scene scene = Scene.Load(@"c:\temp\Scene1.xml"); if (scene != null) { RayTracer tracer = new RayTracer(scene); //scene.DefaultCamera = scene.Cameras["MinhaCamera"]; foreach (Primitive primi in scene.Primitives) { if (primi is TriangleModel) { ((TriangleModel)primi).Load(); } } using (Bitmap bFrame = new Bitmap((int)scene.DefaultCamera.ResX, (int)scene.DefaultCamera.ResY)) { Point3D eye = scene.DefaultCamera.Eye; float degreesToRotate = 0.5f; int count = 0; for (float i = 0; i < 360.0; i += degreesToRotate) { //2PI = 360 //xpi = 0.1 = 0.2PI = x * 360 = x = 0.2/360 eye.RotateAxisY(((2f * (float)Math.PI) * degreesToRotate / 360.0f)); scene.DefaultCamera.Eye = eye; tracer.Render(Graphics.FromImage(bFrame)); //FrameViewForm.Instance.FrameView.AddFrame(bFrame); bFrame.Save(@"d:\temp\frames\frame_" + count + ".png", ImageFormat.Png); count++; } } } } catch (Exception ex) { MessageBox.Show("Erro de Execução: " + ex.Message); } }
private void RenderOneTo(string fileName, bool wirteToFile) { // Create a ray tracer, and create a reference to "sphere2" that we are going to bounce var rayTracer = new RayTracer(_width, _height); var scene = rayTracer.DefaultScene; var sphere2 = (Sphere)scene.Things[0]; // The first item is assumed to be our sphere var baseY = sphere2.Radius; sphere2.Center.Y = sphere2.Radius; var rgb = new Color[_width * _height]; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); rayTracer.RenderSequential(scene, rgb); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); if (wirteToFile) { var file = new System.IO.StreamWriter(fileName); file.WriteLine("P3"); file.WriteLine(_width + " " + _height); file.WriteLine("255"); for (int i = 0; i < _height; i++) { for (int j = 0; j < _width; j++) { var point = rgb[i * _height + j]; file.Write(String.Format("{0,-3}", Color.ToInt32(point.R)) + " " + String.Format("{0,-3}", Color.ToInt32(point.G)) + " " + String.Format("{0,-3}", Color.ToInt32(point.B)) + " "); } file.Write("\n"); } } }
public void Measure(Data data) { // Run for a second long start = JavaSystem.CurrentTimeMillis(); long elapsed = 0; int i = 0; while (elapsed < 1000) { RayTracer.renderScene(null); i++; elapsed = JavaSystem.CurrentTimeMillis() - start; } if (data != null) { data.runs += i; data.elapsed += elapsed; } }
static async Task Main(string[] args) { var rayTracer = new RayTracer(1024, 768); rayTracer.Progress += remaining => Console.WriteLine("Remaining scan lines: {0}", remaining); var world = new HittableList(); world.Add(new Sphere(new Vector3(0, 0, -1), 0.5d)); world.Add(new Sphere(new Vector3(0, -50.5d, -1), 50)); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "result.ppm"); using (var fileStream = new FileStream(filePath, FileMode.Create)) { using (var result = await rayTracer.Go <PpmOutput>(world)) { await result.CopyToAsync(fileStream); } } }
public void restartRenderer() { displayTimer = new UpdateStatsTimer(); if (rtRenderer != null) { rtRenderer.JoinRenderThread(); rtRenderer.dispose(); rtRenderer = null; } try { rtRenderer = new RayTracer(frame, width, height, targetFPS, maxBounces, forceCPU); } catch (Exception e) { FPS.Content = e.ToString(); Trace.WriteLine(e.ToString()); } }
public void Can_Draw_Background() { // Arrange var nx = 200; var ny = 100; var rayTracer = new RayTracer(nx, ny); var lowerBound = new Vec3(-2, -1, -1); var dx = new Vec3(4, 0, 0); var dy = new Vec3(0, 2, 0); var origin = new Vec3(0, 0, 0); // Act for (int j = ny - 1; j >= 0; j--) { for (int i = 0; i < nx; i++) { var u = (double)i / (double)nx; var v = (double)j / (double)ny; var currentPoint = lowerBound.Add(dx.Scale(u).Add(dy.Scale(v))); var ray = new Ray(origin, currentPoint); var colour = ColourByRay(ray); var r = (int)(colour.X * 255); var g = (int)(colour.Y * 255); var b = (int)(colour.Z * 255); rayTracer.AddToImageBuffer($"{r} {g} {b}"); } } var fileName = "Can_Draw_Background.png"; rayTracer.SaveImageFromPPM(fileName); // Assert Assert.That(VerifyImage(fileName, fileName), Is.True); }
public void Run() { try { Scene scene = UnifiedScenesRepository.Scenes["DistributedRT"]; //Scene scene = Scene.Load(@"D:\Models & Textures\HandAnimation.xml"); //Scene scene = Scene.Load(@"c:\temp\Scene1.xml"); if(scene != null) { RayTracer tracer = new RayTracer(scene); //scene.DefaultCamera = scene.Cameras["MinhaCamera"]; foreach(Primitive primi in scene.Primitives) { if(primi is TriangleModel) { ((TriangleModel)primi).Load(); } } using(Bitmap bFrame = new Bitmap((int)scene.DefaultCamera.ResX, (int)scene.DefaultCamera.ResY)) { Point3D eye = scene.DefaultCamera.Eye; float degreesToRotate = 0.5f; int count = 0; for(float i = 0; i < 360.0; i += degreesToRotate) { //2PI = 360 //xpi = 0.1 = 0.2PI = x * 360 = x = 0.2/360 eye.RotateAxisY(((2f * (float)Math.PI) * degreesToRotate / 360.0f)); scene.DefaultCamera.Eye = eye; tracer.Render(Graphics.FromImage(bFrame)); //FrameViewForm.Instance.FrameView.AddFrame(bFrame); bFrame.Save(@"d:\temp\frames\frame_" + count + ".png", ImageFormat.Png); count++; } } } } catch(Exception ex) { MessageBox.Show("Erro de Execução: " + ex.Message); } }
void UpdateCoords( RayTracer tracer, int* minX, int* maxX, int* minY, int* maxY, ref int count) { tracer.Step(); minX[tracer.Z] = Math.Min( tracer.X, minX[tracer.Z] ); minY[tracer.Z] = Math.Min( tracer.Y, minY[tracer.Z] ); maxX[tracer.Z] = Math.Max( tracer.X, maxX[tracer.Z] ); maxY[tracer.Z] = Math.Max( tracer.Y, maxY[tracer.Z] ); count = Math.Max( count, tracer.Z ); }