def getCameraAltitudeHeight(self, main_scene_xml_file_prifix, pos_x, pos_z): currdir = os.path.split(os.path.realpath(__file__))[0] sys.path.append(currdir + '/bin/rt/' + current_rt_program + '/python/2.7/') os.environ[ 'PATH'] = currdir + '/bin/rt/' + current_rt_program + os.pathsep + os.environ[ 'PATH'] import mitsuba from mitsuba.core import Vector, Point, Ray, Thread from mitsuba.render import SceneHandler import platform scenepath = session.get_scenefile_path() fileResolver = Thread.getThread().getFileResolver() logger = Thread.getThread().getLogger() logger.clearAppenders() scenepath = scenepath.encode('utf-8') fileResolver.appendPath(scenepath) filepath = os.path.join(session.get_scenefile_path(), main_scene_xml_file_prifix + terr_scene_file).encode("utf-8") scene = SceneHandler.loadScene(fileResolver.resolve(filepath)) scene.configure() scene.initialize() ray = Ray() ray.setOrigin(Point(pos_x, 999999999, pos_z)) ray.setDirection(Vector(0, -1, 0)) its = scene.rayIntersect(ray) if not its is None: return its.p[1] else: print("Camera is outside of the scene, do not use relative height") return 0
def loadScene(): # Get a reference to the thread's file resolver fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath('cbox') paramMap = StringMap() paramMap['myParameter'] = 'value' scene = SceneHandler.loadScene(fileResolver.resolve("cbox.xml"), paramMap) return scene
def set_scene(self, export_context): if export_context.EXPORT_API_TYPE == 'FILE': scene_path, scene_file = os.path.split(efutil.filesystem_path(export_context.file_names[0])) self.fresolver.appendPath(scene_path) self.scene = SceneHandler.loadScene(self.fresolver.resolve(scene_file)) elif export_context.EXPORT_API_TYPE == 'API': self.scene = export_context.scene else: raise Exception('Unknown exporter type')
def set_scene(self, export_context): if export_context.EXPORT_API_TYPE == 'FILE': scene_path, scene_file = os.path.split( efutil.filesystem_path(export_context.file_names[0])) self.fresolver.appendPath(scene_path) self.scene = SceneHandler.loadScene( self.fresolver.resolve(scene_file)) elif export_context.EXPORT_API_TYPE == 'API': self.scene = export_context.scene else: raise Exception('Unknown exporter type')
def loadScene(filename, vpls_location): # Get a reference to the thread's file resolver fileResolver = Thread.getThread().getFileResolver() # Optional: supply parameters that can be accessed # by the scene (e.g. as $myParameter) paramMap = StringMap() paramMap['mesh'] = str(vpls_location[:-13] + 'mesh.ply') paramMap['envmap'] = str(vpls_location[:-14] + '.exr') # Load the scene from an XML file scene = SceneHandler.loadScene(fileResolver.resolve(filename), paramMap) return (scene)
def sample_mesh(mesh_file, n_samples, density=None, blue_noise_radius=None, resource_dir='./resources'): fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath(resource_dir) fileResolver.appendPath(os.path.split(mesh_file)[0]) paramMap = StringMap() paramMap['meshfile'] = mesh_file scene = SceneHandler.loadScene(fileResolver.resolve(resource_dir + '/scene_shape_template.xml'), paramMap) scene.initialize() shape = scene.getShapes()[0] if density is not None: n_samples = max(int(shape.getSurfaceArea() * density), 32) use_blue_noise = blue_noise_radius is not None if not use_blue_noise: blue_noise_radius = 10 sampled_p, sampled_n = scene.sampleSurface(shape, n_samples, use_blue_noise, blue_noise_radius) n_samples = len(sampled_p) // 3 return np.reshape(np.array(sampled_p), [n_samples, 3]), np.reshape(np.array(sampled_n), [n_samples, 3])
def do_simulation_multi_spectral_py(): currdir = os.path.split(os.path.realpath(__file__))[0] sys.path.append(currdir + '/bin/rt/' + current_rt_program + '/python/2.7/') os.environ['PATH'] = currdir + '/bin/rt/' + current_rt_program + os.pathsep + os.environ['PATH'] import mitsuba from mitsuba.core import Vector, Point, Ray, Thread, Scheduler, LocalWorker, PluginManager, Transform from mitsuba.render import SceneHandler from mitsuba.render import RenderQueue, RenderJob from mitsuba.render import Scene import multiprocessing scheduler = Scheduler.getInstance() for i in range(0, multiprocessing.cpu_count()): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() cfgfile = session.get_config_file() f = open(cfgfile, 'r') cfg = json.load(f) distFileName = spectral_img_prefix + "_VZ=" + str(cfg["observation"]["obs_zenith"]) + \ "_VA=" + str(cfg["observation"]["obs_azimuth"]) distFile = os.path.join(session.get_output_dir(), distFileName).encode("utf-8") scene_file_path = os.path.join(session.get_scenefile_path(), main_scene_xml_file).encode("utf-8") scene_path = session.get_scenefile_path().encode("utf-8") fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath(scene_path) scene = SceneHandler.loadScene(fileResolver.resolve(scene_file_path)) scene.setDestinationFile(distFile) scene.configure() scene.initialize() queue = RenderQueue() sceneResID = scheduler.registerResource(scene) job = RenderJob(('Simulation Job '+distFileName).encode("utf-8"), scene, queue, sceneResID) job.start() queue.waitLeft(0) queue.join() if output_format not in ("npy", "NPY") and os.path.exists(distFile + ".npy"): data = np.load(distFile + ".npy") bandlist = cfg["sensor"]["bands"].split(",") RasterHelper.saveToHdr_no_transform(data, distFile, bandlist, output_format) os.remove(distFile + ".npy") log("INFO: Finished")
def getScene(self): if (project_dir == "null"): print("No simulation.") return fileResolver = Thread.getThread().getFileResolver() logger = Thread.getThread().getLogger() logger.clearAppenders() scenepath = session.get_scenefile_path_according_to_basedir( project_dir) fileResolver.appendPath(str(scenepath)) main_xml = str(os.path.join(scenepath, main_scene_xml_file)) if not os.path.exists(main_xml): print("Simulation not generated.") return scene = SceneHandler.loadScene(main_xml) scene.configure() scene.initialize() return LessScene(scene, self.XSize, self.YSize)
def sample_scattering_mesh(mesh_file, n_samples, batch_size, n_abs_samples, media, seed, kdtree, extra_options): assert (mesh_file) resource_dir = './resources' fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath(resource_dir) fileResolver.appendPath(os.path.split(mesh_file)[0]) paramMap = StringMap() paramMap['meshfile'] = mesh_file scene = SceneHandler.loadScene( fileResolver.resolve(resource_dir + '/scene_shape_template.xml'), paramMap) scene.initialize() shape = scene.getShapes()[0] ignore_zero_scatter = get_default(extra_options, 'ignore_zero_scatter', True) fixed_in_dir = get_default(extra_options, 'fixed_in_dir', False) poly_fit_cfg = PolyFitConfig() set_obj_from_dict(poly_fit_cfg, extra_options) poly_fit_cfg.useLightspace = False importanceSamplePolys = get_default(extra_options, 'importance_sample_polys', False) if kdtree is not None: tmp_result = mitsuba.render.Volpath3D.samplePoly( shape, media, n_samples, batch_size, n_abs_samples, ignore_zero_scatter, False, importanceSamplePolys, kdtree, fixed_in_dir, seed, poly_fit_cfg) else: compute_sh_coefficients = get_default(extra_options, 'compute_sh_coefficients', False) if compute_sh_coefficients: tmp_result = mitsuba.render.Volpath3D.sampleShCoeffs( scene, shape, media, n_samples, batch_size, n_abs_samples, ignore_zero_scatter, False, seed) else: tmp_result = mitsuba.render.Volpath3D.sample( scene, shape, media, n_samples, batch_size, n_abs_samples, ignore_zero_scatter, False, seed) return tmp_result
def __init__(self, base_path,scene_name,params): self.params = params self.light = [] # Get a reference to the thread's file resolver self.fileResolver = Thread.getThread().getFileResolver() scenes_path = base_path + '/' + scene_name + '/mitsuba' self.fileResolver.appendPath(scenes_path) paramMap = StringMap() paramMap['myParameter'] = 'value' # Load the scene from an XML file self.scene = SceneHandler.loadScene(self.fileResolver.resolve(scene_name + '.xml'), paramMap) self.scheduler = Scheduler.getInstance() # Start up the scheduling system with one worker per local core for i in range(0, multiprocessing.cpu_count()): self.scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) self.scheduler.start() # Create a queue for tracking render jobs self.queue = RenderQueue() self.sceneResID = self.scheduler.registerResource(self.scene)
def __init__(self, base_path, scene_name, params, screenParams): self.params = params self.screenParams = screenParams self.light = [] # Get a reference to the thread's file resolver self.fileResolver = Thread.getThread().getFileResolver() scenes_path = base_path + '/' + scene_name + '/mitsuba' self.fileResolver.appendPath(scenes_path) paramMap = StringMap() paramMap['myParameter'] = 'value' ## Load the scene from an XML file self.scene = SceneHandler.loadScene( self.fileResolver.resolve(scene_name + '.xml'), paramMap) ## Setting & adding emmiters to scene - diffusive screen, created out of multiple sub-screens # self.SetWideScreen() # mitsuba.SetSunSky(np.array([[3, 300,3, 0,0,0, 0,0,1]])) # TODO : fix overidin of : self.SetWideScreen(params['screenWidth'] , params['screenHeight'],params['resXScreen'],params['resYScreen'], params['screenZPos'],params['variantRadiance']) self.addSceneLights() ## Simultaneously rendering multiple versions of a scene self.scene.initialize() self.scheduler = Scheduler.getInstance() ## Start up the scheduling system with one worker per local core if 'SYS_NAME' in os.environ and os.environ['SYS_NAME'] == 'AWS': maxThreads = multiprocessing.cpu_count() else: maxThreads = min(multiprocessing.cpu_count(), 30) for i in range(0, maxThreads): self.scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) self.scheduler.start() ## Create a queue for tracking render jobs self.queue = RenderQueue() self.sceneResID = self.scheduler.registerResource(self.scene)
def getTerrainBoundingAABB(self, main_scene_xml_file_prifix): # get bounding sphere currdir = os.path.split(os.path.realpath(__file__))[0] import platform if platform.system() == "Windows": sys.path.append( os.path.join(currdir, "bin", "rt", current_rt_program, "python", "3.6")) else: sys.path.append( os.path.join(currdir, "bin", "rt", current_rt_program, "python", "3.5")) os.environ['PATH'] = os.path.join( currdir, "bin", "rt", current_rt_program) + os.pathsep + os.environ['PATH'] import mitsuba from mitsuba.core import Vector, Point, Ray, Thread from mitsuba.render import SceneHandler import platform scenepath = session.get_scenefile_path() # if "Windows" in platform.system(): # scenepath = str(scenepath.replace('\\', '\\\\')) # 得到高程信息 通过光线跟踪的方法精确得到高程信息 fileResolver = Thread.getThread().getFileResolver() logger = Thread.getThread().getLogger() logger.clearAppenders() scenepath = scenepath.encode('utf-8') fileResolver.appendPath(scenepath) filepath = os.path.join(session.get_scenefile_path(), main_scene_xml_file_prifix + terr_scene_file).encode("utf-8") scene = SceneHandler.loadScene(fileResolver.resolve(filepath)) scene.configure() scene.initialize() return scene.getKDTree().getAABB()
sys.path.append(MITSUBA_PATH + 'python/2.7') os.environ['PATH'] = MITSUBA_PATH + os.pathsep + os.environ['PATH'] import mitsuba import multiprocessing from mitsuba.core import * from mitsuba.render import SceneHandler, RenderQueue, RenderJob fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath('cbox/') paramMap = StringMap() scene = SceneHandler.loadScene(fileResolver.resolve("cbox.xml"), paramMap) #print(scene) for nb_cores in range(1, multiprocessing.cpu_count()): scheduler = Scheduler.getInstance() for i in range(0, nb_cores): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() queue = RenderQueue() scene.setDestinationFile('rendererResult_c'+str(nb_cores)) job = RenderJob('testJob', scene, queue)
def forest_generate_according_tree_pos_file_for3d(config_file_path): import mitsuba from mitsuba.core import Vector, Point, Ray, Thread from mitsuba.render import SceneHandler from mitsuba.render import RenderQueue, RenderJob from mitsuba.render import Scene from mitsuba.render import Intersection f = open(config_file_path, 'r') cfg = json.load(f) tree_pos = combine_file_path(session.get_input_dir(), cfg["scene"]["forest"]["tree_pos_file"]) if cfg["scene"]["forest"]["tree_pos_file"] == "" or ( not os.path.exists(tree_pos)): return # 读取地形数据 计算每个树的高程 if cfg["scene"]["terrain"]["terrain_type"] != "PLANE" and cfg["scene"][ "terrain"]["terrain_type"] == "RASTER": demfile = combine_file_path(session.get_input_dir(), cfg["scene"]["terrain"]["terr_file"]) img_w, img_h, dem_arr = RasterHelper.read_dem_as_array(demfile) dem_arr = dem_arr - dem_arr.min() scenepath = session.get_scenefile_path() if "Windows" in platform.system(): scenepath = str(scenepath.replace('\\', '\\\\')) # 得到高程信息 通过光线跟踪的方法精确得到高程信息 fileResolver = Thread.getThread().getFileResolver() logger = Thread.getThread().getLogger() logger.clearAppenders() fileResolver.appendPath(scenepath) # 由于batch模式不会改变地形几何结构,因此在用地形打点计算树木的高程时,用第一个terrain文件即可,所以加上了_0_ scene = SceneHandler.loadScene( fileResolver.resolve(str(terr_scene_file))) scene.configure() scene.initialize() tf = open(tree_pos) objectPosFile = open( os.path.join(session.get_input_dir(), "object_pos_3dView.txt"), 'w') # 创建一个虚拟根节点,最后再删除 for line in tf: arr = line.replace("\n", "").split(" ") objectName = arr[0] x = float(arr[1]) y = float(arr[2]) xScale = cfg["scene"]["terrain"]["extent_width"] zScale = cfg["scene"]["terrain"]["extent_height"] treeX = 0.5 * xScale - x treeZ = 0.5 * zScale - y if cfg["scene"]["terrain"]["terrain_type"] != "PLANE": ray = Ray() ray.setOrigin(Point(treeX, 9999, treeZ)) ray.setDirection(Vector(0, -1, 0)) its = scene.rayIntersect(ray) if not its is None: linestr = objectName + " " + str(treeX) + " " + str( its.p[1]) + " " + str(treeZ) + "\n" else: # log("warning: precise height not found.") if cfg["scene"]["terrain"]["terrain_type"] == "RASTER": im_r = int((y / float(zScale)) * img_h) im_c = int((x / float(xScale)) * img_w) if im_r >= img_h: im_r = img_h - 1 if im_c >= img_w: im_c = img_w - 1 linestr = objectName + " " + str(treeX) + " " + str( dem_arr[im_r][im_c]) + " " + str(treeZ) + "\n" else: linestr = objectName + " " + str(treeX) + " " + str( 0) + " " + str(treeZ) + "\n" else: linestr = objectName + " " + str(treeX) + " " + str( 0) + " " + str(treeZ) + "\n" objectPosFile.write(linestr) objectPosFile.close()
if not exists("result"): mkdir("result") # Get a reference to the thread's file resolver fileResolver = Thread.getThread().getFileResolver() # Register any searchs path needed to load scene resources (optional) #fileResolver.appendPath('<path to scene directory>') # Optional: supply parameters that can be accessed # by the scene (e.g. as $myParameter) paramMap = StringMap() scene_name = argv[1] print "Rendering scene #%s#" % scene_name paramMap['myParameter'] = 'value' # Load the scene from an XML file scene = SceneHandler.loadScene( fileResolver.resolve( expanduser("/home/xhg/Desktop/kujiale_files/mitsuba/" + scene_name + "_full_new_diffuse_twosided.xml")), paramMap) scheduler = Scheduler.getInstance() # Start up the scheduling system with one worker per local core for i in range(0, multiprocessing.cpu_count()): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() # Create a queue for tracking render jobs queue = RenderQueue() sensor = scene.getSensor() shapes = scene.getShapes()
import mitsuba from mitsuba.core import * from mitsuba.render import SceneHandler fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath('~/CONF/QUIJIBO/renders/python') paramMap = StringMap() scene = SceneHandler.loadScene( fileResolver.resolve( "/Users/tkim/CONF/QUIJIBO/renders/python/bunny_zoom_0_1.xml"), paramMap) from mitsuba.core import * from mitsuba.render import RenderQueue, RenderJob import multiprocessing scheduler = Scheduler.getInstance() # Start up the scheduling system with one worker per local core for i in range(0, 4): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() queue = RenderQueue() import numpy as np from scipy import * target0 = Vector(0.681017, 0.344339, 0.841651) origin0 = Vector(1.06275, -0.147389, 1.62427) up0 = Vector(-0.180728, -0.870101, -0.458544) target1 = Vector(0.0329559, 0.23162, 0.731513) origin1 = Vector(0.975366, 0.0865425, 0.430146)
fileResolver = Thread.getThread().getFileResolver() paramMap = StringMap() scheduler = Scheduler.getInstance() for i in range(0, multiprocessing.cpu_count()): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() totalFrames = 1111 # upper_filepath = os.path.abspath(os.path.join(os.getcwd(), "../..")) for i in range(totalFrames): origin_now, target_now = bal.update("camera") processXML.changeXML_lookat( "scene_integrator_cam.xml", "perspective", origin_now, target_now) processXML.changeXML_translate( "scene_objs.xml", "cow.obj", bal.update("cow.obj")[0]) paramMap = StringMap() scene = SceneHandler.loadScene( fileResolver.resolve("scene_main.xml"), paramMap) queue = RenderQueue() scene.setDestinationFile('imgs/' + str(i) + '.jpg') # Create a render job and insert it into the queue job = RenderJob('myRenderJob', scene, queue) # render one img job.start() # Wait for all jobs to finish and release resources queue.waitLeft(0) queue.join()
print 'Starting frame', frame # # Scene parameters paramMap = StringMap() paramMap['target_x'] = str(target_x) paramMap['target_y'] = str(target_y) paramMap['target_z'] = str(target_z) paramMap['origin_x'] = str(origin_x) paramMap['origin_y'] = str(origin_y) paramMap['origin_z'] = str(origin_z) paramMap['up'] = '0, 1, 0' paramMap['sample_count'] = SampleCount # paramMap['mesh_filename'] = mesh_file paramMap['solid_filename'] = '../mesh/static_solids/levelset_solid.ply' scene = SceneHandler.loadScene(fileResolver.resolve(xml_name + '.xml'), paramMap) # # Create a queue for tracking render jobs queue = RenderQueue() exr_path = img_path + '/' + str(frame) + '_' + xml_name + '.exr' scene.setDestinationFile(exr_path) # # Create a render job and insert it into the queue job = RenderJob('myRenderJob', scene, queue) job.start() # # Wait for all jobs to finish and release resources queue.waitLeft(0) queue.join() # # Print some statistics about the rendering process
# # Path to density files density_file = '../density/' + str(frame) + '_density.vol' # while (not os.path.exists(density_file)): time.sleep(1) # print 'Starting frame', frame # # Scene parameters paramMap = StringMap() paramMap['sample_count'] = SampleCount paramMap['volume_scale'] = VolumeScale paramMap['density_filename'] = density_file # scene = SceneHandler.loadScene(fileResolver.resolve("smoke.xml"), paramMap) # # Create a queue for tracking render jobs queue = RenderQueue() scene.setDestinationFile(img_path + '/' + str(frame) + '_density.exr') # # Create a render job and insert it into the queue job = RenderJob('myRenderJob', scene, queue) job.start() # # Wait for all jobs to finish and release resources queue.waitLeft(0) queue.join() # # Print some statistics about the rendering process print(Statistics.getInstance().getStats())
def __init__(self, parent, width, height, barHeight, progressHeight, folderPath, sceneName, mitsubaPath, frameNumber, scenePath, renderWindowPosX, renderWindowPosY, pluginPath): QDialog.__init__( self, parent ) #global isWindowExist #isWindowExist = True #global window #window = self self.startRender = True self.folderPath = folderPath self.mitsubaPath = mitsubaPath self.frameNumber = frameNumber self.scenePath = scenePath # Initialize Mitsuba if renderWindowPosX == -1 and renderWindowPosY == -1: self.setGeometry((GetSystemMetrics(0) - width - 20) / 2,(GetSystemMetrics(1) - height - barHeight - progressHeight - 40)/2, width + 20, height + barHeight + progressHeight + 40) else: self.setGeometry(renderWindowPosX, renderWindowPosY, width + 20, height + barHeight + progressHeight + 40) self.Colorize() btnStop = QtGui.QPushButton("Stop", self) btnStop.setMaximumSize(70, barHeight) btnRefresh = QtGui.QPushButton("Refresh", self) btnRefresh.setMaximumSize(80, barHeight) btnSave = QtGui.QPushButton("Save", self) btnSave.setMaximumSize(70, barHeight) self.connect(btnStop, SIGNAL('clicked()'), self.stopMethod) self.connect(btnRefresh, SIGNAL('clicked()'), self.refreshMethod) self.connect(btnSave, SIGNAL('clicked()'), self.saveMethod) doneLabel = QLabel() font = QtGui.QFont('Tahoma', 14) font.setBold(True) doneLabel.setFont(font) doneLabel.setText("Rendering...") doneLabel.setStyleSheet("QLabel { color: #d37700; }"); sIcon = QIcon(pluginPath + "\\icons\\" + "save_3118.png") btnSave.setIcon(sIcon) stopIcon = QIcon(pluginPath + "\\icons\\" + "stop_32_1340.png") btnStop.setIcon(stopIcon) rIcon = QIcon(pluginPath + "\\icons\\" + "view-refresh_2730.png") btnRefresh.setIcon(rIcon) imgLabel = QLabel() qp = QtGui.QPainter() layout = QGridLayout(self) layout.setSpacing(10) layout.addWidget(btnSave, 1, 0) layout.addWidget(btnRefresh, 1, 1) layout.addWidget(btnStop, 1, 2) layout.addWidget(imgLabel, 2, 0, 1, 4) self.initializeMitsuba() self.scene = SceneHandler.loadScene(folderPath + "\\" + sceneName) self.show() self.job = RenderJob('rjob', self.scene, self.queue) self.job.setInteractive(True) # Initialize the user interface progress = QtGui.QProgressBar(self) layout.addWidget(doneLabel, 3, 0, 1, 3) layout.addWidget(progress, 3, 3) self.rwidget = RenderWidget(self, self.queue, self.scene.getFilm().getSize()) self.setWindowTitle('Mitsuba render window') # Hide the scroll bar once the rendering is done def renderingUpdated(event): progress.setValue(100 * self.rwidget.extProgress / (self.rwidget.extIMG.width() * self.rwidget.extIMG.height())) imgLabel.setPixmap(QPixmap.fromImage(self.rwidget.extIMG)); if event == MitsubaRenderBuffer.RENDERING_FINISHED: lm("FINISH!!!") self.startRender = False #progress.hide() doneLabel.setText("Done!") doneLabel.setStyleSheet("QLabel { color: #00d328; }"); self.rwidget.renderingUpdated.connect(renderingUpdated, Qt.QueuedConnection) # Start the rendering process self.job.start()
def forest_generate_according_tree_pos_file(config_file_path, forest_file_name, linestart, lineend, forest_prifix=""): import mitsuba from mitsuba.core import Vector, Point, Ray, Thread from mitsuba.render import SceneHandler from mitsuba.render import RenderQueue, RenderJob from mitsuba.render import Scene from mitsuba.render import Intersection f = open(config_file_path, 'r') cfg = json.load(f) tree_pos = combine_file_path(session.get_input_dir(), cfg["scene"]["forest"]["tree_pos_file"]) if cfg["scene"]["forest"]["tree_pos_file"] == "" or ( not os.path.exists(tree_pos)): return # 保存场景中树的位置 forest*.xml # f = open(os.path.join(session.get_scenefile_path(),forest_file_name),'w') f = codecs.open( os.path.join(session.get_scenefile_path(), forest_file_name), "w", "utf-8-sig") doc = minidom.Document() root = doc.createElement("scene") doc.appendChild(root) root.setAttribute("version", "0.5.0") #读取地形数据 计算每个树的高程 if cfg["scene"]["terrain"]["terrain_type"] != "PLANE" and cfg["scene"][ "terrain"]["terrain_type"] == "RASTER": demfile = combine_file_path(session.get_input_dir(), cfg["scene"]["terrain"]["terr_file"]) img_w, img_h, dem_arr = RasterHelper.read_dem_as_array(demfile) dem_arr = dem_arr - dem_arr.min() #读取object boundingbox 数据 bound_path = os.path.join(session.get_input_dir(), obj_bounding_box_file) if os.path.exists(bound_path): fobj = open(bound_path) bound_dict = dict() for line in fobj: arr = line.split(":") objName = arr[0] arr = list(map(lambda x: float(x), arr[1].split(" "))) bound_dict[objName] = [ arr[3] - arr[0], arr[4] - arr[1], arr[5] - arr[2] ] scenepath = session.get_scenefile_path() # if "Windows" in platform.system(): # scenepath = str(scenepath.replace('\\', '\\\\')) #得到高程信息 通过光线跟踪的方法精确得到高程信息 fileResolver = Thread.getThread().getFileResolver() logger = Thread.getThread().getLogger() logger.clearAppenders() fileResolver.appendPath(str(scenepath)) # 由于batch模式不会改变地形几何结构,因此在用地形打点计算树木的高程时,用第一个terrain文件即可,所以加上了_0_ # if(forest_prifix != ""): # forest_prifix = forest_prifix[0:len(forest_prifix)-1] +"_0_" scene = SceneHandler.loadScene( fileResolver.resolve(str(forest_prifix + terr_scene_file))) # scene = SceneHandler.loadScene(fileResolver.resolve(r"E:\Research\20-LESS\RealScene\SimProj\calLAI\Parameters\_scenefile\terrain1.xml")) scene.configure() scene.initialize() tf = open(tree_pos) hidden_objects = SceneGenerate.get_hidded_objects() #创建一个虚拟根节点,最后再删除 treeIdx = 0 for line in tf: if treeIdx >= linestart and treeIdx <= lineend: arr = line.replace("\n", "").strip().split(" ") objectName = arr[0] if objectName in hidden_objects: continue shapenode = doc.createElement("shape") root.appendChild(shapenode) shapenode.setAttribute("type", "instance") refnode = doc.createElement("ref") shapenode.appendChild(refnode) refnode.setAttribute("id", objectName) trnode = doc.createElement("transform") shapenode.appendChild(trnode) trnode.setAttribute("name", "toWorld") if len(arr) == 6: # fit with scale_node = doc.createElement("scale") trnode.appendChild(scale_node) scale_node.setAttribute( "x", str(float(arr[4]) / bound_dict[objectName][0])) scale_node.setAttribute( "z", str(float(arr[4]) / bound_dict[objectName][0])) scale_node.setAttribute( "y", str(float(arr[5]) / bound_dict[objectName][1])) if len(arr) == 5: # for rotation of the tree angle = arr[len(arr) - 1] rotatenode = doc.createElement("rotate") trnode.appendChild(rotatenode) rotatenode.setAttribute("y", '1') rotatenode.setAttribute("angle", angle) translatenode = doc.createElement("translate") trnode.appendChild(translatenode) x = float(arr[1]) y = float(arr[2]) z = float(arr[3]) xScale = cfg["scene"]["terrain"]["extent_width"] zScale = cfg["scene"]["terrain"]["extent_height"] # treeX = xScale - x * (2 * xScale) / float(img_w) # treeZ = zScale - y * (2 * zScale) / float(img_h) treeX = 0.5 * xScale - x treeZ = 0.5 * zScale - y translatenode.setAttribute("x", str(treeX)) translatenode.setAttribute("z", str(treeZ)) if cfg["scene"]["terrain"]["terrain_type"] != "PLANE": ray = Ray() ray.setOrigin(Point(treeX, 9999, treeZ)) ray.setDirection(Vector(0, -1, 0)) its = scene.rayIntersect(ray) if not its is None: translatenode.setAttribute("y", str(its.p[1] + z)) # translatenode.setAttribute("y", str(z)) else: # log("warning: precise height not found.") if cfg["scene"]["terrain"]["terrain_type"] == "RASTER": im_r = int((y / float(zScale)) * img_h) im_c = int((x / float(xScale)) * img_w) if im_r >= img_h: im_r = img_h - 1 if im_c >= img_w: im_c = img_w - 1 translatenode.setAttribute( "y", str(dem_arr[im_r][im_c] + z)) else: translatenode.setAttribute("y", str(z)) else: translatenode.setAttribute("y", str(z)) treeIdx += 1 xm = doc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') f.write(xm) f.close() log("INFO: Objects and positions generated.")
def main(argv): scene_xml_name = '' camera_txt_name = '' output_folder = '' camera_indicate_name = '' # Read command line args opts, args = getopt.getopt(argv, "s:c:o:h:g:") for opt, arg in opts: if opt == '-h': print 'mitsuba_render.py -s <scene_xml> -c <camera_file> -g <good_camera_indicator_file> -o <output_directory>' sys.exit() elif opt in ("-s", "--scenefile"): scene_xml_name = arg elif opt in ("-c", "--camerafile"): camera_txt_name = arg elif opt in ("-o", "--outputdir"): output_folder = arg elif opt in ("-g", "--goodcamerafile"): camera_indicate_name = arg print('Render job for %s starts...\n' % scene_xml_name) if not os.path.exists(output_folder): os.makedirs(output_folder) camera = np.loadtxt(camera_txt_name) goodcam = np.loadtxt(camera_indicate_name) last_dest = output_folder + '%06i_mlt.png' % (len(camera) - 1) if os.path.isfile(last_dest): print('Job is done in the first round.\n') return tmp = scene_xml_name.split('/') work_path = '/'.join(tmp[0:-1]) os.chdir(work_path) paramMap = StringMap() paramMap['emitter_scale'] = '75' paramMap['fov'] = '63.414969' paramMap['origin'] = '0 0 0' paramMap['target'] = '1 1 1' paramMap['up'] = '1 0 0' paramMap['sampler'] = '1024' paramMap['width'] = '640' paramMap['height'] = '480' paramMap['envmap_path'] = './util_data/HDR_111_Parking_Lot_2_Ref.hdr' paramMap['default_texture_path'] = './util_data/wallp_0.jpg' fileResolver = Thread.getThread().getFileResolver() scene = SceneHandler.loadScene(fileResolver.resolve(scene_xml_name), paramMap) scheduler = Scheduler.getInstance() # Start up the scheduling system with one worker per local core for i in range(0, multiprocessing.cpu_count()): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() # Create a queue for tracking render jobs queue = RenderQueue() from mitsuba.render import Scene sensor = scene.getSensor() scene.initialize() for i in range(0, len(camera)): if goodcam[i] < 0.5: continue destination = output_folder + '%06i_mlt' % i if os.path.isfile(destination + '.rgbe'): continue c = camera[i] t = Transform.lookAt(Point(c[0], c[1], c[2]), Point(c[0] + c[3], c[1] + c[4], c[2] + c[5]), Vector(c[6], c[7], c[8])) sensor.setWorldTransform(t) scene.setDestinationFile(destination) # # Create a render job and insert it into the queue. Note how the resource # # ID of the original scene is provided to avoid sending the full scene # # contents over the network multiple times. job = RenderJob('myRenderJob' + str(i), scene, queue) job.start() queue.waitLeft(0) print('%d render jobs finished!\n' % len(camera))
def do_simulation_multiangle_seq(seqname): currdir = os.path.split(os.path.realpath(__file__))[0] sys.path.append(currdir + '/bin/rt/' + current_rt_program + '/python/2.7/') os.environ['PATH'] = currdir + '/bin/rt/' + current_rt_program + os.pathsep + os.environ['PATH'] import mitsuba from mitsuba.core import Vector, Point, Ray, Thread, Scheduler, LocalWorker, PluginManager, Transform from mitsuba.render import SceneHandler from mitsuba.render import RenderQueue, RenderJob from mitsuba.render import Scene import multiprocessing scheduler = Scheduler.getInstance() for i in range(0, multiprocessing.cpu_count()): scheduler.registerWorker(LocalWorker(i, 'wrk%i' % i)) scheduler.start() scene_path = session.get_scenefile_path() fileResolver = Thread.getThread().getFileResolver() fileResolver.appendPath(str(scene_path)) scene = SceneHandler.loadScene(fileResolver.resolve( str(os.path.join(session.get_scenefile_path(), main_scene_xml_file)))) scene.configure() scene.initialize() queue = RenderQueue() sceneResID = scheduler.registerResource(scene) bsphere = scene.getKDTree().getAABB().getBSphere() radius = bsphere.radius targetx, targety, targetz = bsphere.center[0], bsphere.center[1], bsphere.center[2] f = open(seqname + ".conf", 'r') params = json.load(f) obs_azimuth = params['seq1']['obs_azimuth'] obs_zenith = params['seq2']['obs_zenith'] cfgfile = session.get_config_file() f = open(cfgfile, 'r') cfg = json.load(f) viewR = cfg["sensor"]["obs_R"] mode = cfg["sensor"]["film_type"] azi_arr = map(lambda x: float(x), obs_azimuth.strip().split(":")[1].split(",")) zeni_arr = map(lambda x: float(x), obs_zenith.strip().split(":")[1].split(",")) seq_header = multi_file_prefix + "_" + seqname index = 0 for azi in azi_arr: for zeni in zeni_arr: distFile = os.path.join(session.get_output_dir(), seq_header + ("_VA_%.2f" % azi).replace(".", "_") + ("_VZ_%.2f" % zeni).replace(".", "_")) newScene = Scene(scene) pmgr = PluginManager.getInstance() newSensor = pmgr.createObject(scene.getSensor().getProperties()) theta = zeni / 180.0 * math.pi phi = (azi - 90) / 180.0 * math.pi scale_x = radius scale_z = radius toWorld = Transform.lookAt( Point(targetx - viewR * math.sin(theta) * math.cos(phi), targety + viewR * math.cos(theta), targetz - viewR * math.sin(theta) * math.sin(phi)), # original Point(targetx, targety, targetz), # target Vector(0, 0, 1) # up ) * Transform.scale( Vector(scale_x, scale_z, 1) # 视场大小 ) newSensor.setWorldTransform(toWorld) newFilm = pmgr.createObject(scene.getFilm().getProperties()) newFilm.configure() newSensor.addChild(newFilm) newSensor.configure() newScene.addSensor(newSensor) newScene.setSensor(newSensor) newScene.setSampler(scene.getSampler()) newScene.setDestinationFile(str(distFile)) job = RenderJob('Simulation Job' + "VA_"+str(azi)+"_VZ_"+str(zeni), newScene, queue, sceneResID) job.start() queue.waitLeft(0) queue.join() # handle npy if mode == "spectrum" and (output_format not in ("npy", "NPY")): for azi in azi_arr: for zeni in zeni_arr: distFile = os.path.join(session.get_output_dir(), seq_header + ("_VA_%.2f" % azi).replace(".", "_") + ("_VZ_%.2f" % zeni).replace( ".", "_")) data = np.load(distFile + ".npy") bandlist = cfg["sensor"]["bands"].split(",") RasterHelper.saveToHdr_no_transform(data, distFile, bandlist, output_format) os.remove(distFile + ".npy")