Example #1
0
    def execute(self, context):
        global db_results
        global last_import

        wm = bpy.context.window_manager
        to_import = [d for d in db_results if d['name'] == wm.query_results][0]
        if last_import == 'object':
            print('--- importing: ---')
            print(to_import)
            O = bvp.Object(**to_import)
            O.Place(proxy=self.proxy_import)
        elif last_import == 'action':
            raise NotImplementedError(
                'Not yet! need to apply actions to objects!')
        return {'FINISHED'}
Example #2
0
			camConstr = None # Size=...
			obConstr = None # Size=...			
	else:
		# Needs modification! defaults should depend on real world size / size of floor mesh / something...
		# OR: simply raise error, and demand that all files have pos constraints.
		camConstr = bvp.CamConstraint() # Size=...
		obConstr = bvp.bvpObConstraint() # Size=...
	try:
		rws = gOb['RealWorldSize'], # of the whole space
	except:
		rws = 100.
	try:
		Lens = gOb['Lens']
	except:
		Lens = 50.
	d.append(dict(
			fname=bpy.data.filepath,
			name=G.name,
			semantic_category=semCat,
			real_world_size=rws,
			lens=Lens,
			nVertices=sum([len(oo.data.vertices) for oo in G.objects if oo.type=='MESH']),
			nFaces=sum([len(oo.data.polygons) for oo in G.objects if oo.type=='MESH']),
			obConstraints=obConstr,
			CamConstraint=camConstr,
			obSemanticCat=obCat, ## List of object categories that can (reasonably) populate this scene
			sky_semantic_category=skyCat, ## List of sky categories that can go with this background.
			obstacles=[bvp.Object(pos3D=list(o.location),size3D=max(o.dimensions)) for o in Obst], ## To come! ##
			))
sName = bpy.data.filepath.replace('.blend','.pik')
savePik(d,sName)
Example #3
0
if subCat:
	ToRender = Lib.getSCL(subCat,'objects')
else:
	ToRender = Lib.objects # all objects

ScCt = 0
ScnL = []
for o in ToRender:
	# Get all object variations to add as separate scenes
	ObToAdd = []
	for s in oSz:
		for pos in oPos:
			for rotZ in oRot:
				if o['nPoses'] and render_Pose:
					for p in range(o['nPoses']):
						O = bvp.Object(obID=o['name'],Lib=Lib,pos3D=pos,size3D=s,rot3D=(0,0,rotZ),pose=p)
						ObToAdd.append(O)
						if scaleObj:
							ScObSz = 10.*scaleObj.size3D/O.size3D
							ScObToAdd.append
				else:
					O = bvp.Object(obID=o['name'],Lib=Lib,pos3D=pos,size3D=s,rot3D=(0,0,rotZ))
					ObToAdd.append(O)
					# Add scale object in here somehwhere... Scale for each object!
					if scaleObj:
						ScObSz = 10.*scaleObj.size3D/O.size3D
						ScObToAdd.append
	# Lights (Sky), Background
	Sky = bvp.Sky()
	BG = bvp.Background()
	# Objects
Example #4
0
print('%s\n~~~    Running mlOFFexportLoop.py    ~~~\n%s ' % (Div, Div))
print(bvp.version)

Res = sk.Settings['VolRes']  # Default (2012.08.13) = 96
# establish memory-saving mode for multiple imports:
#? necessary?

#LibDir = bvp.Settings['Paths']['LibDir']
#if not LibDir==sk.Settings['LibDir']:
#	raise Exception('Path problem! pfSkel settings "LibDir" does not match bvp settings "LibDir". GAAAAAA!')

Lib = bvp.bvpLibrary()
name = 'Reptile_005_Frog'  #'Mammal_005_Cat'
#for name in Lib.getGrpNames():
# Get & add object
O = bvp.Object(name, Lib, size3D=10)
O.Place()
G = bpy.context.object
# Make proxy objects & create render mesh for all objects in group
ObList = []
scn = bpy.context.scene
for o in G.dupli_group.objects:
    bvp.utils.blender.grab_only(G)
    bpy.ops.object.proxy_make(object=G.name, type=o.name)
    NewOb = bpy.context.object
    if NewOb.type == 'MESH':
        me = NewOb.to_mesh(scn, True, 'RENDER')
        NewOb.data = me
    else:
        continue
    ObList.append(NewOb)
