示例#1
0
def _import_ytsurface(vertices, colors, alpha, emisses, colorindex, 
                      meshname='Steve', meshlocation=(0,0,0), plot_index=0):
    import numpy as np
    deselect_all()
    nftype = [("f1","int"),("f2","int"),("f3","int"),("f4","int")]
    newfaces = np.empty(int(len(vertices)/3.), dtype=nftype) # store sets of face colors
    cc = 0
    for i in range(0,int(len(vertices)/3.)):
        newfaces[i] = (cc, cc+1, cc+2, cc) # repeat last for triangles
        cc = cc+3
    me = bpy.data.meshes.new(meshname+"Mesh")
    ob = bpy.data.objects.new(meshname,me)
    ob.location = meshlocation   # position object at 3d-cursor
    bpy.context.scene.objects.link(ob)                # Link object to scene
    # Fill the mesh with verts, edges, faces 
    me.from_pydata(vertices.tolist(),[],newfaces.tolist())
    me.update(calc_edges=True)    # Update mesh with new data
    # materials woop woop!
    obj = bpy.data.objects[meshname]
    bpy.context.scene.objects.active=obj
    for i in range(0,len(colors[0])):
        mat = makeMaterial(meshname+str(i)+'_'+str(plot_index), 
                           (colors[0][i],colors[1][i],colors[2][i]), 
                           (1,1,1), alpha, emisses[i])
        setMaterial(obj,mat)
    # now, do individual mat indecies
    for i in range(0,len(newfaces)):
        me.polygons[i].material_index = colorindex[i]
示例#2
0
 def color(self,color): 
     bpy.context.scene.objects.active = bpy.data.objects[self.__name]
     delete_unused_materials(self.__name)
     sphmat = makeMaterial(self.__name, color, (1,1,1), 1.0, 0.0) # no emissivity or transperency for now
     setMaterial(bpy.data.objects[self.__name], sphmat)
     self.__color = color
