int main() { RayTracer r; r.Initialize(); r.Render(); r.Clean(); return 0; }
void Window::renderRayImage () { qglviewer::Camera * cam = viewer->camera (); RayTracer * rayTracer = RayTracer::getInstance (); qglviewer::Vec p = cam->position (); qglviewer::Vec d = cam->viewDirection (); qglviewer::Vec u = cam->upVector (); qglviewer::Vec r = cam->rightVector (); Vec3Df camPos (p[0], p[1], p[2]); Vec3Df viewDirection (d[0], d[1], d[2]); Vec3Df upVector (u[0], u[1], u[2]); Vec3Df rightVector (r[0], r[1], r[2]); float fieldOfView = cam->fieldOfView (); float aspectRatio = cam->aspectRatio (); unsigned int screenWidth = cam->screenWidth (); unsigned int screenHeight = cam->screenHeight (); QTime timer; timer.start (); viewer->setRayImage(rayTracer->render (camPos, viewDirection, upVector, rightVector, fieldOfView, aspectRatio, screenWidth, screenHeight)); statusBar()->showMessage(QString ("Raytracing performed in ") + QString::number (timer.elapsed ()) + QString ("ms at ") + QString::number (screenWidth) + QString ("x") + QString::number (screenHeight) + QString (" screen resolution")); viewer->setDisplayMode (GLViewer::RayDisplayMode); }
/** * Not-So-Simple raytracer demo by Hoanh Nguyen. * @param argc Not used. * @param argv Not used. * @return 0. */ int main( int argc, char **argv ) { Engine::init( &argc, argv, "Raytracer" ); GLint program = Angel::InitShader( "shaders/vRaytracer.glsl", "shaders/fRaytracer.glsl" ); rt.init( program ); if (1) { Object *bottle = Engine::instance()->rootScene()->addObject( "bottle", program ); ObjLoader::loadModelFromFile( bottle, "../models/bottle_wine_med.obj" ); //ObjLoader::loadMaterialFromFile( bottle, "../models/bottle_wine_med.mtl" ); rt.pushDataToBuffer(); } else { rt.legacySceneGen(); } glutDisplayFunc( RTdisplay ); // register callback w/Window System boost::thread zipo( aRomanticEvening ); GLCHECK(); Engine::run(); printf("This doesnt exit cleanly... woops.\n"); rt.thisDateIsOver(); zipo.join(); return EXIT_SUCCESS; }
int main(int argc, char * argv[]) { if (argc < 2) { cerr << "Usage: transforms scenefile [grader input (optional)]\n"; exit(-1); } char * sceneFile = argv[1]; cout << "Scene File: " << sceneFile << endl; string fname = string("imgResult.png"); RayTracer tracer; Camera * cam = new Camera(); Scene * scene = new Scene(); readfile(sceneFile, cam, scene); MyImage image = tracer.RayTrace(cam, scene, RENDERSETTINGS->width, RENDERSETTINGS->height); SaveImageFile(image, "" + RENDERSETTINGS->outputFile); system("PAUSE"); return 0; }
void traceImage(void){ RayTracer tracer; pixels = tracer.runRayTracer(); }
int main (int argc, char *argv[]) { srand (time (NULL)); omp_set_nested (1); omp_set_num_threads (16); // process command line parse_commandline (&argc, &argv); LOG (INFO) << "rtrt init"; Window win (FLAGS_width, FLAGS_height, FLAGS_fullscreen, "Real-time Ray Tracer", FLAGS_interval); Image front (win.width(), win.height()), back (win.width(), win.height()); // create the images Image *front_p = &front, *back_p = &back; World world; //world.fill(75, 4); world.demo0(); RayTracer rt (world); #pragma omp parallel { #pragma omp single nowait { while (win.is_running()) { // update frame PerformanceMonitor::instance().RT_FPS.count(); //win.update_frame_rate(); win.clearXY(); // render the new back buffer rt.render (back_p); // swap buffers std::swap (front_p, back_p); } } #pragma omp master { while (win.is_running()) { // main rendering loop, keep rendering the front buffer PerformanceMonitor::instance().GL_FPS.count(); win.clear(); // clear the render windows back buffer if (FLAGS_fps) { win.update_title_with_frame_rate(); // show the frame rate in the window title } win.render_image (*front_p); // render the image to the back buffer win.update(); // swap the back buffer with the front buffer PerformanceMonitor::instance().update(); } } } LOG (INFO) << "shutting down"; LOG (INFO) << "Average frame rate was " << win.average_framerate(); front.destroy_image(); back.destroy_image(); win.destroy_window(); LOG (INFO) << PerformanceMonitor::instance(); return (0); }
int Scene::render() { RayTracer raytracer; Camera camera(options); Film film(options); Sampler sampler(options); Sample sample; Ray ray; Color color; while(sampler.generate_sample(sample)) { camera.generate_ray(sample, ray); raytracer.trace(options, ray, color, options.maxdepth); film.commit(sample, color); } return film.write_image(); };
RayTracerController::RayTracerController(RayTracer &rt, QObject *parent) : QObject(parent), m_rt(rt), m_rtThread(rt), m_imageProcessor(rt.imageProcessor()) { connect(&m_rtThread, SIGNAL(finished()), SLOT(rayTracerThreadFinished())); }
int main(int argc, char *argv[]) { settings.parse(argc, argv); settings.print(); //Timer t; //StopWatch sw; //sw.setTimer(&t); //sw.start("Begining"); Scene *scene = SceneFactory::load(settings.input()); //sw.lap("Datastructure built"); RayFrameBuffer fb(settings.width(), settings.height()); printf("..\n"); RayTracer *rayTracer = NULL; if (settings.useThreads()) { rayTracer = new ThreadedRayTracer(scene, &fb); } else { rayTracer = new RayTracer(scene, &fb); } //rayTracer.setEnvironmentMap(new EnvironmentMap("./texture/earth.jpg")); // if (settings.environmentMap()) { rayTracer->setEnvironmentMap(new EnvironmentMap(settings.environmentMap())); } rayTracer->setAntiAliasingResolution(settings.valias(), settings.halias()); rayTracer->render(); //sw.lap("Scene Rendered"); printf("wtf\n"); fb.write(settings.output()); delete rayTracer; //sw.stop(); delete scene; //sw.print(); printLightStats(); return 0; }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); if (app.arguments().size() == 2 && app.arguments().at(1) == "--help") { printUsage(); return 0; } InputParametersParser paramatersParser; InputParametersPointer inputParameters = paramatersParser.parseInputParameters(app.arguments()); if (inputParameters == NULL) { std::cout << "Invalid arguments passed to application" << std::endl; printUsage(); return -1; } std::cout << "Loading scene..." << std::endl; SceneLoader sceneLoader; ScenePointer scene = sceneLoader.loadScene(inputParameters->sceneFilePath); if (scene == NULL) { std::cout << "Scene loading failed" << std::endl; return -1; } std::cout << "Loading scene finished" << std::endl; RayTracer rayTracer; rayTracer.setScene(scene); rayTracer.setImageResolution(inputParameters->xResolution, inputParameters->yResolution); std::cout << "Rendering scene..." << std::endl; rayTracer.renderScene(); std::cout << "Rendering scene finished" << std::endl; std::cout << "Saving image to file '" << inputParameters->outputFilePath.toUtf8().constData() << "'" << std::endl; rayTracer.saveRenderedImageToFile(inputParameters->outputFilePath); std::cout << "Image is saved" << std::endl; return 0; }
void threadFunction(RayTracer ray_tracer, int w) { for(int h=0;h<height;h++) { Ray ray = camera.rayThruPixel(width, height, w, h); Color col = ray_tracer.traceThisRay(ray); RGBQUAD color; color.rgbRed = col.blue; color.rgbGreen = col.green; color.rgbBlue = col.red; FreeImage_SetPixelColor(bitmap,w,h,&color); } }
int main(int ac, char **av) { if (ac < 2) { std::cout << "Missing Command" << std::endl; } SceneReader sceneReader; char* command = av[1]; std::cout << "Parsing input file... " << std::endl; sceneReader.parse(command); std::cout << "Done!" << std::endl; RayTracer rt = RayTracer(sceneReader); std::cout << "Ray Tracing... " << std::endl; bool result = rt.DrawScene(); if (!result) std::cout << "Error on rendering... " << std::endl; std::cout << "Done! image.exr" << std::endl; return 1; }
void PointLight::emitRays(quint64 count, RayTracer& rayTracer) const { // Obtain light source origin v3f origin = translation(transform()); // Emit count rays in random directions for (quint64 i=0; i<count; ++i) { // Emit ray in random direction rayTracer.processRay(Ray(origin, randomPointOnUnitSphere(), m_color, 0)); } }
int main(int argc, char *argv[]) { signal(SIGSEGV, handler); FILE* pStream; if (argc == 1) { pStream = stdin; } else if (argc == 2 && (pStream = fopen(argv[1], "r"))) { } else { usage(); } // initialization RayTracer app; app.init(pStream); app.run(); // encode raytracer image encodeOneStep("output.png", app.getFilm()->getBuffer(), OUTPUT_IMAGE_WIDTH, OUTPUT_IMAGE_HEIGHT); // clean up app.halt(); fclose(pStream); return 0; }
void RayTracer::doLightCalculations() { //hitted game object - get color Color ambient = Color(20, 10, 10); Color diffuse = Color(200, 100, 100); double diffuse_light = 0; //cycle through lights std::vector<LightSource*> * lightSources = Scene::getInstance()->getLightSources(); for (std::vector<LightSource*>::iterator it = lightSources->begin(); it != lightSources->end(); it++) { //shoot ray to light Vector3 direction = (*it)->getDirToLight(hitpoint.getPoint()); Ray rtray = Ray(hitpoint.getPoint(), direction); // + direction * 1 RayTracer rt = RayTracer(rtray); //on hit - do light calculations if (!rt.startRay()) { LightSetting ls = (*it)->getLightSetting(hitpoint.getPoint(), hitpoint.getNormal()); diffuse_light += ls.diffuse; } } color = ambient + diffuse * diffuse_light; }
int main(int ArgumentCount, char *Arguments[]) { queue<string> ArgumentQueue; bool Done = false; // Check command-line arguments if (ArgumentCount < 2) { cout << "Command-line arguments:" << endl; cout << " dsraytracer [scenefile.txt] [-split SECTION/FACTOR] [-save [FILENAME]] [-load SCREENWIDTH SCREENHEIGHT FILENAME1 FILENAME2 ...]" << endl; return EXIT_FAILURE; } // Push arguments into a queue for (int i = 1; i < ArgumentCount; i++) ArgumentQueue.push(Arguments[i]); // Create object RayTracer *Scene = new RayTracer(); Scene->SetArguments(ArgumentQueue); while (!Done) { // States switch(Scene->GetState()) { case ARGUMENTS: Scene->ProcessArguments(); break; case INIT: Scene->LoadScene(); break; case RENDERING: Scene->SetupScreen(); Scene->BuildScene(); break; case FINISHED_RENDERING: Scene->GetKeys(); break; case EXIT: Done = true; break; } } delete Scene; return EXIT_SUCCESS; }
/** * Simple program that starts our raytracer */ int main(int argc, char *argv[]) { try { RayTracer* rt; Timer t; rt = new RayTracer(800, 600); std::shared_ptr<SceneObjectEffect> color(new ColorEffect(glm::vec3(0.0, 1.0, 0.0))); std::shared_ptr<SceneObjectEffect> phong(new PhongEffect(glm::vec3(0.0, 0.0, 10.0))); std::shared_ptr<SceneObjectEffect> steel(new SteelEffect()); std::shared_ptr<SceneObjectEffect> fresnel(new FresnelEffect()); std::shared_ptr<SceneObject> s1(new Sphere(glm::vec3(-3.0f, 0.0f, 6.0f), 2.0f, steel)); rt->addSceneObject(s1); std::shared_ptr<SceneObject> s2(new Sphere(glm::vec3(3.0f, 0.0f, 3.0f), 2.0f, fresnel)); rt->addSceneObject(s2); std::shared_ptr<SceneObject> s3(new Sphere(glm::vec3(0.0f, 3.0f, 9.0f), 2.0f, steel)); rt->addSceneObject(s3); std::string path = "cubemaps/SaintLazarusChurch3/"; std::shared_ptr<SceneObject> cubeMap(new CubeMap(path + "posx.jpg", path + "negx.jpg", path + "posy.jpg", path + "negy.jpg", path + "posz.jpg", path + "negz.jpg")); rt->addSceneObject(cubeMap); std::shared_ptr<SceneObject> triangle(new Triangle(glm::vec3(0.0f, 2.0f, -1.0f), glm::vec3(-2.0f, -2.0f, -1.0f), glm::vec3(2.0f, -2.0f, 0.0f), steel)); rt->addSceneObject(triangle); t.restart(); rt->render(); double elapsed = t.elapsed(); std::cout << "Computed in " << elapsed << " seconds" << std::endl; rt->save("test", "bmp"); //We want to write out bmp's to get proper bit-maps (jpeg encoding is lossy) delete rt; } catch (std::exception &e) { std::string err = e.what(); std::cout << err.c_str() << std::endl; return -1; } return 0; }
int simulateMeasurement(Ray measurementAction, RayTracer &rayt, ros::ServiceClient pfilterAdd, double noiseStdDev) { std::random_device rd; std::normal_distribution<double> randn(0.0, noiseStdDev); tf::Point start = measurementAction.start; tf::Point end = measurementAction.end; tf::Point intersection; geometry_msgs::Point obs; geometry_msgs::Point dir; double distToPart; if(!rayt.traceRay(measurementAction, distToPart)){ ROS_INFO("NO INTERSECTION, Skipping"); return -1; } intersection = start + (end-start).normalize() * (distToPart); std::cout << "Intersection at: " << intersection.getX() << " " << intersection.getY() << " " << intersection.getZ() << std::endl; tf::Point ray_dir(end.x()-start.x(),end.y()-start.y(),end.z()-start.z()); ray_dir = ray_dir.normalize(); obs.x=intersection.getX() + randn(rd); obs.y=intersection.getY() + randn(rd); obs.z=intersection.getZ() + randn(rd); dir.x=ray_dir.x(); dir.y=ray_dir.y(); dir.z=ray_dir.z(); particle_filter::AddObservation pfilter_obs; pfilter_obs.request.p = obs; pfilter_obs.request.dir = dir; if(!pfilterAdd.call(pfilter_obs)){ ROS_INFO("Failed to call add observation"); } return 1; }
/** * Randomly chooses vectors, gets the Information Gain for each of * those vectors, and returns the ray (start and end) with the highest information gain */ void randomSelection(PlotRayUtils &plt, RayTracer &rayt, tf::Point &best_start, tf::Point &best_end) { // tf::Point best_start, best_end; double bestIG; bestIG = 0; std::random_device rd; std::uniform_real_distribution<double> rand(-1.0,1.0); for(int i=0; i<500; i++){ tf::Point start(0.5, 0.5, rand(rd)); // start = start.normalize(); tf::Point end(start.getX(), start.getY(), rand(rd)); // end.normalized(); Ray measurement(start, end); // auto timer_begin = std::chrono::high_resolution_clock::now(); double IG = rayt.getIG(measurement, 0.01, 0.002); // auto timer_end = std::chrono::high_resolution_clock::now(); // auto timer_dur = timer_end - timer_begin; // cout << "IG: " << IG << endl; // cout << "Elapsed time for ray: " << std::chrono::duration_cast<std::chrono::milliseconds>(timer_dur).count() << endl; // double IG = plt.getIG(start, end, 0.01, 0.002); if (IG > bestIG){ bestIG = IG; best_start = start; best_end = end; } } //Ray measurement(best_start, best_end); // plt.plotCylinder(best_start, best_end, 0.01, 0.002, true); ROS_INFO("Ray is: %f, %f, %f. %f, %f, %f", best_start.getX(), best_start.getY(), best_start.getZ(), best_end.getX(), best_end.getY(), best_end.getZ()); }
int gr_render_cmd(lua_State* L) { GRLUA_DEBUG_CALL; gr_node_ud* root = (gr_node_ud*)luaL_checkudata(L, 1, "gr.node"); luaL_argcheck(L, root != 0, 1, "Root node expected"); const char* filename = luaL_checkstring(L, 2); int width = (int)luaL_checknumber(L, 3); int height = (int)luaL_checknumber(L, 4); Point eye; Vector view, up; get_tuple(L, 5, &eye[0], 3); get_tuple(L, 6, &view[0], 3); get_tuple(L, 7, &up[0], 3); double fov = luaL_checknumber(L, 8); double ambient_data[3]; get_tuple(L, 9, ambient_data, 3); Colour ambient(ambient_data[0], ambient_data[1], ambient_data[2]); luaL_checktype(L, 10, LUA_TTABLE); int light_count = luaL_getn(L, 10); luaL_argcheck(L, light_count >= 1, 10, "Tuple of lights expected"); std::list<Light*> lights; for (int i = 1; i <= light_count; i++) { lua_rawgeti(L, 10, i); gr_light_ud* ldata = (gr_light_ud*)luaL_checkudata(L, -1, "gr.light"); luaL_argcheck(L, ldata != 0, 10, "Light expected"); lights.push_back(ldata->light); lua_pop(L, 1); } Scene* scene = new Scene(*root->node, lights, ambient); scene->prepare(); // XXX come back and fix this for interactive. RayTracer* rt = new RayTracer(); Camera *c = new PerspectiveCamera(eye, eye + view, up, fov, 0.1, 1000000, width, height, Prefs::sharedPrefs().lensRadius, Prefs::sharedPrefs().focalDistance); /* * Choose a very large number for the far plane so that we can acomodate * scenes with larger scales. This still won't work with all scenes. * the lua command really should be updated to pass in near and far. * Can't just use INFINITY because we get an error when constructing the * perpective projection (ie the view volume must be finite). */ Stats::sharedStats().nextRender(); // prints the last render's stats if any. std::cout << std::endl << std::endl << "Rendering " << filename << "..." << std::endl; std::cout << Prefs::sharedPrefs(); Stats::sharedStats().imageWidth = width; Stats::sharedStats().imageHeight = height; rt->render(*scene, *c, width, height); rt->getImage().savePng(*(new std::string(filename))); delete rt; return 0; }
void fixedSelection(PlotRayUtils &plt, RayTracer &rayt, tf::Point &best_start, tf::Point &best_end) { int index; double bestIG = 0; tf::Point tf_start; tf::Point tf_end; bestIG = 0; std::random_device rd; std::uniform_real_distribution<double> rand(0, 1); std::uniform_int_distribution<> int_rand(0, 3); Eigen::Vector3d start; Eigen::Vector3d end; double state[6] = {0.3, 0.3, 0.3, 0.5, 0.7, 0.5}; Eigen::Matrix3d rotationC; rotationC << cos(state[5]), -sin(state[5]), 0, sin(state[5]), cos(state[5]), 0, 0, 0, 1; Eigen::Matrix3d rotationB; rotationB << cos(state[4]), 0 , sin(state[4]), 0, 1, 0, -sin(state[4]), 0, cos(state[4]); Eigen::Matrix3d rotationA; rotationA << 1, 0, 0 , 0, cos(state[3]), -sin(state[3]), 0, sin(state[3]), cos(state[3]); Eigen::Matrix3d rotationM = rotationC * rotationB * rotationA; Eigen::Vector3d displaceV(state[0], state[1], state[2]); for(int i=0; i<500; i++){ index = int_rand(rd); if (index == 0) { double y = rand(rd) * 0.31 - 0.35; double z = rand(rd) * 0.18 + 0.03; start << 2, y, z; end << -1, y, z; } else if (index == 1) { double x = rand(rd) * 1.1 + 0.1; double z = rand(rd) * 0.18 + 0.03; start << x, -1, z; end << x, 1, z; } else if (index == 2) { double x = rand(rd) * 1.1 + 0.1; double y = rand(rd) * 0.01 - 0.02; start << x, y, 1; end << x, y, -1; } else { double x = rand(rd) * 0.02 + 0.33; double y = rand(rd) * 0.2 - 0.35; start << x, y, 1; end << x, y, -1; } Eigen::Vector3d tran_start = rotationM * start + displaceV; Eigen::Vector3d tran_end = rotationM * end + displaceV; tf_start.setValue(tran_start(0, 0), tran_start(1, 0), tran_start(2, 0)); tf_end.setValue(tran_end(0, 0), tran_end(1, 0), tran_end(2, 0)); Ray measurement(tf_start, tf_end); // auto timer_begin = std::chrono::high_resolution_clock::now(); double IG = rayt.getIG(measurement, 0.01, 0.002); // plt.plotRay(measurement); // plt.labelRay(measurement, IG); // auto timer_end = std::chrono::high_resolution_clock::now(); // auto timer_dur = timer_end - timer_begin; // cout << "IG: " << IG << endl; // cout << "Elapsed time for ray: " << std::chrono::duration_cast<std::chrono::milliseconds>(timer_dur).count() << endl; // double IG = plt.getIG(start, end, 0.01, 0.002); if (IG > bestIG){ bestIG = IG; best_start = tf_start; best_end = tf_end; } } // plt.plotCylinder(best_start, best_end, 0.01, 0.002, true); ROS_INFO("Ray is: %f, %f, %f. %f, %f, %f", best_start.getX(), best_start.getY(), best_start.getZ(), best_end.getX(), best_end.getY(), best_end.getZ()); plt.plotRay(Ray(best_start, best_end)); }
int main( int argc, char* argv[] ) { // Fill in your implementation here. // This loop loops over each of the input arguments. // argNum is initialized to 1 because the first // "argument" provided to the program is actually the // name of the executable (in our case, "a4"). string sceneInput; int sizeX; int sizeY; string outputFile; string normalFile; int depth1; int depth2; string depthFile; bool shadows = false; int bounces = 0; float weight = 0.1; int numSamples = 0; bool uniformSamples = true; bool jitteredSamples = false; float boxFilterRadius = 0.0f; bool antialiasing = false; string renderSamplesFile; int renderSamplesFactor = 1; for( int argNum = 1; argNum < argc; ++argNum ) { //std::cout << "Argument " << argNum << " is: " << argv[argNum] << std::endl; string arg = argv[argNum]; if (arg == "-input") { argNum++; sceneInput = argv[argNum]; } else if (arg == "-size") { argNum++; sscanf(argv[argNum], "%d", &sizeX); argNum++; sscanf(argv[argNum], "%d", &sizeY); } else if (arg == "-output") { argNum++; outputFile = argv[argNum]; } else if (arg == "-normals") { argNum++; normalFile = argv[argNum]; } else if (arg == "-depth") { argNum++; sscanf(argv[argNum], "%d", &depth1); argNum++; sscanf(argv[argNum], "%d", &depth2); argNum++; depthFile = argv[argNum]; } else if (arg == "-bounces") { argNum++; sscanf(argv[argNum], "%d", &bounces); } else if (arg == "-weight") { argNum++; sscanf(argv[argNum], "%f", &weight); } else if (arg == "-shadows") { shadows = true; } else if (arg == "-uniform_samples") { uniformSamples = true; argNum++; sscanf(argv[argNum], "%d", &numSamples); } else if (arg == "-jittered_samples") { jitteredSamples = true; argNum++; sscanf(argv[argNum], "%d", &numSamples); } else if (arg == "-box_filter") { argNum++; sscanf(argv[argNum], "%f", &boxFilterRadius); antialiasing = true; } else if (arg == "-render_samples") { argNum++; renderSamplesFile = argv[argNum]; argNum++; sscanf(argv[argNum], "%d", &renderSamplesFactor); } else { std::cout << "Argument not implemented " << argNum << " is: " << argv[argNum] << std::endl; } } assert(sceneInput != ""); SceneParser* sceneParser = new SceneParser( (char*)sceneInput.c_str() ); Camera* camera = sceneParser->getCamera(); Group* objects = sceneParser->getGroup(); // First, parse the scene using SceneParser. // Then loop over each pixel in the image, shooting a ray // through that pixel and finding its intersection with // the scene. Write the color at the intersection to that // pixel in your output image. float stepX = 2.0f/(sizeX); float stepY = 2.0f/(sizeY); float stepXStart = 3.0 * stepX / 8.0f; float stepYStart = 3.0 * stepY / 8.0f; int rootNumSamples = (int)sqrt(numSamples); float stepRoot = 1.0f / rootNumSamples; float stepRootStart = stepRoot / 2.0f; //float stepXrender = 2.0f/(sizeX - 1)/renderSamplesFactor; //float stepYrender = 2.0f/(sizeY - 1)/renderSamplesFactor; Image* output; Image* depth; Image* normal; SampleDebugger* render; if (outputFile != "") { output = new Image( sizeX, sizeY ); output->SetAllPixels( sceneParser->getBackgroundColor() ); } if (depthFile != "") { depth = new Image( sizeX, sizeY ); depth->SetAllPixels( Vector3f::ZERO ); } if (normalFile != "") { normal = new Image( sizeX, sizeY ); normal->SetAllPixels( Vector3f::ZERO ); } if (renderSamplesFile != "") { render = new SampleDebugger( sizeX, sizeY, numSamples ); } RayTracer rayTracer = RayTracer( sceneParser, bounces, weight, shadows ); for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { Vector2f point = Vector2f(-1 + ((x + 0.5f) * stepX), -1 + ((y + 0.5f) * stepY)); Ray ray = camera->generateRay( point ); Hit hit = Hit(); float tmin = camera->getTMin(); if (renderSamplesFile != "") { for (int i = 0; i < numSamples; i++) { int row = floor((float)i / (float)rootNumSamples); int col = i % rootNumSamples; Vector2f offset = Vector2f( stepRootStart + col * stepRoot, stepRootStart + row * stepRoot); if (jitteredSamples) { offset = Vector2f( nextFloat(), nextFloat()); } Vector3f color = sceneParser->getBackgroundColor(); Ray renderRay = camera->generateRay( point - Vector2f(0.5f * stepX, 0.5f * stepY) + (offset) * Vector2f(stepX, stepY) ); Hit renderHit = Hit(); if (objects->intersect(renderRay, renderHit, tmin)) { color = rayTracer.traceRay( renderRay, tmin, 0, 1.0, renderHit, 1.0 ); } render->setSample( x, y, i, offset, color ); } } //cout << "testing ray at " << ray << tmin << endl; bool intersected = objects->intersect( ray, hit, tmin ); if (intersected || antialiasing) { //cout << "found an intersection for " << ray << "at " << hit.getT() << endl; if (outputFile != "") { Vector3f pixelColor = sceneParser->getBackgroundColor(); if (antialiasing) { Vector3f color = Vector3f( 0 ); for (int i = 0; i < numSamples; i++) { int row = floor((float)i / (float)rootNumSamples); int col = i % rootNumSamples; Vector2f offset = Vector2f( stepRootStart + col * stepRoot, stepRootStart + row * stepRoot); if (jitteredSamples) { offset = Vector2f( nextFloat(), nextFloat() ); } Vector3f aColor = sceneParser->getBackgroundColor(); Ray renderRay = camera->generateRay( point - Vector2f(0.5f * stepX, 0.5f * stepY) + (offset) * Vector2f(2.0 * boxFilterRadius * stepX, 2.0 * boxFilterRadius * stepY) ); Hit renderHit = Hit(); if (objects->intersect(renderRay, renderHit, tmin)) { aColor = rayTracer.traceRay( renderRay, tmin, 0, 1.0, renderHit, 1.0 ); } color += aColor; } pixelColor = color / numSamples; } else if (intersected) { pixelColor = rayTracer.traceRay( ray, tmin, 0, 1.0, hit, 1.0 ); } /* Vector3f pixelColor = sceneParser->getAmbientLight() * hit.getMaterial()->getDiffuseColor(); for (int i = 0; i < sceneParser->getNumLights(); i++) { Light* light = sceneParser->getLight(i); Vector3f p = ray.pointAtParameter( hit.getT() ); Vector3f dir = Vector3f(); Vector3f col = Vector3f(); float distance = 0; light->getIllumination(p, dir, col, distance); pixelColor += hit.getMaterial()->shade( ray, hit, dir, col ); } //cout << "final pixel color: "; //pixelColor.print(); //cout << endl; */ output->SetPixel(x, y, VecUtils::clamp(pixelColor)); } if (depthFile != "") { Vector3f clamped = VecUtils::clamp(Vector3f(hit.getT()), depth1, depth2); Vector3f grayscale = (Vector3f(depth2) - clamped) / (float)(depth2 - depth1); //clamped.print(); //grayscale.print(); depth->SetPixel(x, y, grayscale); } if (normalFile != "") { normal->SetPixel(x, y, VecUtils::absoluteValue(hit.getNormal()) ); } } } } if (outputFile != "") { output->SaveTGA( (char *)outputFile.c_str() ); } if (depthFile != "") { depth->SaveTGA( (char *)depthFile.c_str() ); //printf("depth %d %d\n", depth1, depth2); } if (normalFile != "") { normal->SaveTGA( (char *)normalFile.c_str() ); } if (renderSamplesFile != "") { render->renderSamples( (char *)renderSamplesFile.c_str(), renderSamplesFactor ); } return 0; }
int main( int argc, char* argv[] ) { // Fill in your implementation here. // This loop loops over each of the input arguments. // argNum is initialized to 1 because the first // "argument" provided to the program is actually the // name of the executable (in our case, "a4"). for( int argNum = 1; argNum < argc; ++argNum ) { std::cout << "Argument " << argNum << " is: " << argv[argNum] << std::endl; } int w, h ; //img size float depthMin, depthMax; char filename[80]; char output[80]; char depthOutput[80]; char normalsOutput[80]; bool depthMode = false, normalsMode = false, imageMode = false; int max_bounces = 0; float cutoff_weight; bool shadows = false; bool refraction = false; int uniform_samples = 0; int jitter_samples = 0; float box_filter_radius; bool render_samples = false; char* render_samples_outfile; int zoom_factor; for( int i = 0 ; i < argc ; i++) { if(!strcmp(argv[i], "-input")){ strcpy(filename, argv[i+1]); } else if(!strcmp(argv[i], "-size")){ w = atoi(argv[i+1]); h = atoi(argv[i+2]); } else if(!strcmp(argv[i], "-output")){ strcpy(output , argv[i+1]); imageMode = true; } else if(!strcmp(argv[i], "-depth")){ depthMode = true; depthMin = atof(argv[i+1]); depthMax = atof(argv[i+2]); strcpy(depthOutput , argv[i+3]); } else if(!strcmp(argv[i], "-normals")){ normalsMode = true; strcpy(normalsOutput , argv[i+1]); } else if(!strcmp(argv[i], "-bounces")){ max_bounces = atoi(argv[i+1]); } else if(!strcmp(argv[i], "-weight")){ cutoff_weight = atoi(argv[i+1]); } else if(!strcmp(argv[i], "-shadows")){ shadows = true; } else if(!strcmp(argv[i], "-uniform_samples")){ uniform_samples = atoi(argv[i+1]); } else if(!strcmp(argv[i], "-jittered_samples")){ jitter_samples = atoi(argv[i+1]); } else if(!strcmp(argv[i], "-box_filter")){ box_filter_radius = atof(argv[i+1]); } else if(!strcmp(argv[i], "-render_samples")){ // strcpy(render_samples_outfile, argv[i+1]); render_samples_outfile = argv[i+1]; zoom_factor = atoi(argv[i+2]); render_samples = true; } else if (!strcmp(argv[i], "-refraction")){ refraction = true; } } // First, parse the scene using SceneParser. // Then loop over each pixel in the image, shooting a ray // through that pixel and finding its intersection with // the scene. Write the color at the intersection to that // pixel in your output image. SceneParser sp = SceneParser(filename); RayTracer rt = RayTracer(&sp, max_bounces, cutoff_weight, shadows, refraction); Image image( w , h ); Image depth( w , h ); Image normals( w,h ); Camera* camera = sp.getCamera(); // Variables for anti-aliasing SampleDebugger *sd; Hit hit; int num_samples = max(uniform_samples, jitter_samples); if (render_samples) { // cout << "render samples - now making the sample_debugger" << endl; sd = new SampleDebugger(w, h, num_samples); } // cout << "now starting iteration through pixels" << endl; for( int j = 0 ; j < h ; j++ ) { for ( int i = 0 ; i < w ; i++ ) { // if (i > 144 && j > 43) {cout << "at beginning of loop i = " << i<< "j = " << j << endl;} Vector3f pixelColor; Vector3f normalVal; // if (i > 144 && j > 43) {cout << " checking num_samples" << endl;} if (num_samples > 0) { float grid_width = sqrt(num_samples); float max_offset = 1.0/grid_width; float offset = 0; // if (i > 144 && j > 43) {cout << " where is this getting stuck - jitter samples?" << endl;} if (jitter_samples > 0) { offset += (float)rand()/RAND_MAX * max_offset; } int count = 0; Vector3f color_sum = Vector3f(0.0, 0.0, 0.0); // if (i > 144 && j > 43) {cout << " where is this getting stuck - for loop?" << endl;} for (int grid_x = 0; grid_x < grid_width; grid_x++) { for (int grid_y = 0; grid_y < grid_width; grid_y++) { // if (i > 144 && j > 43) {cout << " in second for loop: grid_x = " << grid_x << "grid y =" << grid_y << endl;} float xin = grid_x*max_offset + i + offset; float yin = grid_y*max_offset + j + offset; float normX = (float)((float)(xin-((float)w)/2))/((float)w/2); float normY = (float)((float)(yin-((float)h)/2))/((float)h/2); Ray ray = camera->generateRay( Vector2f( normX , normY ) ); hit = Hit(INFINITY, NULL, Vector3f(1,0,0)); Vector3f local_color = rt.traceRay(ray, camera->getTMin(), max_bounces, cutoff_weight, hit); color_sum += local_color; // if (i > 144 && j > 43) {cout << " where is this getting stuck first render sampels?" << endl;} if (render_samples) { cout << "1) count = " << count << endl; Vector2f offset_vec = Vector2f(max_offset*grid_x+offset, max_offset*grid_y+offset); sd->setSample(i, j, count, offset_vec, local_color); count++; } } } // if (i > 144 && j > 43) {cout << " where is this getting stuck - setting pixel color?" << endl;} pixelColor = color_sum/num_samples; } else { // float x = 2*((float)j/((float)w - 1.0f)) - 1.0f; // float y = 2*((float)i/((float)h - 1.0f)) - 1.0f; float x = (float)((float)(i+0.25-((float)w)/2))/((float)w/2); float y = (float)((float)(j+0.25-((float)h)/2))/((float)h/2); Ray ray = camera->generateRay( Vector2f( x , y ) ); // if (i > 144 && j > 43) {cout << " where is this getting stuck - tracing the ray?" << endl;} // group->intersect( ray , hit , camera->getTMin() ) ; hit = Hit(INFINITY, NULL, Vector3f(1,0,0)); Vector3f color_normal = rt.traceRay(ray, camera->getTMin(), max_bounces, cutoff_weight, hit); // if (i > 144 && j > 43) {cout << " made it through traceRay?" << endl;} pixelColor = color_normal; // if( hit.getMaterial()==NULL){ //background // // pixelColor = Scene.getBackgroundColor(); // normalVal = Vector3f(0.0,0.0,0.0); // } // else{ // //ambient light // pixelColor = PhongMaterial::pointwiseDot( Scene.getAmbientLight(), hit.getMaterial()->getDiffuseColor()); // //defussion light // for( int i = 0 ; i < Scene.getNumLights(); i++){ // Light* light = Scene.getLight(i); // Vector3f dirToLight, lightColor ; // Vector3f position = ray.pointAtParameter(hit.getT()); // float dist = hit.getT(); // light->getIllumination( position , dirToLight , lightColor , dist); // // pixelColor += hit.getMaterial()->Shade( ray , hit , dirToLight , lightColor ) ; // } // // //normal map // Vector3f n = hit.getNormal(); // normalVal = Vector3f( abs(n[0]),abs(n[1]),abs(n[2])); // } } float d = clampedDepth( hit.getT(), depthMin , depthMax); // cout << "setting pixel for i,j = " << i << ", " << j << endl; depth.SetPixel( i , j , Vector3f(d,d,d)); image.SetPixel( i , j , pixelColor ); // if (i > 144) {cout << "where is this getting stuck?" << endl;} normalVal = hit.getNormal(); for (int k = 0; k < 3; k++) { // if (i > 144) {cout << "where is this getting stuck? in normals?" << endl;} normalVal[k] = fabs(normalVal[k]); } // if (i > 144) {cout << "where is this getting stuck? setting normals?" << endl;} normals.SetPixel( i , j , normalVal) ; // if (i > 144) {cout << "where is this getting stuck? redner samples??" << endl;} // if (i > 144) {cout << "where is this getting stuck? before starting the next loop?" << endl;} } } cout << "output = " << output << "should not be null!" << endl; if(imageMode){image.SaveTGA(output);} if( depthMode){ depth.SaveTGA(depthOutput);} if( normalsMode){ normals.SaveTGA(normalsOutput);} if (render_samples) { sd->renderSamples(render_samples_outfile, zoom_factor); } return 0; }
int main(int argc, char* argv[]) { //_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc(305); std::string path = ""; std::string ext = ""; switch (argc) { case 2: path = std::string(argv[1]); break; case 3: path = std::string(argv[1]); ext = std::string(argv[2]); break; default: printUsage(); std::cout << "Press any key to continue..." << std::endl; getchar(); return -1; } // more portable and failsafe: forward slash! path = String::replace(path, "\\", "/"); // append a forward slash if we are in directory mode if (argc != 2 && path != "" && path.at(path.length()-1) != '/') path += '/'; // do the rendering for all files in path with ext extension if (ext.length() > 0) { // get all filenames std::vector<std::string> files; getAllFilesIn(path, files, ext); if (files.size() == 0) std::cout << "No files found!" << std::endl; // render all the files for (auto it = files.begin(); it != files.end(); ++it) { auto& filepath = path + *it; std::cout << "Rendering " << filepath << std::endl; auto out_file = String::replaceExtension(filepath, "png"); std::cout << " into: " << out_file << "\n"; PNGImage image(out_file, 600, 600); RayTracer tracer; tracer.load(filepath); tracer.renderInto(&image); std::cout << " Done! Duration: " << tracer.getRenderDuration().count() << " ms" << std::endl << std::endl; } } else { std::cout << "Rendering " << path << std::endl; auto out_file = String::replaceExtension(path, "png"); std::cout << " into: " << out_file << "\n"; PNGImage image(out_file, 600, 480); //Null image; RayTracer tracer; tracer.load(path); #ifdef PERF_TEST long long sum = 0; for (auto i=0; i<10; ++i) { #endif //for (int i=0; i<10; ++i) { tracer.renderInto(&image); //if (i<5) // tracer.moveCamera(Scene::Direction::CLOSER); //else // tracer.moveCamera(Scene::Direction::FARTHER); //std::stringstream ss; //ss << out_file << i << ".png"; //image.setOutputName(ss.str()); //} #ifdef PERF_TEST sum += tracer.getRenderDuration().count(); } std::fstream out("perf.csv", std::fstream::out | std::fstream::app); out << "Avg run: " << sum/10.0 << " ms" << std::endl; #endif std::cout << " Done! Duration: " << tracer.getRenderDuration().count() << " ms" << std::endl << std::endl; } return 0; }
void RTdisplay( void ) { rt._display(); }
void aRomanticEvening() { rt.lightFlicker(); }
void* rayThread(void* argument) { float r = 10.0f; mvl::GVector3f center(0.0f, 0.0f, -15.0f); std::shared_ptr<IlluminatedObject> sphereA(new Sphere (center, r)); sphereA->setColor(mvl::GVector4f(1.0f, 0.85f, 0.73f, 1.0f)); sphereA->setDiffAmbCoeff(1.0); sphereA->setReflCoeff(0.0); //sphereA.setDiffAmbCoeff(.8); //sphereA.setReflCoeff(0.4); r = 7.0f; center = mvl::GVector3f(-15.0f, -3.0f, -3.0f); std::shared_ptr<IlluminatedObject> sphereB(new Sphere(center, r)); sphereB->setColor(mvl::GVector4f(1.0f, 1.0f, 0.6f, 1.0f)); sphereB->setDiffAmbCoeff(0.8f); sphereB->setReflCoeff(0.1f); r = 14.0f; center = mvl::GVector3f(20.0f, 4.0f, 0.0f); std::shared_ptr<IlluminatedObject> sphereL(new Sphere(center, r)); sphereL->setColor(mvl::GVector4f(1.0f, 0.079f, 0.57f, 1.0f)); sphereL->setReflCoeff(0.0f); mvl::GVector3f p0(-30.0f, 10.0f, -15.0f); mvl::GVector3f p1(-7.0f, 10.0f, -20.0f); mvl::GVector3f p2(-20.0f, 25.0f, -8.5f); std::shared_ptr<IlluminatedObject>triangle(new RTriangle (p0, p1, p2)); triangle->setDiffAmbCoeff(0.2f); triangle->setReflCoeff(1.0f); //Plane plane(mvl::GVector4f(0.0f, 0.0f, -100.0f, 1.0f), mvl::GVector4f(0.0f, 0.707f, 0.707f, 1.0f)); std::shared_ptr<IlluminatedObject>table(new Plane(mvl::GVector3f(0.0f, -10.0f, 0.0f), mvl::GVector3f(0.0f, 1.0f, 0.1f))); table->setColor(mvl::GVector4f(1.0f, 1.0f, 1.0f, 1.0f)); table->setReflCoeff(.2); std::shared_ptr<IlluminatedObject>backWall(new Plane(mvl::GVector3f(0.0f, -10.0f, -50.0f), mvl::GVector3f(0.0f, 0.0f, 1.0f))); backWall->setColor(mvl::GVector4f(0.67f, 0.84f, 0.90f, 1.0f)); backWall->setReflCoeff(.2); Plane frontWall(mvl::GVector3f(0.0f, -10.0f, 100.0f), mvl::GVector3f(0.0f, 0.0f, -1.0f)); frontWall.setColor(mvl::GVector4f(0.5f, 1.0f, 0.5f, 1.0f)); frontWall.setReflCoeff(.2); Plane ceilingWall(mvl::GVector3f(0.0f, 40.0f, 100.0f), mvl::GVector3f(0.0f, -1.0f, 0.0f)); ceilingWall.setColor(mvl::GVector4f(1.0f, 0.0f, 0.0f, 1.0f)); ceilingWall.setReflCoeff(.2); LambertLight light0; //light.setPos(mvl::GVector4f(0.0f, 0.0f, 10.0f, 1.0f)); light0.setPos(mvl::GVector3f(-20.0f, 20.0f, 100.0f)); light0.setDiffuse(mvl::GVector4f(0.75f, 0.75f, 0.6f, 1.0f)); light0.setAmbient(mvl::GVector4f(0.01f, 0.01f, 0.01f, 1.0f)); LambertLight light1; light1.setPos(mvl::GVector3f(20.0f, 20.0f, 100.0f)); //light2.setPos(mvl::GVector4f(0.0f, 0.0f, -500.0f, 1.0f)); light1.setDiffuse(mvl::GVector4f(0.5f, 0.5f, 0.4f, 1.0f)); light1.setAmbient(mvl::GVector4f(0.01f, 0.01f, 0.01f, 1.0f)); Scene scene; scene.addObject(sphereA); scene.addObject(sphereB); scene.addObject(sphereL); scene.addObject(table); scene.addObject(triangle); scene.addObject(backWall); //scene.addObject(&frontWall); //scene.addObject(&ceilingWall); scene.addLight(&light0); scene.addLight(&light1); rayTracer.trace(scene); return NULL; }
void Window::renderRayImage () { // Modify scene to apply options if necessary resampleScenesLights(); // Get camera informations qglviewer::Camera * cam = viewer->camera (); qglviewer::Vec p = cam->position (); qglviewer::Vec d = cam->viewDirection (); qglviewer::Vec u = cam->upVector (); qglviewer::Vec r = cam->rightVector (); Vec3Df camPos (p[0], p[1], p[2]); Vec3Df viewDirection (d[0], d[1], d[2]); Vec3Df upVector (u[0], u[1], u[2]); Vec3Df rightVector (r[0], r[1], r[2]); float fieldOfView = cam->fieldOfView (); float aspectRatio = cam->aspectRatio (); unsigned int screenWidth = cam->screenWidth (); unsigned int screenHeight = cam->screenHeight (); // Create a ray Iterator RayIterator* rayIterator = new LensBlurIterator(); rayIterator->setCameraInformation(camPos, viewDirection, upVector, rightVector, fieldOfView, aspectRatio, screenWidth, screenHeight); setRayIteratorOptions(rayIterator); // Create the ray tracer RayTracer * rayTracer = RayTracer::getInstance (); rayTracer->rayIterator = rayIterator; // Pass options down rayTracer->enableCastShadows = shadowCheckBox->isChecked(); rayTracer->enableRefraction = transparencyCheckBox->isChecked(); rayTracer->enableMirrorEffet = mirrorCheckBox->isChecked(); rayTracer->shadingFunction = getShadingFunction(); rayTracer->bounces = (int)bouncesSlider->getValue(); QTime timer; timer.start (); #ifdef _OPENMP QImage image(screenWidth, screenHeight, QImage::Format_RGB888); bool over = false; #pragma omp parallel num_threads(2) { int i = omp_get_thread_num(); //First thread is calculating image if(i == 0) over = rayTracer->render(camPos, viewDirection, upVector, rightVector, fieldOfView, aspectRatio, screenWidth, screenHeight, image); //Second thread is getting image every refreshingTime if(i == 1) { while (!over) { if(timer.elapsed() > lastTime + refreshTime) { lastTime = timer.elapsed(); viewer->setRayImage(image); viewer->setDisplayMode (GLViewer::RayDisplayMode); } } } } # elif __APPLE__ QImage image(screenWidth, screenHeight, QImage::Format_RGB888); for(int i = 0 ; i < screenWidth ; i++) { for(int j = 0 ; j < screenHeight ; j++) { image.setPixel(i, j, qRgb(0, 0, 0)); } } __block bool over = false; __block QImage& imgRef = image; dispatch_queue_t rayTracerQueue = dispatch_queue_create("com.raymini.queue", 0); dispatch_async(rayTracerQueue, ^{ over = rayTracer->render(camPos, viewDirection, upVector, rightVector, fieldOfView, aspectRatio, screenWidth, screenHeight, imgRef); });
int main(int argc, char **argv) { ros::init(argc, argv, "updating_particles"); ros::NodeHandle n; PlotRayUtils plt; RayTracer rayt; std::random_device rd; std::normal_distribution<double> randn(0.0,0.000001); ROS_INFO("Running..."); ros::Publisher pub_init = n.advertise<particle_filter::PFilterInit>("/particle_filter_init", 5); ros::ServiceClient srv_add = n.serviceClient<particle_filter::AddObservation>("/particle_filter_add"); ros::Duration(1).sleep(); // pub_init.publish(getInitialPoints(plt)); geometry_msgs::Point obs; geometry_msgs::Point dir; double radius = 0.00; int i = 0; //for(int i=0; i<20; i++){ while (i < NUM_TOUCHES) { // ros::Duration(1).sleep(); //tf::Point start(0.95,0,-0.15); //tf::Point end(0.95,2,-0.15); tf::Point start, end; // randomSelection(plt, rayt, start, end); fixedSelection(plt, rayt, start, end); Ray measurement(start, end); double distToPart; if(!rayt.traceRay(measurement, distToPart)){ ROS_INFO("NO INTERSECTION, Skipping"); continue; } tf::Point intersection(start.getX(), start.getY(), start.getZ()); intersection = intersection + (end-start).normalize() * (distToPart - radius); std::cout << "Intersection at: " << intersection.getX() << " " << intersection.getY() << " " << intersection.getZ() << std::endl; tf::Point ray_dir(end.x()-start.x(),end.y()-start.y(),end.z()-start.z()); ray_dir = ray_dir.normalize(); obs.x=intersection.getX() + randn(rd); obs.y=intersection.getY() + randn(rd); obs.z=intersection.getZ() + randn(rd); dir.x=ray_dir.x(); dir.y=ray_dir.y(); dir.z=ray_dir.z(); // obs.x=intersection.getX(); // obs.y=intersection.getY(); // obs.z=intersection.getZ(); // pub_add.publish(obs); // plt.plotCylinder(start, end, 0.01, 0.002, true); plt.plotRay(Ray(start, end)); // ros::Duration(1).sleep(); particle_filter::AddObservation pfilter_obs; pfilter_obs.request.p = obs; pfilter_obs.request.dir = dir; if(!srv_add.call(pfilter_obs)){ ROS_INFO("Failed to call add observation"); } ros::spinOnce(); while(!rayt.particleHandler.newParticles){ ROS_INFO_THROTTLE(10, "Waiting for new particles..."); ros::spinOnce(); ros::Duration(.1).sleep(); } i ++; } // std::ofstream myfile; // myfile.open("/home/shiyuan/Documents/ros_marsarm/diff.csv", std::ios::out|std::ios::app); // myfile << "\n"; // myfile.close(); // myfile.open("/home/shiyuan/Documents/ros_marsarm/time.csv", std::ios::out|std::ios::app); // myfile << "\n"; // myfile.close(); // myfile.open("/home/shiyuan/Documents/ros_marsarm/diff_trans.csv", std::ios::out|std::ios::app); // myfile << "\n"; // myfile.close(); // myfile.open("/home/shiyuan/Documents/ros_marsarm/diff_rot.csv", std::ios::out|std::ios::app); // myfile << "\n"; // myfile.close(); // myfile.open("/home/shiyuan/Documents/ros_marsarm/workspace_max.csv", std::ios::out|std::ios::app); // myfile << "\n"; // myfile.close(); // myfile.open("/home/shiyuan/Documents/ros_marsarm/workspace_min.csv", std::ios::out|std::ios::app); // myfile << "\n"; // myfile.close(); ROS_INFO("Finished all action"); }
int main(int argc, char *argv[]) { // For detecting memory leaks #ifdef _MSVC _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); #endif //// Seed the random number generator //srand( (unsigned int)time( 0 ) ); // Display license std::cout << "RayWatch - A simple cross-platform RayTracer." << std::endl << "Copyright (C) 2008" << std::endl << " Angelo Rohit Joseph Pulikotil," << std::endl << " Francis Xavier Joseph Pulikotil" << std::endl << "This program comes with ABSOLUTELY NO WARRANTY." << std::endl << "This is free software, and you are welcome to redistribute it" << std::endl << "under certain conditions; see <http://www.gnu.org/licenses/>." << std::endl << std::endl; if( argc < 3 ) { std::cout << "Insufficient arguments" << std::endl << std::endl; std::cout << "Syntax (to render a Scene file):" << std::endl << argv[0] << " <input scene filename> <output bitmap filename> [width] [height]" << std::endl << std::endl; std::cout << "Syntax (to generate a sample file): " << std::endl << argv[0] << " --gen:<sample name> <output scene filename>" << std::endl << std::endl; std::cout << "Currently supported samples are CornellBox, Example1, Example2" << std::endl; return -1; } // If we're supposed to generate a sample file if( Utility::String::CaseInsensitiveCompare( std::string( argv[1] ).substr(0, 6), "--gen:" ) == 0 ) { const std::string sampleName = std::string( argv[1] ).substr( 6 ); bool bResult = false; if( Utility::String::CaseInsensitiveCompare( sampleName, "CornellBox" ) == 0 ) { bResult = Examples::CornellBox( argv[2] ); } else if( Utility::String::CaseInsensitiveCompare( sampleName, "Example1" ) == 0 ) { bResult = Examples::Example1( argv[2] ); } else if( Utility::String::CaseInsensitiveCompare( sampleName, "Example2" ) == 0 ) { bResult = Examples::Example2( argv[2] ); } else // We don't have this sample std::cout << "Error: Unknown sample name: " << sampleName << std::endl; if( !bResult ) return -1; std::cout << "Sample '" << sampleName << "' written to file: " << argv[2] << std::endl; return 0; } // Get the required width int width = 500; if( argc > 3 ) { if( !Utility::String::FromString(width, argv[3]) || (width < 1) ) { std::cout << "Error: Invalid integer specified for width: " << argv[3] << std::endl; return -1; } } // Get the required height int height = 500; if( argc > 4 ) { if( !Utility::String::FromString(height, argv[4]) || (height < 1) ) { std::cout << "Error: Invalid integer specified for height: " << argv[4] << std::endl; return -1; } } // Create a Camera Camera camera; camera._position .Set( 0, 0, 0 ); camera._hFov = 45 * (width / (float)height); camera._vFov = 45; // Create an Image Image image; if( !image.Create( width, height ) ) { std::cout << "Error: Failed to create Image of size " << width << "x" << height << std::endl; return -1; } // Open the input scene file std::fstream stream; stream.open( argv[1], std::ios_base::in ); if( !stream.is_open() ) { std::cout << "Error: Failed to open input scene file: " << argv[1] << std::endl; return -1; } // Create a Deserializer for the stream Deserializer d; if( !d.Open( stream ) ) { std::cout << "Error: Failed to read file: " << argv[1] << std::endl; return -1; } // Load the scene from the stream Scene *pScene = d.Deserialize<Scene>( 0 ); if( !pScene ) { std::cout << "Error: Failed to load Scene from file: " << argv[1] << std::endl; return -1; } // Create a RayTracer and ray trace the scene RayTracer rayTracer; std::cout << "RayTracing"; const bool bRTResult = rayTracer.Render( camera, *pScene, image ); std::cout << "Done" << std::endl; // We're done with the scene, delete it SafeDeleteScalar( pScene ); if( !bRTResult ) { std::cout << "Error: Failed while RayTracing the Scene." << std::endl; return -1; } // Save the image to the required output file if( !image.Save( argv[2] ) ) { std::cout << "Error: Failed while saving image to file: " << argv[2] << std::endl; return -1; } return 0; }