Example #5
0
RO = bvp.RenderOptions()
RO.filepath = '/auto/k6/mark/BlenderFiles/LibBackgrounds/%s'
DummyObjects = ['*soccer ball','*fire extinguisher','002_CartoonGuy']
if SubCat:
	ToRender = Lib.getSCL(SubCat,'backgrounds')
else:
	ToRender = Lib.backgrounds # all backgrounds

# Frame count
frames = (1,1)
# set standard lights (Sky)
Sky = bvp.Sky()
# Get dummy objects to put in scenes:
ObL = []
for o in DummyObjects:
	ObL.append(bvp.Object(obID=o,Lib=Lib,size3D=None)
# Misc Setup
BGCt = 0;
ScnL = []
for bg in ToRender:
	BGCt+=1
	# Create Scene
	BG = bvp.Background(bgID=bg['name'],Lib=Lib)
	for p in range(nCamLoc):
		cNum = p+1
		Cam = bvp.Camera(location=BG.CamConstraint.sampleCamPos(frames),fixPos=BG.CamConstraint.sampleFixPos(frames),frames=frames)
		S = bvp.Scene(Num=BGCt,BG=BG,Sky=Sky,Obj=None,
							Shadow=None,Cam=Cam,FrameRange=(1,1),
							fpath='%s_%s_cp%d_fr##'%(BG.semantic_category[0],BG.name,cNum),
							FrameRate=15)
		try:
Example #6
0
    def RenderSkies(self, subCat=None, Is_Overwrite=False):
        """
		Render (all) skies in bvpLibrary to folder <LibDir>/LibBackgrounds/<category>_<name>.png

		subCat = None # lambda x: 'dome' in x['semantic_category']
		"""
        raise Exception('Not done yet!')
        RO = bvp.RenderOptions()
        RO.BVPopts['BasePath'] = os.path.join(self.LibDir, 'Images', 'Skies',
                                              '%s')
        RO.resolution_x = RO.resolution_y = 256  # smaller images
        if subCat:
            ToRender = self.getSCL(subCat, 'backgrounds')
        else:
            ToRender = self.backgrounds  # all backgrounds
        # Frame count
        frames = (1, 1)
        # set standard lights (Sky)
        Sky = bvp.Sky()
        # Get dummy objects to put in scenes:
        ObL = []
        for o in dummyObjects:
            ObL.append(bvp.Object(obID=o, Lib=self, size3D=None))
        # Misc Setup
        BGCt = 0
        ScnL = []
        for bg in ToRender:
            BGCt += 1
            # Create Scene
            BG = bvp.Background(bgID=bg['name'], Lib=self)
            for p in range(nCamLoc):
                cNum = p + 1
                fpath = '%s_%s_cp%d_fr##' % (BG.semantic_category[0], BG.name,
                                             cNum)
                fChk = RO.BVPopts['BasePath'] % fpath.replace(
                    '##', '01.' + RO.file_format.lower())
                print('Checking for file: %s' % (fChk))
                if os.path.exists(fChk) and not Is_Overwrite:
                    print('Found it!')
                    # Only append scenes to render that DO NOT have previews already rendered!
                    continue
                Cam = bvp.Camera(
                    location=BG.CamConstraint.sampleCamPos(frames),
                    fixPos=BG.CamConstraint.sampleFixPos(frames),
                    frames=frames)
                S = bvp.Scene(Num=BGCt,
                              BG=BG,
                              Sky=Sky,
                              Obj=None,
                              Shadow=None,
                              Cam=Cam,
                              FrameRange=(1, 1),
                              fpath=fpath,
                              FrameRate=15)
                #try:
                # Allow re-set of camera position with each attempt to populate scene
                S.populate_scene(ObL, ResetCam=True)
                #except:
                #	print('Unable to populate scene %s!'%S.fpath)
                ScnL.append(S)
        # Convert list of scenes to SceneList
        SL = bvp.SceneList(ScnList=ScnL, RenderOptions=RO)
        SL.RenderSlurm(RenderGroupSize=nCamLoc)
Example #7
0
    def RenderBGs(self,
                  subCat=None,
                  dummyObjects=(),
                  nCamLoc=5,
                  Is_Overwrite=False):
        """
		Render (all) backgrounds in bvpLibrary to folder <LibDir>/Images/Backgrounds/<category>_<name>.png

		subCat = None #lambda x: x['name']=='BG_201_mHouse_1fl_1' #None #'outdoor'		
		dummyObjects = ['*human', '*artifact', '*vehicle']
		"""
        RO = bvp.RenderOptions()
        RO.BVPopts['BasePath'] = os.path.join(self.LibDir, 'Images',
                                              'Backgrounds', '%s')
        RO.resolution_x = RO.resolution_y = 256  # smaller images
        if subCat:
            ToRender = self.getSCL(subCat, 'backgrounds')
        else:
            ToRender = self.backgrounds  # all backgrounds
        # Frame count
        frames = (1, 1)
        # Get dummy objects to put in scenes:
        # Misc Setup
        BGCt = 0
        ScnL = []
        for bg in ToRender:
            BGCt += 1
            # Create Scene
            BG = bvp.Background(bgID=bg['name'], Lib=self)
            ObL = []
            for o in dummyObjects:
                ObL.append(bvp.Object(obID=o, Lib=self, size3D=None))

            for p in range(nCamLoc):
                cNum = p + 1
                fpath = '%s_%s_cp%02d_fr##' % (BG.semantic_category[0],
                                               BG.name, cNum)
                fChk = RO.BVPopts['BasePath'] % fpath.replace(
                    '##', '01.' + RO.image_settings['file_format'].lower())
                print('Checking for file: %s' % (fChk))
                if os.path.exists(fChk) and not Is_Overwrite:
                    print('Found it!')
                    # Only append scenes to render that DO NOT have previews already rendered!
                    continue
                Cam = bvp.Camera(
                    location=BG.CamConstraint.sampleCamPos(frames),
                    fixPos=BG.CamConstraint.sampleFixPos(frames),
                    frames=frames)
                Sky = bvp.Sky('*' + BG.sky_semantic_category[0], Lib=self)
                if Sky.semantic_category:
                    if 'dome' in Sky.semantic_category:
                        if len(Sky.lightLoc) > 1:
                            Shad = None
                        elif len(Sky.lightLoc) == 1:
                            if 'sunset' in Sky.semantic_category:
                                Shad = bvp.Shadow('*west', self)
                            else:
                                fn = lambda x: 'clouds' in x[
                                    'semantic_category'] and not 'west' in x[
                                        'semantic_category']
                                Shad = bvp.Shadow(fn, self)
                        else:
                            Shad = None
                else:
                    Shad = None

                S = bvp.Scene(Num=BGCt,
                              BG=BG,
                              Sky=Sky,
                              Obj=None,
                              Shadow=Shad,
                              Cam=Cam,
                              FrameRange=frames,
                              fpath=fpath,
                              FrameRate=15)
                try:
                    # Allow re-set of camera position with each attempt to populate scene
                    S.populate_scene(ObL, ResetCam=True)
                except:
                    print('Unable to populate scene %s!' % S.fpath)
                ScnL.append(S)
        # Convert list of scenes to SceneList
        SL = bvp.SceneList(ScnList=ScnL, RenderOptions=RO)
        SL.RenderSlurm(RenderGroupSize=nCamLoc)
Example #8
0
    def RenderObjectVox(self,
                        nGrid=10,
                        xL=(-5, 5),
                        yL=(-5, 5),
                        zL=(0, 10),
                        maxFilesPerDir=5000,
                        subCat=None,
                        render_Pose=True,
                        Is_Overwrite=False):
        """
		Render (all) objects in bvpLibrary in voxelized 3D form

		TODO: longer help!
		ScaleObj = optional scale object to render along with this object (NOT FINISHED!)
		"""
        if bvp.Is_Blender:
            print('Sorry, this won'
                  't run inside Blender; it requires access to slurm!')
            return
        RO = bvp.RenderOptions()
        RO.BVPopts['Voxels'] = True  # This will over-ride all other options...
        RO.BVPopts['BasePath'] = os.path.join(self.LibDir, 'Images', 'Objects',
                                              'Voxels', '%s')
        RO.BVPopts['Type'] = 'all'
        RO.resolution_x = RO.resolution_y = 5  # itty-bitty images for inside/outside test

        if subCat:
            ToRender = self.getSCL(subCat, 'objects')
        else:
            ToRender = self.objects  # all objects

        ObCt = 0
        for o in ToRender:
            ScnL = []
            # Get all object variations to add as separate scenes
            ObToAdd = []
            if o['nPoses'] and render_Pose:
                for p in range(o['nPoses']):
                    O = bvp.Object(obID=o['name'],
                                   Lib=self,
                                   pos3D=(0, 0, 0),
                                   size3D=10,
                                   pose=p)
                    ObToAdd.append(O)
            else:
                O = bvp.Object(obID=o['name'],
                               Lib=self,
                               pos3D=(0, 0, 0),
                               size3D=10)
                ObToAdd.append(O)
            # Lights (Sky) & Background
            Sky = bvp.Sky()
            Sky.WorldParams['horizon_color'] = (0, 0, 0)
            BG = bvp.Background()
            # Get all (nGrid**3) camera positions
            cPos = bvp.utils.basics.gridPos(nGrid, xL, yL, zL)
            # Center (fixation) Position
            fPos = [[0, 0, 0] for x in range(len(cPos))]
            fr = range(1, nGrid**3 + 1)
            # break up into multiple directories with <maxFilesPerDir> files each
            nDirs = int(math.ceil((nGrid**3) / float(maxFilesPerDir)))
            # Loop over objects to render each <maxFilesPerDir> files
            for Obj in ObToAdd:
                # Loop to create a separate scene for each <maxFilesPerDir> files
                for d in range(nDirs):
                    # Create Scene
                    ObCt += 1
                    if Obj.pose or Obj.pose == 0:
                        pNum = Obj.pose + 1
                    else:
                        pNum = 1
                    # Frame range
                    FR = (d * maxFilesPerDir + 1,
                          min(nGrid**3, maxFilesPerDir * (d + 1)))
                    Cam = bvp.Camera(location=cPos[FR[0] - 1:FR[1]],
                                     fixPos=fPos[FR[0] - 1:FR[1]],
                                     frames=fr[FR[0] - 1:FR[1]])
                    fpath = '%s_%s_p%d_res%d_f%09d/vox%s' % (
                        Obj.semantic_category[0], Obj.name, pNum, nGrid,
                        d * maxFilesPerDir, '#' * len(str(nGrid**3)))
                    ScnL.append(
                        bvp.Scene(Num=ObCt,
                                  Obj=(Obj, ),
                                  BG=BG,
                                  Sky=Sky,
                                  Shadow=None,
                                  Cam=Cam,
                                  FrameRange=FR,
                                  fpath=fpath))
            # Convert list of scenes to SceneList
            SL = bvp.SceneList(ScnList=ScnL, RenderOptions=RO)
            #return SL
            jIDs = SL.RenderSlurm(RenderGroupSize=1,
                                  RenderType=('Voxels', ),
                                  Is_Overwrite=True)
            ConcatCmd = """import bvp, pickle, os
fD = '{fD}'
vox = bvp.utils.math.concatVoxels(fD)
sName = fD+'.pik'
bvp.utils.basics.savePik(vox, sName)
for f in os.listdir(fD): os.unlink(os.path.join(fD, f))
os.rmdir(fD)
			"""
            cjIDs = []
            for jID, S in zip(jIDs, ScnL):
                DepStr = 'afterok:%s' % jID  # Dependencies for job
                fD, xx = S.fpath.split('/')  # last part of filepath from scene
                fD = RO.BVPopts['BasePath'] % fD
                cjID = bvp.utils.basics.pySlurm(
                    ConcatCmd.format(fD=fD),
                    dep=DepStr,
                    memory=2000,
                )
                cjIDs.append(cjID)
                # Up priority... (base is 5000 as of 2012.12.31)
                subprocess.call([
                    'sudo', 'scontrol', 'update', 'jobID=' + jID,
                    'Priority=5010'
                ])
            # Final concatenation and clean-up
            ConcatAllCmd = """import bvp, os
import numpy as np
I = np.zeros({res}**3)
fD = "{fD}"
fNm = sorted([os.path.join(fD, f) for f in os.listdir(fD) if 'pik' in f and "{key}" in f])
for f in fNm:
	I+=np.array(bvp.utils.basics.loadPik(f))
I = bvp.utils.basics.make_blender_safe(I, 'float')
sName = os.path.join(fD, "{key}"+".pik")
bvp.utils.basics.savePik(I, sName)
for f in fNm:
	os.unlink(f)
"""
            DepStr = ('afterok' + ':%s' * len(cjIDs)) % tuple(
                cjIDs)  # Depends on all other concat jobs
            fD, key = os.path.split(fD)
            key = key[:-11]  # Cut "_f000000000" part
            bvp.utils.basics.pySlurm(
                ConcatAllCmd.format(res=nGrid, fD=fD, key=key),
                dep=DepStr,
                memory=2000,
            )
Example #9
0
    def RenderObjects(self,
                      Type=('Image', ),
                      subCat=None,
                      rotList=(0, ),
                      render_Pose=True,
                      renderGroupSize=1,
                      Is_Overwrite=False,
                      scaleObj=None):
        """
		Render (all) objects in bvpLibrary

		TODO: longer help!
		ScaleObj = optional scale object to render along with this object (NOT FINISHED!)
		"""

        RO = bvp.RenderOptions()
        RO.BVPopts['BasePath'] = os.path.join(self.LibDir, 'Images', 'Objects',
                                              'Scenes', '%s')
        RO.resolution_x = RO.resolution_y = 256  # smaller images

        if subCat:
            ToRender = self.getSCL(subCat, 'objects')
        else:
            ToRender = self.objects  # all objects

        ObCt = 0
        ScnL = []
        for o in ToRender:
            # Get all object variations to add as separate scenes
            ObToAdd = []
            for rotZ in rotList:
                if o['nPoses'] and render_Pose:
                    for p in range(o['nPoses']):
                        O = bvp.Object(obID=o['name'],
                                       Lib=self,
                                       pos3D=(0, 0, 0),
                                       size3D=10,
                                       rot3D=(0, 0, rotZ),
                                       pose=p)
                        ObToAdd.append(O)
                        if scaleObj:
                            ScObSz = 10. * scaleObj.size3D / O.size3D
                            ScObToAdd.append
                else:
                    O = bvp.Object(obID=o['name'],
                                   Lib=self,
                                   pos3D=(0, 0, 0),
                                   size3D=10,
                                   rot3D=(0, 0, rotZ))
                    ObToAdd.append(O)
                    # Add scale object in here somehwhere... Scale for each object!
                    if scaleObj:
                        ScObSz = 10. * scaleObj.size3D / O.size3D
                        ScObToAdd.append
            # Camera, Lights (Sky), Background
            Cam = bvp.Camera()
            Sky = bvp.Sky()
            BG = bvp.Background()
            # Objects
            for Obj in ObToAdd:
                # Create Scene
                ObCt += 1
                if Obj.pose or Obj.pose == 0:
                    pNum = Obj.pose + 1
                else:
                    pNum = 1
                fpath = '%s_%s_p%d_r%d_fr##' % (Obj.semantic_category[0],
                                                Obj.name, pNum, Obj.rot3D[2])
                ScnL.append(
                    bvp.Scene(Num=ObCt,
                              Obj=(Obj, ),
                              BG=BG,
                              Sky=Sky,
                              Shadow=None,
                              Cam=Cam,
                              FrameRange=(1, 1),
                              fpath=fpath,
                              FrameRate=15))
        # Convert list of scenes to SceneList
        SL = bvp.SceneList(ScnList=ScnL, RenderOptions=RO)
        SL.RenderSlurm(RenderGroupSize=renderGroupSize, RenderType=Type)
Example #10
0
    ToRender = Lib.getSCL(SubCat)
else:
    ToRender = Lib.objects  # all objects

ObCt = 0
ScnL = []
for o in ToRender:
    # Get all object variations to add as separate scenes
    ObToAdd = []
    for rotZ in rotList:
        if o['nPoses']:
            for p in range(o['nPoses']):
                ObToAdd.append(
                    bvp.Object(obID=o['name'],
                               Lib=Lib,
                               pos3D=(0, 0, 0),
                               size3D=10,
                               rot3D=(0, 0, rotZ),
                               pose=p))
        else:
            ObToAdd.append(
                bvp.Object(obID=o['name'],
                           Lib=Lib,
                           pos3D=(0, 0, 0),
                           size3D=10,
                           rot3D=(0, 0, rotZ)))
    # Camera, Lights (Sky), Background
    Cam = bvp.Camera()
    Sky = bvp.Sky()
    BG = bvp.Background()
    # Set up list of scenes for SceneList