示例#3
0
def import_ytsph(filename, halo_sizes, color_field, color_map, color_log, n_ref):
    from yt import load
    import numpy as np
    import bmesh
    from scienceutils import deselect_all
    from scienceutils import makeMaterial, setMaterial
    ds = load(filename)
    # strip "/" for naming
    xnn2 = 0
    xnn = 0
    # you only want the file name, not all the directory stuff
    while xnn != -1:
        xnn2 = xnn
        xnn = filename.find('/',xnn+1)
    fname_out = filename[xnn2+1:]            
    # get coords and color data
    dd = ds.all_data()
    #xcoord = dd['Gas','Coordinates'][:,0].v
    #ycoord = dd['Gas','Coordinates'][:,1].v
    #zcoord = dd['Gas','Coordinates'][:,2].v
    xcoord = (dd['Gas','Coordinates'][:,0].in_units('unitary')).v
    ycoord = (dd['Gas','Coordinates'][:,1].in_units('unitary')).v
    zcoord = (dd['Gas','Coordinates'][:,2].in_units('unitary')).v
    cs = dd[color_field]
    print('cs')
    print(len(cs))
    # map colorcode to 256 material colors
    if color_log: cs = np.log10(cs)
    mi, ma = cs.min(), cs.max()
    cs = (cs - mi) / (ma - mi)
    from yt.visualization._colormap_data import color_map_luts # import colors 
    # the rgb colors
    colors = color_map_luts[color_map]
    x = np.mgrid[0.0:1.0:colors[0].shape[0]*1j]
    # how the values map to the colors
    color_index = (np.interp(cs,x,x)*(colors[0].shape[0]-1)).astype("uint8")
    color_index_list = color_index.tolist()
    name = []
    hused = []
    scale = [(1.0, 1.0, 1.0)]
    # create scale if necessary
    if len(scale[:][:]) < color_index.max(): # generate larger scale
        sc = (scale[0][0], scale[0][1], scale[0][2])
        scale = []
        for i in range(color_index.min(), color_index.max()):
            scale.append(sc)
    # also, allow for multiple halo sizes
    if len(halo_sizes) < color_index.max():
        hs = halo_sizes[0]
        halo_sizes = []
        for i in range(color_index.min(), color_index.max()):
            halo_sizes.append(hs)
    # create sph data into meshes and color them
    for ind in range(color_index.min(), color_index.max()):
        cl = [i for i,j in enumerate(color_index_list) if j == ind]
        print(ind)
        if len(cl) > 0:
            #print("particle name")
            #print(name)
            fname = fname_out + '_' + str(ind)
            name.append('particle_'+fname)
            hused.append(halo_sizes[ind])
            me = bpy.data.meshes.new('particleMesh_'+fname)
            ob = bpy.data.objects.new('particle_'+fname,me)
            ob.location = (0,0,0)
            bpy.context.scene.objects.link(ob)    # Link object to scene
            coords = [(0,0,0)]
            me.from_pydata(coords,[],[])
            ob.location = (0,0,0)
            ob = bpy.data.objects['particle_'+fname] # select right object
            deselect_all()
            ob.select = True
            bpy.context.scene.objects.active=ob
            mat = makeMaterial('particle_'+fname, 
                                       (colors[0][ind],colors[1][ind],colors[2][ind]), 
                                       (1,1,1), 1.0, 1.0, mat_type = 'HALO', halo_size=halo_sizes[ind])
            setMaterial(ob,mat)
            # add in verts
            bpy.ops.object.mode_set(mode='EDIT')  # toggle to edit mode
            bm = bmesh.from_edit_mesh(ob.data)
            # now, find all verts with this color index (ind)
            # move original vertex to actual location
            if hasattr(bm.verts, "ensure_lookup_table"): # to make it work with 2.73
                bm.verts.ensure_lookup_table()
            bm.verts[0].co = (xcoord[cl[0]]*scale[ind][0],ycoord[cl[0]]*scale[ind][1],zcoord[cl[0]]*scale[ind][2])
            print('coords')
            print(xcoord[cl[0]], ycoord[cl[0]], zcoord[cl[0]])
            print(len(cl))
            print(len(xcoord))
            for i in range(1,len(xcoord[cl])):
                bm.verts.new((xcoord[cl[i]]*scale[ind][0],ycoord[cl[i]]*scale[ind][1],zcoord[cl[i]]*scale[ind][2]))
            bmesh.update_edit_mesh(ob.data)
            bpy.ops.object.mode_set(mode='OBJECT')
            #print(ind)
            #print(bpy.data.objects['particle_' + fname].name)
            print(bpy.data.objects['particle_' + fname].location)
    #print("NAME OUT HERE")
    #print(name)
    return name, ds, hused
