Cubemap* TextureFactory::CreateCubemapFromFile(const char*const name, const std::vector<std::string>& paths, const TextureWrapMode wrapMode, const TextureFilterMode filterMode) { if (strcmp(name, "") == 0) { LOG_ERROR("Cannot create a texture with an empty name string"); return nullptr; } for (uint i = 0; i < paths.size(); i++) { if (strcmp(paths[i].c_str(), "") == 0) { LOG_ERROR("Cannot create a texture with an empty path string"); return nullptr; } if (!FileUtils::CheckFileExists(paths[i].c_str())) { LOG_ERROR("Texture file \"", paths[i].c_str(), "\"was not found"); return nullptr; } } Cubemap* texture = new Cubemap(name, paths, wrapMode, filterMode); if (!texture->Load()) { LOG_ERROR("Failed to load cubemap: ", name); SafeDelete(texture); return nullptr; } return texture; }
Cubemap *MaterialManager::cubemapFromXMLNode(TiXmlNode *node) { TiXmlElement *nodeElement = node->ToElement(); if (!nodeElement) return NULL; // Skip comment nodes Cubemap *newCubemap = NULL; String name = nodeElement->Attribute("name"); String xPos = nodeElement->Attribute("xPos"); String xNeg = nodeElement->Attribute("xNeg"); String yPos = nodeElement->Attribute("yPos"); String yNeg = nodeElement->Attribute("yNeg"); String zPos = nodeElement->Attribute("zPos"); String zNeg = nodeElement->Attribute("zNeg"); newCubemap = CoreServices::getInstance()->getRenderer()->createCubemap( CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(xPos), CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(xNeg), CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(yPos), CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(yNeg), CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(zPos), CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(zNeg) ); newCubemap->setResourceName(name); return newCubemap; }
Cubemap *MaterialManager::cubemapFromXMLNode(TiXmlNode *node) { TiXmlElement *nodeElement = node->ToElement(); if (!nodeElement) return NULL; // Skip comment nodes Cubemap *newCubemap = NULL; String name = nodeElement->Attribute("name"); String mapString = nodeElement->GetText(); vector<String> maps = mapString.split(","); if(maps.size() != 6) { Logger::log("Error: A cubemap must contain 6 images \n"); return NULL; } newCubemap = CoreServices::getInstance()->getRenderer()->createCubemap( (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, maps[0]), (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, maps[1]), (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, maps[2]), (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, maps[3]), (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, maps[4]), (Texture*)CoreServices::getInstance()->getResourceManager()->getResource(Resource::RESOURCE_TEXTURE, maps[5]) ); newCubemap->setResourceName(name); return newCubemap; }
void Renderer::onDraw(al::Graphics& gl) { int faceIndex = mOmni.face(); { // render cubemap if (cubemap && cubemap->getEyesCount() > 0) { Cubemap* eye = cubemap->getEye(0); if (eye->getFacesCount() > faceIndex) { CubemapFace* face = eye->getFace(faceIndex); glUseProgram(0); glDepthMask(GL_FALSE); // draw the background glDrawPixels(face->getWidth(), face->getHeight(), GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)face->getPixels()); glDepthMask(GL_TRUE); if(newCubemap) { if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, faceIndex); } } } } light(); mShader.begin(); mOmni.uniforms(mShader); gl.pushMatrix(); //gl.draw(cube); gl.pushMatrix(); // rotate over time: gl.rotate(now*30., 0.707, 0.707, 0.); gl.translate(1., 1., 1.); //gl.draw(sphere); gl.popMatrix(); gl.popMatrix(); mShader.end(); }
void addFaceSubstreams0(void*) { int portCounter = 0; for (int j = 0; j < cubemap->getEyesCount(); j++) { Cubemap* eye = cubemap->getEye(j); for (int i = 0; i < eye->getFacesCount(); i++) { faceStreams.push_back(FrameStreamState()); FrameStreamState* state = &faceStreams.back(); state->content = eye->getFace(i)->getContent(); Port rtpPort(FACE0_RTP_PORT_NUM + portCounter); portCounter += 2; Groupsock* rtpGroupsock = new Groupsock(*env, destinationAddress, rtpPort, TTL); //rtpGroupsock->multicastSendOnly(); // we're a SSM source setReceiveBufferTo(*env, rtpGroupsock->socketNum(), bufferSize); // Create a 'H264 Video RTP' sink from the RTP 'groupsock': state->sink = H264VideoRTPSink::createNew(*env, rtpGroupsock, 96); ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink); cubemapSMS->addSubsession(subsession); RawPixelSource* source = RawPixelSource::createNew(*env, state->content, avgBitRate); source->setOnSentNALU (boost::bind(&onSentNALU, _1, _2, _3, j, i)); source->setOnEncodedFrame(boost::bind(&onEncodedFrame, _1, j, i)); state->source = H264VideoStreamDiscreteFramer::createNew(*env, source); state->sink->startPlaying(*state->source, NULL, NULL); std::cout << "Streaming face " << i << " (" << ((j == 0) ? "left" : "right") << ") on port " << ntohs(rtpPort.num()) << " ..." << std::endl; } } announceStream(rtspServer, cubemapSMS, cubemapStreamName); }
bool load() { if (!shader_simple.loadAndLinkFromFile("./demo/11camera/simple") || !shader_background.loadAndLinkFromFile("./demo/11camera/background")) return false; if (!cubemap.loadFromFile("./data/cubemaps/iceland_", ".jpg")) return false; glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); cubemap.setTexParameteri( GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); return true; }
extern "C" void EXPORT_API UnityRenderEvent (int eventID) { // When we use the RenderCubemap.cs and USeRenderingPlugin.cs scripts // This function will get called twice (with different eventIDs). // We have to make sure that the extraction only happens once for the cubemap // and binoculars respectively! if (eventID == 1) { // Allocate cubemap the first time we render a frame. // By doing so, we can make sure that both // the cubemap and the binoculars are fully configured. if (!thisProcess) { allocateSHM(cubemapConfig, binocularsConfig); } presentationTime = boost::chrono::system_clock::now(); std::vector<Frame*> frames; if (cubemap) { for (int j = 0; j < cubemap->getEyesCount(); j++) { Cubemap* eye = cubemap->getEye(j); for (int i = 0; i < eye->getFacesCount(); i++) { frames.push_back(eye->getFace(i)->getContent()); } } } if (binoculars) { frames.push_back(binoculars->getContent()); } copyFromGPUtoCPU(frames); } }
int main (int argc, char** argv) { /*---------------------- Initialize OpenGL and OpenCL ----------------------*/ if (init_gl(argc,argv,&glinfo, window_size, "RT") != 0){ std::cerr << "Failed to initialize GL" << std::endl; exit(1); } else { std::cout << "Initialized GL succesfully" << std::endl; } if (init_cl(glinfo,&clinfo) != CL_SUCCESS){ std::cerr << "Failed to initialize CL" << std::endl; exit(1); } else { std::cout << "Initialized CL succesfully" << std::endl; } print_cl_info(clinfo); /* Initialize device interface */ if (device.initialize(clinfo)) { std::cerr << "Failed to initialize device interface" << std::endl; exit(1); } /* Initialize generic gpu library */ DeviceFunctionLibrary::initialize(clinfo); /*---------------------- Create shared GL-CL texture ----------------------*/ gl_tex = create_tex_gl(window_size[0],window_size[1]); tex_id = device.new_memory(); DeviceMemory& tex_mem = device.memory(tex_id); if (tex_mem.initialize_from_gl_texture(gl_tex)) { std::cerr << "Failed to create memory object from gl texture" << std::endl; exit(1); } /*---------------------- Set up scene ---------------------------*/ frames = 15; const std::string pack = "pack1OBJ"; // const std::string pack = "pack2OBJ"; double wave_attenuation = 1.f; scenes.resize(frames); for (uint32_t i = 0; i < frames ; ++i) { scenes[i].initialize(); std::stringstream grid_path,visual_path; grid_path << "models/obj/" << pack << "/gridFluid" << i+1 << ".obj"; mesh_id grid_mid = scenes[i].load_obj_file_as_aggregate(grid_path.str()); object_id grid_oid = scenes[i].add_object(grid_mid); Object& grid = scenes[i].object(grid_oid); grid.mat.diffuse = White; grid.mat.reflectiveness = 0.95f; grid.mat.refractive_index = 1.5f; grid.geom.setScale(makeVector(1.f,wave_attenuation,1.f)); /* ---- Solids ------ */ // visual_path << "models/obj/" << pack << "/visual" << visual_frame << ".obj"; // mesh_id visual_mid = scenes[i].load_obj_file_as_aggregate(visual_path.str()); // object_id visual_oid = scenes[i].geometry.add_object(visual_mid); // Object& visual = scenes[i].geometry.object(visual_oid); // visual.mat.diffuse = Red; // for (uint32_t j = 0; j < bridge_parts ; ++j) { // std::stringstream bridge_path; // bridge_path << "models/obj/" << pack << "/bridge" << j << i+1 << ".obj"; // mesh_id bridge_mid = scenes[i].load_obj_file_as_aggregate(bridge_path.str()); // object_id bridge_oid = scenes[i].geometry.add_object(bridge_mid); // Object& bridge = scenes[i].geometry.object(bridge_oid); // bridge.mat.diffuse = Green; // } // mesh_id teapot_mesh_id = scenes[i].load_obj_file_as_aggregate("models/obj/teapot2.obj"); // mesh_id teapot_mesh_id = scenes[i].load_obj_file_as_aggregate("models/obj/teapot-low_res.obj"); // object_id teapot_obj_id = scenes[i].geometry.add_object(teapot_mesh_id); // Object& teapot_obj = scenes[i].geometry.object(teapot_obj_id); // teapot_obj.geom.setPos(makeVector(-1.f,0.f,0.f)); // teapot_obj.geom.setScale(makeVector(3.f,3.f,3.f)); // teapot_obj.mat.diffuse = Green; // teapot_obj.mat.shininess = 1.f; // teapot_obj.mat.reflectiveness = 0.3f; /* ------------------*/ // scenes[i].set_accelerator_type(KDTREE_ACCELERATOR); scenes[i].set_accelerator_type(BVH_ACCELERATOR); scenes[i].create_aggregate_mesh(); scenes[i].create_aggregate_accelerator(); Mesh& scene_mesh = scenes[i].get_aggregate_mesh(); if (scenes[i].transfer_aggregate_mesh_to_device() || scenes[i].transfer_aggregate_accelerator_to_device()) std::cerr << "Failed to transfer scene info to device"<< std::endl; /*---------------------- Print scene data ----------------------*/ std::cerr << "Scene " << i << " stats: " << std::endl; std::cerr << "\tTriangle count: " << scene_mesh.triangleCount() << std::endl; std::cerr << "\tVertex count: " << scene_mesh.vertexCount() << std::endl; std::cerr << std::endl; } /*---------------------- Set initial Camera paramaters -----------------------*/ camera.set(makeVector(0,3,-30), makeVector(0,0,1), makeVector(0,1,0), M_PI/4., window_size[0] / (float)window_size[1]); /*---------------------------- Set tile size ------------------------------*/ best_tile_size = clinfo.max_compute_units * clinfo.max_work_item_sizes[0]; best_tile_size *= 64; best_tile_size = std::min(pixel_count, best_tile_size); /*---------------------- Initialize ray bundles -----------------------------*/ int32_t ray_bundle_size = best_tile_size * 4; if (ray_bundle_1.initialize(ray_bundle_size)) { std::cerr << "Error initializing ray bundle 1" << std::endl; std::cerr.flush(); exit(1); } if (ray_bundle_2.initialize(ray_bundle_size)) { std::cerr << "Error initializing ray bundle 2" << std::endl; std::cerr.flush(); exit(1); } std::cout << "Initialized ray bundles succesfully" << std::endl; /*---------------------- Initialize hit bundle -----------------------------*/ int32_t hit_bundle_size = ray_bundle_size; if (hit_bundle.initialize(hit_bundle_size)) { std::cerr << "Error initializing hit bundle" << std::endl; std::cerr.flush(); exit(1); } std::cout << "Initialized hit bundle succesfully" << std::endl; /*----------------------- Initialize cubemap ---------------------------*/ if (cubemap.initialize("textures/cubemap/Path/posx.jpg", "textures/cubemap/Path/negx.jpg", "textures/cubemap/Path/posy.jpg", "textures/cubemap/Path/negy.jpg", "textures/cubemap/Path/posz.jpg", "textures/cubemap/Path/negz.jpg")) { std::cerr << "Failed to initialize cubemap." << std::endl; exit(1); } std::cerr << "Initialized cubemap succesfully." << std::endl; /*------------------------ Initialize FrameBuffer ---------------------------*/ if (framebuffer.initialize(window_size)) { std::cerr << "Error initializing framebuffer." << std::endl; exit(1); } std::cout << "Initialized framebuffer succesfully." << std::endl; /* ------------------ Initialize ray tracer kernel ----------------------*/ if (tracer.initialize()){ std::cerr << "Failed to initialize tracer." << std::endl; return 0; } std::cerr << "Initialized tracer succesfully." << std::endl; /* ------------------ Initialize Primary Ray Generator ----------------------*/ if (prim_ray_gen.initialize()) { std::cerr << "Error initializing primary ray generator." << std::endl; exit(1); } std::cout << "Initialized primary ray generator succesfully." << std::endl; /* ------------------ Initialize Secondary Ray Generator ----------------------*/ if (sec_ray_gen.initialize()) { std::cerr << "Error initializing secondary ray generator." << std::endl; exit(1); } sec_ray_gen.set_max_rays(ray_bundle_1.count()); std::cout << "Initialized secondary ray generator succesfully." << std::endl; /*------------------------ Initialize RayShader ---------------------------*/ if (ray_shader.initialize()) { std::cerr << "Error initializing ray shader." << std::endl; exit(1); } std::cout << "Initialized ray shader succesfully." << std::endl; /*----------------------- Enable timing in all clases -------------------*/ framebuffer.timing(true); prim_ray_gen.timing(true); sec_ray_gen.timing(true); tracer.timing(true); ray_shader.timing(true); /*------------------------- Count mem usage -----------------------------------*/ int32_t total_cl_mem = 0; total_cl_mem += pixel_count * 4; /* 4bpp texture */ // for (uint32_t i = 0; i < frames; ++i) // total_cl_mem += scene_info[i].size(); total_cl_mem += ray_bundle_1.mem().size() + ray_bundle_2.mem().size(); total_cl_mem += hit_bundle.mem().size(); total_cl_mem += cubemap.positive_x_mem().size() * 6; total_cl_mem += framebuffer.image_mem().size(); std::cout << "\nMemory stats: " << std::endl; std::cout << "\tTotal opencl mem usage: " << total_cl_mem/1e6 << " MB." << std::endl; // for (uint32_t i = 0; i < frames; ++i) // std::cout << "\tScene " << i << " mem usage: " << scene_info[i].size()/1e6 << " MB." << std::endl; std::cout << "\tFramebuffer+Tex mem usage: " << (framebuffer.image_mem().size() + pixel_count * 4)/1e6 << " MB."<< std::endl; std::cout << "\tCubemap mem usage: " << (cubemap.positive_x_mem().size()*6)/1e6 << " MB."<< std::endl; std::cout << "\tRay mem usage: " << (ray_bundle_1.mem().size()*2)/1e6 << " MB."<< std::endl; std::cout << "\tRay hit info mem usage: " << hit_bundle.mem().size()/1e6 << " MB."<< std::endl; /* !! ---------------------- Test area ---------------- */ std::cerr << std::endl; std::cerr << "Misc info: " << std::endl; std::cerr << "Tile size: " << best_tile_size << std::endl; std::cerr << "Tiles: " << pixel_count / (float)best_tile_size << std::endl; std::cerr << "color_cl size: " << sizeof(color_cl) << std::endl; std::cerr << "directional_light_cl size: " << sizeof(directional_light_cl) << std::endl; std::cerr << "ray_cl size: " << sizeof(ray_cl) << std::endl; std::cerr << "sample_cl size: " << sizeof(sample_cl) << std::endl; std::cerr << "sample_trace_info_cl size: " << sizeof(sample_trace_info_cl) << std::endl; /*------------------------ Set GLUT and misc functions -----------------------*/ rt_time.snap_time(); seq_time.snap_time(); glutKeyboardFunc(gl_key); glutMotionFunc(gl_mouse); glutDisplayFunc(gl_loop); glutIdleFunc(gl_loop); glutMainLoop(); clinfo.release_resources(); return 0; }
void gl_loop() { static int i = 0; static int dir = 1; static int total_ray_count = 0; static double min_time=-1; static double max_time=-1; double prim_gen_time = 0; double sec_gen_time = 0; double prim_trace_time = 0; double sec_trace_time = 0; double prim_shadow_trace_time = 0; double sec_shadow_trace_time = 0; double shader_time = 0; double fb_clear_time = 0; double fb_copy_time = 0; glClear(GL_COLOR_BUFFER_BIT); if (device.acquire_graphic_resource(tex_id) || cubemap.acquire_graphic_resources()) { std::cerr << "Error acquiring texture resource." << std::endl; exit(1); } for (size_t i = 0; i < scenes.size(); ++i) { Scene& scene = scenes[i]; if (scene.acquire_graphic_resources()) { std::cerr << "Error acquiring texture resource." << std::endl; exit(1); } } if (framebuffer.clear()) { std::cerr << "Failed to clear framebuffer." << std::endl; exit(1); } fb_clear_time = framebuffer.get_clear_exec_time(); cl_int arg = i%STEPS; int32_t tile_size = best_tile_size; directional_light_cl light; light.set_dir(1.f,-1.f,0.f); light.set_color(1.f,1.f,1.f); // light.set_dir(0.05f * (arg - 8.f) , -0.6f, 0.2f); // light.set_color(0.05f * (fabsf(arg)) + 0.1f, 0.2f, 0.05f * fabsf(arg+4.f)); Scene &scene = scenes[current_frame]; scene.set_dir_light(light); color_cl ambient; ambient[0] = ambient[1] = ambient[2] = 0.1f; scene.set_ambient_light(ambient); int32_t sample_count = pixel_count * prim_ray_gen.get_spp(); for (int32_t offset = 0; offset < sample_count; offset+= tile_size) { RayBundle* ray_in = &ray_bundle_1; RayBundle* ray_out = &ray_bundle_2; if (sample_count - offset < tile_size) tile_size = sample_count - offset; if (prim_ray_gen.generate(camera, *ray_in, window_size, tile_size, offset)) { std::cerr << "Error seting primary ray bundle" << std::endl; exit(1); } prim_gen_time += prim_ray_gen.get_exec_time(); total_ray_count += tile_size; if (tracer.trace(scene, tile_size, *ray_in, hit_bundle)){ // if (tracer.trace(scene, bvh_mem, tile_size, *ray_in, hit_bundle)){ std::cerr << "Failed to trace." << std::endl; exit(1); } prim_trace_time += tracer.get_trace_exec_time(); if (tracer.shadow_trace(scene, tile_size, *ray_in, hit_bundle)){ //if (tracer.shadow_trace(scene, bvh_mem, tile_size, *ray_in, hit_bundle)){ std::cerr << "Failed to shadow trace." << std::endl; exit(1); } prim_shadow_trace_time += tracer.get_shadow_exec_time(); if (ray_shader.shade(*ray_in, hit_bundle, scene, cubemap, framebuffer, tile_size, true)){ std::cerr << "Failed to update framebuffer." << std::endl; exit(1); } shader_time += ray_shader.get_exec_time(); size_t sec_ray_count = tile_size; for (uint32_t i = 0; i < MAX_BOUNCE; ++i) { sec_ray_gen.generate(scene, *ray_in, sec_ray_count, hit_bundle, *ray_out, &sec_ray_count); sec_gen_time += sec_ray_gen.get_exec_time(); std::swap(ray_in,ray_out); if (!sec_ray_count) break; if (sec_ray_count == ray_bundle_1.count()) std::cerr << "Max sec rays reached!\n"; total_ray_count += sec_ray_count; // if (tracer.trace(scene, bvh_mem, sec_ray_count, if (tracer.trace(scene, sec_ray_count, *ray_in, hit_bundle, true)) { std::cerr << "Failed to trace." << std::endl; exit(1); } sec_trace_time += tracer.get_trace_exec_time(); // if (tracer.shadow_trace(scene, bvh_mem, sec_ray_count, if (tracer.shadow_trace(scene, sec_ray_count, *ray_in, hit_bundle, true)) { std::cerr << "Failed to shadow trace." << std::endl; exit(1); } sec_shadow_trace_time += tracer.get_shadow_exec_time(); if (ray_shader.shade(*ray_in, hit_bundle, scene, cubemap, framebuffer, sec_ray_count)){ std::cerr << "Ray shader failed execution." << std::endl; exit(1); } shader_time += ray_shader.get_exec_time(); } } if (framebuffer.copy(device.memory(tex_id))){ std::cerr << "Failed to copy framebuffer." << std::endl; exit(1); } fb_copy_time = framebuffer.get_copy_exec_time(); double total_msec = rt_time.msec_since_snap(); if (min_time < 0) min_time = total_msec; else min_time = std::min(min_time,total_msec); if (max_time < 0) max_time = total_msec; else max_time = std::max(max_time,total_msec); if (device.release_graphic_resource(tex_id) || cubemap.release_graphic_resources()) { std::cerr << "Error releasing texture resource." << std::endl; exit(1); } for (size_t i = 0; i < scenes.size(); ++i) { if (scenes[i].release_graphic_resources()) { std::cerr << "Error releasing texture resource." << std::endl; exit(1); } } ////////////////// Immediate mode textured quad glBindTexture(GL_TEXTURE_2D, gl_tex); glBegin(GL_TRIANGLE_STRIP); glTexCoord2f(1.0,1.0); glVertex2f(1.0,1.0); glTexCoord2f(1.0,0.0); glVertex2f(1.0,-1.0); glTexCoord2f(0.0,1.0); glVertex2f(-1.0,1.0); glTexCoord2f(0.0,0.0); glVertex2f(-1.0,-1.0); glEnd(); //////////////////////////////////////////// i += dir; if (!(i % (STEPS-1))){ dir *= -1; } std::cout << "Time elapsed: " << total_msec << " milliseconds " << "\t" << (1000.f / total_msec) << " FPS" << "\t" << total_ray_count << " rays casted " << "\t(" << pixel_count << " primary, " << total_ray_count-pixel_count << " secondary)" << " \r" ; std::flush(std::cout); rt_time.snap_time(); total_ray_count = 0; std::cout << "\nPrim Gen time: \t" << prim_gen_time << std::endl; std::cout << "Sec Gen time: \t" << sec_gen_time << std::endl; std::cout << "Tracer time: \t" << prim_trace_time + sec_trace_time << " (" << prim_trace_time << " - " << sec_trace_time << ")" << std::endl; std::cout << "Shadow time: \t" << prim_shadow_trace_time + sec_shadow_trace_time << " (" << prim_shadow_trace_time << " - " << sec_shadow_trace_time << ")" << std::endl; std::cout << "Shader time: \t " << shader_time << std::endl; std::cout << "Fb clear time: \t" << fb_clear_time << std::endl; std::cout << "Fb copy time: \t" << fb_copy_time << std::endl; std::cout << std::endl; glutSwapBuffers(); current_frame = (current_frame+motion_rate)%frames; if (current_frame == 0) { double t = seq_time.msec_since_snap(); std::cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << std::endl; std::cout << "Sequence stats:" << std::endl << std::endl; std::cout << "Frames: " << frames << std::endl; std::cout << "Sequence render time: " << t << "msec\t(" << frames*1000.f/t << " FPS)" << std::endl; std::cout << "Mean / Min / Max render time: " << t/frames << " / " << min_time << " / " << max_time << " msec" << std::endl; std::cout << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << std::endl; max_time = -1; min_time = -1; seq_time.snap_time(); } }
//---------------------------------------------------------------------------- //---------------------------------------------------------------------------- void CubemapProvider::LoadCubemap(Core::StorageLocation in_location, const std::string& in_filePath, const Core::IResourceOptionsBaseCSPtr& in_options, const Core::ResourceProvider::AsyncLoadDelegate& in_delegate, const Core::ResourceSPtr& out_resource) { //read the Cubemap JSON Json::Value jsonRoot; if (Core::JsonUtils::ReadJson(in_location, in_filePath, jsonRoot) == false) { CS_LOG_ERROR("Could not read face Cubemap file '" + in_filePath + "'."); out_resource->SetLoadState(Core::Resource::LoadState::k_failed); if(in_delegate != nullptr) { Core::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(in_delegate, out_resource)); } return; } const u32 k_numFaces = 6; const std::string k_faces[k_numFaces] = {"Right", "Left", "Top", "Bottom", "Front", "Back"}; //MSVC does not support moving arrays of unique_ptr at this time and therefore we have //to create a shared pointer in order to pass it into the lambda auto imageDataContainer = std::make_shared<std::array<Texture::TextureDataUPtr, k_numFaces>>(); std::array<Texture::Descriptor, k_numFaces> descs; for(u32 i = 0; i < k_numFaces; ++i) { auto textureFile = ParseCubemapFace(jsonRoot, k_faces[i]); if (textureFile.first == Core::StorageLocation::k_none || textureFile.second == "") { CS_LOG_ERROR("Could not load face '" + k_faces[i] + "' in Cubemap '" + in_filePath + "'."); out_resource->SetLoadState(Core::Resource::LoadState::k_failed); if(in_delegate != nullptr) { Core::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(in_delegate, out_resource)); } return; } Core::ImageSPtr image(Core::Image::Create()); if (LoadImage(image, m_imageProviders, textureFile.first, textureFile.second) == false) { CS_LOG_ERROR("Could not load image '" + textureFile.second + "' in Cubemap '" + in_filePath + "'"); out_resource->SetLoadState(Core::Resource::LoadState::k_failed); if(in_delegate != nullptr) { Core::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(in_delegate, out_resource)); } return; } (*imageDataContainer)[i] = image->MoveData(); Texture::Descriptor desc; desc.m_width = image->GetWidth(); desc.m_height = image->GetHeight(); desc.m_format = image->GetFormat(); desc.m_compression = image->GetCompression(); desc.m_dataSize = image->GetDataSize(); descs[i] = std::move(desc); } if(in_delegate == nullptr) { Cubemap* cubemap = (Cubemap*)out_resource.get(); const CubemapResourceOptions* options = (const CubemapResourceOptions*)in_options.get(); cubemap->Build(descs, std::move(*imageDataContainer), options->IsMipMapsEnabled(), options->IsRestoreCubemapDataEnabled()); cubemap->SetWrapMode(options->GetWrapModeS(), options->GetWrapModeT()); cubemap->SetFilterMode(options->GetFilterMode()); out_resource->SetLoadState(Core::Resource::LoadState::k_loaded); } else { auto task([descs, imageDataContainer, in_options, in_delegate, out_resource]() { Cubemap* cubemap = (Cubemap*)out_resource.get(); const CubemapResourceOptions* options = (const CubemapResourceOptions*)in_options.get(); cubemap->Build(descs, std::move(*imageDataContainer), options->IsMipMapsEnabled(), options->IsRestoreCubemapDataEnabled()); cubemap->SetWrapMode(options->GetWrapModeS(), options->GetWrapModeT()); cubemap->SetFilterMode(options->GetFilterMode()); out_resource->SetLoadState(Core::Resource::LoadState::k_loaded); in_delegate(out_resource); }); Core::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(task); } }
int32_t RayShader::shade(RayBundle& rays, HitBundle& hb, Scene& scene, Cubemap& cm, FrameBuffer& fb, size_t size, bool primary) { if (m_timing) m_timer.snap_time(); DeviceInterface& device = *DeviceInterface::instance(); function_id shade_id = primary? p_shade_id : s_shade_id; DeviceFunction& shade_function = device.function(shade_id); if (shade_function.set_arg(0, fb.image_mem())) return -1; if (shade_function.set_arg(1,hb.mem())) return -1; if (shade_function.set_arg(2,rays.mem())) return -1; if (shade_function.set_arg(3,scene.material_list_mem())) return -1; if (shade_function.set_arg(4,scene.material_map_mem())) return -1; if (shade_function.set_arg(5,cm.positive_x_mem())) return -1; if (shade_function.set_arg(6,cm.negative_x_mem())) return -1; if (shade_function.set_arg(7,cm.positive_y_mem())) return -1; if (shade_function.set_arg(8,cm.negative_y_mem())) return -1; if (shade_function.set_arg(9,cm.positive_z_mem())) return -1; if (shade_function.set_arg(10,cm.negative_z_mem())) return -1; /*Texture_0 to Texture_25*/ if (shade_function.set_arg(11,scene.texture_atlas.texture_mem(0))) return -1; if (shade_function.set_arg(12,scene.texture_atlas.texture_mem(1))) return -1; if (shade_function.set_arg(13,scene.texture_atlas.texture_mem(2))) return -1; if (shade_function.set_arg(14,scene.texture_atlas.texture_mem(3))) return -1; if (shade_function.set_arg(15,scene.texture_atlas.texture_mem(4))) return -1; if (shade_function.set_arg(16,scene.texture_atlas.texture_mem(5))) return -1; if (shade_function.set_arg(17,scene.texture_atlas.texture_mem(6))) return -1; if (shade_function.set_arg(18,scene.texture_atlas.texture_mem(7))) return -1; if (shade_function.set_arg(19,scene.texture_atlas.texture_mem(8))) return -1; if (shade_function.set_arg(20,scene.texture_atlas.texture_mem(9))) return -1; if (shade_function.set_arg(21,scene.texture_atlas.texture_mem(10))) return -1; if (shade_function.set_arg(22,scene.texture_atlas.texture_mem(11))) return -1; if (shade_function.set_arg(23,scene.texture_atlas.texture_mem(12))) return -1; if (shade_function.set_arg(24,scene.texture_atlas.texture_mem(13))) return -1; if (shade_function.set_arg(25,scene.texture_atlas.texture_mem(14))) return -1; if (shade_function.set_arg(26,scene.texture_atlas.texture_mem(15))) return -1; if (shade_function.set_arg(27,scene.texture_atlas.texture_mem(16))) return -1; if (shade_function.set_arg(28,scene.texture_atlas.texture_mem(17))) return -1; if (shade_function.set_arg(29,scene.texture_atlas.texture_mem(18))) return -1; if (shade_function.set_arg(30,scene.texture_atlas.texture_mem(19))) return -1; if (shade_function.set_arg(31,scene.texture_atlas.texture_mem(20))) return -1; if (shade_function.set_arg(32,scene.texture_atlas.texture_mem(21))) return -1; if (shade_function.set_arg(33,scene.texture_atlas.texture_mem(22))) return -1; if (shade_function.set_arg(34,scene.texture_atlas.texture_mem(23))) return -1; if (shade_function.set_arg(35,scene.texture_atlas.texture_mem(24))) return -1; if (shade_function.set_arg(36,scene.texture_atlas.texture_mem(25))) return -1; cl_uint sample_count = size; if (shade_function.set_arg(37,sizeof(cl_uint), &sample_count)) return -1; cl_int use_cubemap = cm.enabled; if (shade_function.set_arg(38,sizeof(cl_int), &use_cubemap)) return -1; if (shade_function.set_arg(39,scene.lights_mem())) return -1; size_t group_size = shade_function.max_group_size(); if (shade_function.enqueue_single_dim(size,group_size)) return -1; device.enqueue_barrier(); if (m_timing) { device.finish_commands(); m_time_ms = m_timer.msec_since_snap(); } return 0; }
void Game::start() { int width = 800; int height = 600; // context creation this->context = new Context(); this->context->initialize(4, 3); this->context->createWindow(width, height, 1, "ZPG", false, false, true); this->context->setKeyCallback([](GLFWwindow* window, int key, int scan, int action, int modifier) { InputController::getInstance().onKeyCallback(window, key, scan, action, modifier); }); this->context->setMousePositionCallback([](GLFWwindow* window, double x, double y) { InputController::getInstance().onMouseMoveCallback(window, x, y); }); this->context->setMouseScrollCallback([](GLFWwindow* window, double xOffset, double yOffset) { InputController::getInstance().onMouseScrollCallback(window, xOffset, yOffset); }); this->context->setMouseButtonCallback([](GLFWwindow* window, int button, int action, int modifier) { InputController::getInstance().onMouseButtonCallback(window, button, action, modifier); }); this->context->setWindowSizeCallback([](GLFWwindow* window, int width, int height) { Game::getInstance().onWindowSizeCallback(window, width, height); }); this->context->setShowMouseCursor(false); this->context->setDepthTest(true); this->context->setDepthFunc(GL_LEQUAL); this->context->setStencilTest(true); this->context->setStencilMask(0xFF); this->context->setStencilFunc(GL_ALWAYS, 1, 0xFF); this->context->setStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); this->context->setCulling(true); this->context->setBlending(true); this->context->setBlendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); this->screenQuad = new ScreenQuad(); // manager preload AudioManager::getInstance().initialize(); TextureManager::getInstance().preloadTextures(); ModelManager::getInstance().preloadModels(); FontManager::getInstance().initialize(width, height); ShaderLoader::getInstance().addCodeMapping("#LIGHT_DEFINITIONS", FileHelper::loadFile("Shaders/Headers/light_definitions.frag")); ShaderLoader::getInstance().addCodeMapping("#PHONG_CALCULATIONS", FileHelper::loadFile("Shaders/Headers/phong_calculations.frag")); ProgramManager::getInstance().preloadPrograms(); Program program = ProgramManager::getInstance().get(ProgramManager::PROGRAM_MODEL); ProgramManager::getInstance().use(ProgramManager::PROGRAM_MODEL); FramebufferManager::getInstance().preloadFramebuffers(); // initial object spawn Camera* cameraScript = new Camera(new CameraController(10.0f), glm::vec3(0.0f, 0.0f, -1.0f), 45.0f, 4.0f / 3.0f, 0.1f, 1000.0f); this->camera = new GameObject(cameraScript, nullptr, new BasicPhysicsComponent(false, new SphereBoundingBox(1.0f))); this->camera->getTransform().setPosition(glm::vec3(0.0f, 0.0f, 8.0f)); this->camera->getTags().set(Tag::Camera); this->scene.add(this->camera); ProgramManager::getInstance().observeCamera(cameraScript); // objects float distance = 3.0f; GameObject* cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Blue)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(distance, 0.0f, 0.0f)); cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Red)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(-distance, 0.0f, 0.0f)); cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Green)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(0.0f, distance, 0.0f)); cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Yellow)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(0.0f, -distance, 0.0f)); // lights DirectionalLight *dirLight = new DirectionalLight(glm::vec3(10.0f, 10.0f, 10.0f), Phong(Color::White * 0.001f, Color::White, Color::White * 0.1f)); GameObject* light = new GameObject(new LightComponent(dirLight, "directionalLight")); light->getTags().set(Tag::Light); this->scene.add(light); GeometryObject planeGeometry(VERTICES_PLANE, 2 * sizeof(glm::vec3), 6); planeGeometry.setAttributePositionNormal(); GeometryObject cubeGeometry(VERTICES_CUBE, sizeof(glm::vec3), 36); cubeGeometry.setAttributePosition(); PointLight* pointLight = new PointLight(Attenuation::ATT_DISTANCE_LONG, Phong(Color::White * 0.1f, Color::White, Color::White)); light = new GameObject( new LightComponent(pointLight, "pointLights", 0), new SimpleConstantRenderer(cubeGeometry, ProgramManager::PROGRAM_GEOMETRY_CONSTANT, Color::White) ); light->getTransform().setPosition(glm::vec3(0.0f, 0.0f, 0.0f)); light->getTags().set(Tag::Light); this->scene.add(light); program.setUniform1i("pointLightCount", 1); SpotLight* spotLight = new SpotLight(glm::vec3(0.0f, 0.0f, -1.0f), 12.5f, 17.5f, Attenuation::ATT_DISTANCE_LONG, dirLight->phong); GameObject* spotLightObj = new GameObject(new LightComponent(spotLight, "spotLight")); spotLightObj->getTags().set(Tag::Light); this->scene.add(spotLightObj); GameObject* floor = new GameObject(nullptr, new SimpleConstantRenderer(planeGeometry, ProgramManager::PROGRAM_MODEL, Color::Purple)); floor->getTransform().setScale(glm::vec3(10.0f)); floor->getTransform().setPosition(glm::vec3(0.0f, -5.0f, 0.0f)); this->scene.add(floor); // skybox const std::string skyboxPath = "Resources/Textures/skybox/"; std::vector<Image> skyboxFaces; skyboxFaces.push_back(Image(skyboxPath + "right.jpg")); skyboxFaces.push_back(Image(skyboxPath + "left.jpg")); skyboxFaces.push_back(Image(skyboxPath + "top.jpg")); skyboxFaces.push_back(Image(skyboxPath + "bottom.jpg")); skyboxFaces.push_back(Image(skyboxPath + "back.jpg")); skyboxFaces.push_back(Image(skyboxPath + "front.jpg")); Cubemap skyboxCubemap; skyboxCubemap.allocate(); skyboxCubemap.set2DImages(skyboxFaces); GameObject* skybox = new GameObject(nullptr, new SkyboxRenderer(skyboxCubemap)); this->scene.add(skybox); GameObject* crossHair = new GameObject(nullptr, new SpriteRenderer(TextureManager::TEXTURE_CROSSHAIR)); crossHair->getTransform().setScale(glm::vec3(50.0f, 50.0f, 1.0f)); this->scene.add(crossHair); Timer timer(0.01f); Timer switchTimer(0.05f); context->loop([&](Context& context) // physics { //this->physicsHandler.simulate(this->scene.getObjectManager().getObjects(), this->scene.getObjectManager().getObjectCount(), Context::getFixedDeltaTime()); }, [&](Context& context) // render { float delta = context.getDeltaTime(); timer.update(delta); switchTimer.update(delta); FramebufferManager::getInstance().get(FramebufferManager::FRAMEBUFFER_POSTPROCESS).bind(); RenderUtils::clearColor(0.0f, 0.0f, 0.0f, 1.0f); RenderUtils::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); context.setDepthTest(true); spotLight->direction = cameraScript->getFront(); spotLightObj->getTransform().setPosition(camera->getTransform().getPosition()); crossHair->getTransform().setPosition(glm::vec3(context.getWindowWidth() / 2.0f, context.getWindowHeight() / 2.0f, 0.0f)); this->scene.update(); this->scene.draw(); GLchar byte; glReadPixels(context.getWindowWidth() / 2, context.getWindowHeight() / 2, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, &byte); // stencil value at the center this->screenQuad->drawScreen(context); if (timer.resetIfReady()) { FontManager::getInstance().renderText("FPS: " + std::to_string(round(1.0f / delta)), 10.0f, height - 20.0f, 0.5f, glm::vec3(1.0f, 1.0f, 0.0f)); } if (InputController::getInstance().isButtonPressed(GLFW_KEY_ESCAPE)) { context.closeWindow(); } else if (InputController::getInstance().isButtonPressed(GLFW_KEY_SPACE) && switchTimer.resetIfReady()) { // switch render strategy } InputController::getInstance().afterUpdate(); this->scene.updateFrameEnd(); }); // resource disposal this->screenQuad->dispose(); delete this->screenQuad; this->scene.dispose(); ProgramManager::getInstance().dispose(); ModelManager::getInstance().dispose(); TextureManager::getInstance().dispose(); FramebufferManager::getInstance().dispose(); AudioManager::getInstance().dispose(); FontManager::getInstance().dispose(); context->terminate(); }
CubemapStereoFrame(StereoCubemap* cubemap) : cubemap_(cubemap) { Cubemap* left = cubemap_->getEye(0); Cubemap* right = cubemap_->getEye(1); if(cubemap_->getEyesCount() == 2) { faces[0][0] = new CubemapPixelData(left->getFace(0)); faces[0][1] = new CubemapPixelData(left->getFace(1)); faces[0][2] = new CubemapPixelData(left->getFace(2)); faces[0][3] = new CubemapPixelData(left->getFace(3)); faces[0][4] = new CubemapPixelData(left->getFace(4)); faces[0][5] = new CubemapPixelData(left->getFace(5)); faces[1][0] = new CubemapPixelData(right->getFace(0)); faces[1][1] = new CubemapPixelData(right->getFace(1)); faces[1][2] = new CubemapPixelData(right->getFace(2)); faces[1][3] = new CubemapPixelData(right->getFace(3)); faces[1][4] = new CubemapPixelData(right->getFace(4)); faces[1][5] = new CubemapPixelData(right->getFace(5)); } else { faces[0][0] = new CubemapPixelData(left->getFace(0)); faces[0][1] = new CubemapPixelData(left->getFace(1)); faces[0][2] = new CubemapPixelData(left->getFace(2)); faces[0][3] = new CubemapPixelData(left->getFace(3)); faces[0][4] = new CubemapPixelData(left->getFace(4)); faces[0][5] = new CubemapPixelData(left->getFace(5)); faces[1][0] = new CubemapPixelData(left->getFace(0)); faces[1][1] = new CubemapPixelData(left->getFace(1)); faces[1][2] = new CubemapPixelData(left->getFace(2)); faces[1][3] = new CubemapPixelData(left->getFace(3)); faces[1][4] = new CubemapPixelData(left->getFace(4)); faces[1][5] = new CubemapPixelData(left->getFace(5)); } }