示例#4
0
 def new_particle_set(self,
                      dfile,
                      particle_num=1,
                      colors=None,
                      halo_sizes=None,
                      scale=(1, 1, 1)):
     # initial file, number of particles, colors array
     import bmesh
     deselect_all()
     location = (0, 0, 0)
     # strip "/" and ".txt"s for names
     xnn2 = 0
     xnn = 0
     # you only want the file name, not all the directory stuff
     while xnn != -1:
         xnn2 = xnn
         xnn = dfile.find('/', xnn + 1)
     fname = dfile[xnn2 + 1:]
     # take out .txt stufftoo
     xnn = fname.find('.txt')
     fname = fname[0:xnn]
     pname = []
     # create different particle types
     for p in range(0, particle_num):
         #print(p)
         num = "%02d" % (p)
         pname.append(fname + 'particle' + num)
         me = bpy.data.meshes.new(fname + 'particleMesh' + num)
         ob = bpy.data.objects.new(fname + 'particle' + num, me)
         ob.location = (0, 0, 0)
         bpy.context.scene.objects.link(ob)  # Link object to scene
         coords = [(0, 0, 0)]
         me.from_pydata(coords, [], [])
         ob.location = (0, 0, 0)
         if colors is not None:
             color = colors[:][p]
             halo_size = halo_sizes[p]
         else:
             print('no color')
             color = (1, 1, 1)
             halo_size = 0.1
         mat = makeMaterial(fname + 'particle' + num,
                            color, (1, 1, 1),
                            1.0,
                            1.0,
                            mat_type='HALO',
                            halo_size=halo_size)
         setMaterial(ob, mat)  # sets everything to material 0 by default
         ob = bpy.data.objects[fname + 'particle' +
                               num]  # select right object
         ob.select = True
         bpy.context.scene.objects.active = ob
     # now, add in different data types
     p2 = -1  # for toggling to object mode when using a different particle
     f = open(dfile, 'r')  # open file for reading
     for i, line in enumerate(f):
         pint = int(p)
         #p = data["p"][i] # get type - o - particle
         linep = line.strip()  # get rid of end line
         data = linep.split(",")  # split into data based on ","'s
         p = float(data[4])
         if p != p2:
             bpy.ops.object.mode_set(mode='OBJECT')  # toggle to edit mode
         num = "%02d" % (p)
         deselect_all()
         ob = bpy.data.objects[fname + 'particle' +
                               num]  # select right object
         ob.select = True
         bpy.context.scene.objects.active = ob
         bpy.ops.object.mode_set(mode='EDIT')  # toggle to edit mode
         bm = bmesh.from_edit_mesh(ob.data)
         if p != p2:  # if first instance - move origional
             if hasattr(bm.verts,
                        "ensure_lookup_table"):  # to make it work with 2.73
                 bm.verts.ensure_lookup_table()
             bm.verts[0].co = (float(data[1]) * scale[pint][0],
                               float(data[2]) * scale[pint][1],
                               float(data[3]) * scale[pint][2])
             p2 = p
         else:
             bm.verts.new((float(data[1]) * scale[pint][0],
                           float(data[2]) * scale[pint][1],
                           float(data[3]) * scale[pint][2]))
     f.close()  # close up the file
     # update all meshes
     for p in range(0, particle_num):
         deselect_all()
         bpy.ops.object.mode_set(mode='OBJECT')  # toggle to edit mode
         num = "%02d" % (p)
         ob = bpy.data.objects[fname + 'particle' +
                               num]  # select right object
         ob.select = True
         bpy.context.scene.objects.active = ob
         bpy.ops.object.mode_set(mode='EDIT')  # toggle to edit mode
         bmesh.update_edit_mesh(ob.data)
     bpy.ops.object.mode_set(mode='OBJECT')  # toggle to edit mode
     return pname
 else:
     delete_object(cube_name)
 cube = bpy.data.objects[cube_name]
 cube.location = (0,0,0)
 if file_type == 'amr':
     cube.location = (0.5, 0.5, 0.5)
 mat_name = mat_name_base + str(i).zfill(3)
 # make a material
 mat = bpy.data.materials.new(mat_name)
 mat.type = 'VOLUME'
 mat.volume.density = 0.0 # lower?
 mat.volume.density_scale = 1.0 # upper?
 mat.volume.scattering = 1.4
 mat.volume.emission = 0.0
 mat.transparency_method = 'Z_TRANSPARENCY'
 setMaterial(bpy.data.objects[cube_name], mat)
 # Create texture 
 mtex = mat.texture_slots.add()
 mat.active_texture_index = 0
 tex_name = tex_name_base + str(i).zfill(3)
 tex = bpy.data.textures.new(tex_name, type = 'POINT_DENSITY')
 mat.active_texture = tex
 tex.use_color_ramp = True
 bpy.data.textures[tex_name].point_density.point_source = 'OBJECT'
 bpy.data.textures[tex_name].point_density.object = bpy.data.objects[particle_name_base + str(i).zfill(3)]
 bpy.data.textures[tex_name].point_density.radius = pc_radius
 mat.texture_slots[0].texture_coords = 'ORCO' # generated coords
 mat.texture_slots[0].mapping = 'CUBE' # map to a cube
 # NO idea
 ts = mat.texture_slots[0]
 ts.use_map_density = True
示例#6
0
    def __init__(self,
                 ds,
                 image_name="ytProjectionImage",
                 axis='z',
                 variable=('gas', 'temperature'),
                 weight_variable=('gas', 'density'),
                 center=[0.0, 0.0, 0.0],
                 width=10.0,
                 units='kpc',
                 color_map='algae',
                 show_annotations=False):
        from yt import ProjectionPlot, OffAxisProjectionPlot
        if (axis != 'z') and (axis != 'y') and (axis != 'x'):
            p = OffAxisProjectionPlot(ds,
                                      axis,
                                      variable,
                                      width=(width, units),
                                      weight_field=weight_variable)
            #plot = p.plots[variable]
            #fig = plot.figure
            #f = BytesIO()
            #vv = yt.write_image(np.log10(p.frb[variable][:,:-1].d),f, cmap_name = color_map)
            p.hide_axes()
            p.hide_colorbar()
            p.set_cmap(variable, color_map)
            p._setup_plots()
            plot = p.plots[variable]
            plot.canvas.draw()
            buff = plot.canvas.tostring_argb()
            ncols, nrows = plot.canvas.get_width_height()
            vv = np.fromstring(buff, dtype=np.uint8).reshape((nrows, ncols, 4),
                                                             order="C")
            if show_annotations:
                p = OffAxisProjectionPlot(ds,
                                          axis,
                                          variable,
                                          width=(width, units),
                                          weight_field=weight_variable)
                p.set_cmap(variable, color_map)
                p._setup_plots()
                plot = p.plots[variable]
                plot.canvas.draw()
                buff2 = plot.canvas.tostring_argb()
                ncols2, nrows2 = plot.canvas.get_width_height()
                vv2 = np.fromstring(buff2, dtype=np.uint8).reshape(
                    (nrows2, ncols2, 4), order="C")
                #plot.canvas.draw()
                #buff = plot.canvas.tostring_argb()
                #ncols2, nrows2 = plot.canvas.get_width_height()
                #vv2 = np.fromstring(buff, dtype=np.uint8).reshape((nrows2, ncols2, 4), order="C")
        else:
            p = ProjectionPlot(ds,
                               axis,
                               variable,
                               center=center,
                               width=(width, units),
                               weight_field=weight_variable)
            #plot = p.plots[variable]
            #fig = plot.figure
            #f = BytesIO()
            #vv = yt.write_image(np.log10(p.frb[variable][:,:-1].d),f, cmap_name = color_map)
            p.hide_axes()
            p.hide_colorbar()
            p.set_cmap(variable, color_map)
            p._setup_plots()
            plot = p.plots[variable]
            plot.canvas.draw()
            buff = plot.canvas.tostring_argb()
            ncols, nrows = plot.canvas.get_width_height()
            vv = np.fromstring(buff, dtype=np.uint8).reshape((nrows, ncols, 4),
                                                             order="C")

            if show_annotations:
                p = ProjectionPlot(ds,
                                   axis,
                                   variable,
                                   center=center,
                                   width=(width, units),
                                   weight_field=weight_variable)
                p.set_cmap(variable, color_map)
                p._setup_plots()
                plot = p.plots[variable]
                plot.canvas.draw()
                buff2 = plot.canvas.tostring_argb()
                ncols2, nrows2 = plot.canvas.get_width_height()
                vv2 = np.fromstring(buff2, dtype=np.uint8).reshape(
                    (nrows2, ncols2, 4), order="C")
                #plot.canvas.draw()
                #buff = plot.canvas.tostring_argb()
                #ncols2, nrows2 = plot.canvas.get_width_height()
                #vv2 = np.fromstring(buff, dtype=np.uint8).reshape((nrows2, ncols2, 4), order="C")

        ncols = vv.shape[1]
        nrows = vv.shape[0]

        # delete if already there
        for im in bpy.data.images:
            if im.name == image_name:
                delete_unused_images(image_name)
                delete_unused_textures(image_name)
                delete_unused_materials(image_name)

        # for annotations
        for im in bpy.data.images:
            if im.name == image_name + '_ann':
                delete_unused_images(image_name + '_ann')
                delete_unused_textures(image_name + '_ann')
                delete_unused_materials(image_name + '_ann')

        # switching a from back to front, and flipping image
        # if also with annotation do a nice one in the domain
        pixels_tmp = np.array(vv)
        for i in range(0, nrows):
            #pixels_tmp[i,:,0] = vv[i,:,0]
            #pixels_tmp[i,:,1] = vv[i,:,1]
            #pixels_tmp[i,:,2] = vv[i,:,2]
            #pixels_tmp[i,:,3] = vv[i,:,3]
            pixels_tmp[i, :, 3] = vv[nrows - 1 - i, :, 0]
            pixels_tmp[i, :, 0] = vv[nrows - 1 - i, :, 1]
            pixels_tmp[i, :, 1] = vv[nrows - 1 - i, :, 2]
            pixels_tmp[i, :, 2] = vv[nrows - 1 - i, :, 3]

        if show_annotations:
            pixels_tmp2 = np.array(vv2)
        if show_annotations:
            for i in range(0, nrows2):
                pixels_tmp2[i, :, 3] = vv2[nrows2 - 1 - i, :, 0]
                pixels_tmp2[i, :, 0] = vv2[nrows2 - 1 - i, :, 1]
                pixels_tmp2[i, :, 1] = vv2[nrows2 - 1 - i, :, 2]
                pixels_tmp2[i, :, 2] = vv2[nrows2 - 1 - i, :, 3]

        # blank image
        image = bpy.data.images.new(image_name, width=ncols, height=nrows)
        if show_annotations:
            image2 = bpy.data.images.new(image_name + '_ann',
                                         width=ncols2,
                                         height=nrows2)

        pixels = pixels_tmp.ravel() / 255.
        #pixels = vv.ravel()/255.
        if show_annotations:
            pixels2 = pixels_tmp2.ravel() / 255.

        image.pixels = pixels
        if show_annotations:
            image2.pixels = pixels2

        # activate the image in the uv editor
        for area in bpy.context.screen.areas:
            if area.type == 'IMAGE_EDITOR':
                if show_annotations:
                    area.spaces.active.image = image2
                else:
                    area.spaces.active.image = image
            elif area.type == 'VIEW_3D':  # make sure material/render view is on
                for space in area.spaces:
                    if space.type == 'VIEW_3D':
                        if (space.viewport_shade != 'RENDERED') and (
                                space.viewport_shade != 'MATERIAL'):
                            space.viewport_shade = 'RENDERED'  # material is too slow

        # also, attach to the projection in the blender 3d window
        # now, set color
        figmat = makeMaterial(image_name, (0, 0, 0), (1, 1, 1), 1.0,
                              0.0)  # no emissivity or transperency for now
        setMaterial(bpy.data.objects[image_name], figmat)
        # also, make shadeless
        bpy.data.materials[image_name].use_shadeless = True

        # Create image texture from image
        cTex = bpy.data.textures.new(image_name, type='IMAGE')
        cTex.image = image
        # Add texture slot for color texture
        mat = bpy.data.materials[image_name]
        mtex = mat.texture_slots.add()
        mtex.texture = cTex
        #mtex.texture_coords = 'UV'
        mtex.texture_coords = 'OBJECT'  # this seems to work better for figures, but certainly needs to be tested
        mtex.use_map_color_diffuse = True
        mtex.use_map_color_emission = True
        mtex.emission_color_factor = 0.5
        mtex.use_map_density = True
        mtex.mapping = 'FLAT'

        # map to object
        mtex.object = bpy.data.objects[image_name]