def exportParticles(context, emitter, psys, oct_t):
	"""Exports a particle system for the specified emitter"""
	octane = context.scene.octane_render
	export_path = bpath.abspath(octane.path)
	pset = psys.settings
	infostr = "Exporting PS '%s' (%s) on emitter '%s'" % (psys.name, pset.type, emitter.name)
	particles = [p for p in psys.particles] if pset.type == 'HAIR' else [p for p in psys.particles if p.alive_state == 'ALIVE']
	
	if pset.render_type == "OBJECT":
		dupli_ob = pset.dupli_object
		if dupli_ob is not None and octane.instances_write_dupli:
			info(infostr + " with %i instances of '%s' objects" % (len(particles), dupli_ob.name))
			filepath = "".join([bpath.abspath(octane.path), dupli_ob.name])
			info("Writing dupli object to file '%s'" % (filepath + ".obj"))
			dupli_world = dupli_ob.matrix_world.copy()
			transl_inv = Matrix.Translation(-dupli_world.translation)
			dupli_ob.matrix_world = transl_inv * dupli_ob.matrix_world
			writeDupliObjects(context, [dupli_ob], filepath)
			dupli_ob.matrix_world = dupli_world
#			
#	elif pset.render_type == "GROUP":
#		duplig = pset.dupli_group
#		if duplig is not None:
#			objects = duplig.objects
#			infostr += " with %i instances from group '%s'" % (len(particles), duplig.name)
#			info(infostr + " {0}".format([o.name for o in objects]))
#			# TODO: separate group scatter per object
	else:
		warning("Invalid PS visualization type '%s'" % pset.render_type)
		return
	if not pset.use_rotation_dupli:
		warning("'Use object rotation' should be on. Rotations wont conform to Blender veiwport")
	
	try:
		fh = open(export_path + psys.name + ".csv", "w")
		for p in particles:
			#if pset.type == 'HAIR' or not p.alive_state == 'DEAD':
			if (pset.type == "HAIR"):
				loc = Matrix.Translation(p.hair_keys[0].co)
				scale = Matrix.Scale(p.size, 4) * Matrix.Scale(pset.hair_length, 4)
			else:
				loc = Matrix.Translation(p.location)
				scale = Matrix.Scale(p.size, 4)
			rot = Quaternion.to_matrix(p.rotation).to_4x4()
			t = loc * rot * scale
			t = emitter.matrix_world * t if pset.type == "HAIR" else t
			t = oct_t[0] * t * oct_t[1]
			writeTransform(t, fh)
		fh.close()
	except IOError as err:
		msg = "IOError during file handling '{0}'".format(err)
		error(msg)
		raise ExportException(msg)
Beispiel #2
0
def findSequenceImages(context):
    scene = context.scene
    images = [[], []]
    
    if scene.cubester_image in bpy.data.images:
        image = bpy.data.images[scene.cubester_image]
        main = image.name.split(".")[0]
        exstention = image.name.split(".")[1]
        
        # first part of name to check against other files
        length = len(main)
        keep_going = True
        for i in range(len(main) - 1, -1, -1):
            if main[i].isdigit() and keep_going:
                length -= 1
            else:
                keep_going = not keep_going
        name = main[0:length]
        
        dir_name = os.path.dirname(path.abspath(image.filepath))
        
        try:
            for file in os.listdir(dir_name):
                if os.path.isfile(os.path.join(dir_name, file)) and file.startswith(name):
                    images[0].append(os.path.join(dir_name, file))
                    images[1].append(file)
        except:
            print("CubeSter: " + dir_name + " directory not found")
        
    return images
def exportDuplis(context, emitter, oct_t):
	"""Exports dupli objects for the specified emitter"""
	info("Exporting dupli objects for '%s'" % emitter.name)
	octane = context.scene.octane_render
	export_path = bpath.abspath(octane.path)
	
	if octane.instances_write_dupli:
		filepath = "".join([export_path, emitter.name, "_objects"])
		info("Writing dupli objects to file '%s'" % (filepath + ".obj"))
		duplis_world = {}
		for c in emitter.children:
			duplis_world[c] = c.matrix_world.copy()
			c.matrix_world = Matrix.Identity(4)
		d_type = emitter.dupli_type
		emitter.dupli_type = 'NONE' 
		writeDupliObjects(context, emitter.children, filepath)
		emitter.dupli_type = d_type
		for k, v in duplis_world.items():
			k.matrix_world = v
	
	emitter.dupli_list_create(context.scene)
	lst = emitter.dupli_list
	if len(lst) == 0: # if not on active layers, dupli list = empty
		return
	try:
		fh = open(export_path + emitter.name + ".csv", "w")
		for duplicate in lst.values():
			t = duplicate.matrix.copy()
			writeTransform(oct_t[0] * t * oct_t[1], fh)
		fh.close()
	except IOError as err:
		msg = "IOError during file handling '{0}'".format(err)
		error(msg)
		raise ExportException(msg)
	emitter.dupli_list_clear()
Beispiel #4
0
def isdir(path):
    if os_path.isdir(path):
        return True
    # could be blender relative
    path = bpy_path.abspath(path)
    if os_path.isdir(path):
        return True
    return False
Beispiel #5
0
    def get_bsdf_dict(self, export_ctx):
        params = {
            "type": "irawan",
            "filename": abspath(self.filename),
            "repeatU": self.repeatU,
            "repeatV": self.repeatV,
            "kd": self.inputs["kd"].get_color_dict(export_ctx),
            "ks": self.inputs["ks"].get_color_dict(export_ctx),
        }

        return params
Beispiel #6
0
    def execute(self, context):
        props = context.scene.cs_properties
        dir_path = Path(abspath(props.image.filepath)).parent
        props.image_sequence.clear()

        image_files = []
        for _, _, files in walk(dir_path):
            for file in files:
                if file.startswith(props.image_base_name):
                    image_files.append(file)

            break  # only get top-level

        image_files.sort()

        for fi in range(props.start_image_index, len(image_files), props.step_image_index):
            file = image_files[fi]
            img = props.image_sequence.add()
            img.filepath = str(dir_path / file)

        return {"FINISHED"}
Beispiel #7
0
    def get_bsdf_dict(self, export_ctx):
        params = {
            "type": "cloth",
            "wiffile": abspath(self.wiffile),
            "specular_strength": self.specular_strength,
            "deltaX": self.deltaX,
            "umax": self.umax,
            "alpha": self.alpha,
            "beta": self.beta,
            "psi": self.psi,
            "utiling": self.utiling,
            "vtiling": self.vtiling,
            "intensity_fineness": self.intensity_fineness,
            "yarnvar_amplitude": self.yarnvar_amplitude,
            "yarnvar_xscale": self.yarnvar_xscale,
            "yarnvar_yscale": self.yarnvar_yscale,
            "yarnvar_persistance": self.yarnvar_persistance,
            "yarnvar_octaves": self.yarnvar_octaves,
            "reflectance": self.inputs["Diffuse Reflectance"].get_color_dict(export_ctx),
        }

        return params
def exportMeshDuplis(context, obj, users, oct_t):
	"""Exports the transforms of Alt+D duplicated objects"""
	octane = context.scene.octane_render
	export_path = bpath.abspath(octane.path)
	csv_filename = export_path + obj.data.name + ".csv"
	info("Saving transforms for '%s' mesh-dupli objects into file '%s' " % (obj.data.name, csv_filename))
	
	try:
		if octane.instances_write_dupli:
			filepath = export_path + obj.data.name
			obj_world = obj.matrix_world.copy()
			obj.matrix_world = Matrix.Identity(4)
			writeDupliObjects(context, [obj], filepath)
			obj.matrix_world = obj_world
		fh = open(csv_filename, "w")
		for o in users:
			t = o.matrix_world.copy()
			writeTransform(oct_t[0] * t * oct_t[1], fh)
		fh.close()
	except IOError as err:
		msg = "IOError during file handling '{0}'".format(err)
		error(msg)
		raise ExportException(msg)
def readSimulationData(simulationFile):
    # Open timing file (output.csv)
    neuronTimingPath = abspath(simulationFile)
    fileName = display_name_from_filepath(simulationFile)
    timingZip = import_model_from_zip(neuronTimingPath)
    
    # read the data into the TIMINGS variable
    global TIMINGS
    TIMINGS = []
    timing_data = timingZip['spikes']

    for row in timing_data:
        if len(row) == 3:
            
            # if start time point is not reached, simply continue
            if (float(row[2]) < bpy.context.scene.pam_anim_animation.startTime):
                continue
            
            # only load data up to the prespecified time point
            if (float(row[2]) < bpy.context.scene.pam_anim_animation.endTime):
                TIMINGS.append((int(row[0]), int(row[1]), float(row[2])))

    # Sort by fire time
    TIMINGS.sort(key = lambda x: x[2])

    global DELAYS
    DELAYS = []
    for i in range(0, len(model.MODEL.connections)):
        try:
            DELAYS.append(timingZip["delay_" + str(i)])
        except:
            print('cannot find file: ' + 'delay_' + str(i) + '.csv')
    
    DELAYS = numpy.array(DELAYS)
    global noAvailableConnections
    noAvailableConnections = len(DELAYS[0][0])
def createMeshFromAudio(scene, verts, faces):
    filepath = scene.cubester_audio_path
    width = scene.cubester_audio_width_blocks
    length = scene.cubester_audio_length_blocks
    offset = scene.cubester_audio_offset
    size_per_hundred = scene.cubester_size_per_hundred_pixels

    size = size_per_hundred / 100

    # create all blocks
    y = -(width / 2) * size
    for r in range(width):
        x = -(length / 2) * size
        for c in range(length):
            createBlock(x, y, size, 1, verts, faces)

            x += size
        y += size

    # create object
    mesh = bpy.data.meshes.new("cubed")
    mesh.from_pydata(verts, [], faces)
    ob = bpy.data.objects.new("cubed", mesh)
    bpy.context.scene.objects.link(ob)
    bpy.context.scene.objects.active = ob
    ob.select = True

    # set keyframe for each object as inital point
    frame = [1 for i in range(int(len(verts) / 8))]
    frames = [frame]

    area = bpy.context.area
    old_type = area.type
    area.type = "GRAPH_EDITOR"

    scene.frame_current = 0

    createFCurves(mesh, frames, 1, "blocks")

    # deselct all fcurves
    fcurves = ob.data.animation_data.action.fcurves.data.fcurves
    for i in fcurves:
        i.select = False

    max = scene.cubester_audio_max_freq
    min = scene.cubester_audio_min_freq

    freq_step = (max - min) / length

    # animate each block with a portion of the frequency
    for c in range(length):

        l = c * freq_step
        h = (c + 1) * freq_step

        for r in range(width):
            pos = c + (r * length)  # block number
            index = pos * 4  # first index for vertex

            # select curves
            for i in range(index, index + 4):
                curve = i * 3 + 2  # fcurve location
                fcurves[curve].select = True

            bpy.ops.graph.sound_bake(filepath=path.abspath(filepath), low=l, high=h)

            # deselect curves
            for i in range(index, index + 4):
                curve = i * 3 + 2  # fcurve location
                fcurves[curve].select = False

    area.type = old_type
    def writeTexture(self, scene, tex):
        name = tex.name

        if name in self.loadedTextures:
            return

        yi = self.yi
        yi.paramsClearAll()

        textureConfigured = False

        if tex.yaf_tex_type == 'BLEND':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "blend")

            switchBlendType = {
                'LINEAR': 'lin',
                'QUADRATIC': 'quad',
                'EASING': 'ease',
                'DIAGONAL': 'diag',
                'SPHERICAL': 'sphere',
                'QUADRATIC_SPHERE': 'halo',
                'RADIAL': 'radial',
            }

            stype = switchBlendType.get(tex.progression, 'lin')  # set blend type for blend texture, default is 'lin'
            yi.paramsSetString("stype", stype)

            textureConfigured = True

        elif tex.yaf_tex_type == 'CLOUDS':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "clouds")

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size

            yi.paramsSetFloat("size", noise_size)

            if tex.noise_type == 'HARD_NOISE':
                hard = True
            else:
                hard = False

            yi.paramsSetBool("hard", hard)
            yi.paramsSetInt("depth", tex.noise_depth)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            textureConfigured = True

        elif tex.yaf_tex_type == 'WOOD':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "wood")

            yi.paramsSetInt("depth", 0)

            turb = 0.0
            noise_size = 0.25
            hard = True

            if tex.wood_type == 'BANDNOISE' or tex.wood_type == 'RINGNOISE':

                turb = tex.turbulence
                noise_size = tex.noise_scale

                if  noise_size > 0:
                    noise_size = 1.0 / noise_size
                if tex.noise_type == 'SOFT_NOISE':
                    hard = False

            yi.paramsSetFloat("turbulence", turb)
            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetBool("hard", hard)

            ts = "bands"

            if tex.wood_type == 'RINGS' or tex.wood_type == 'RINGNOISE':
                ts = "rings"

            yi.paramsSetString("wood_type", ts)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            # shape parameter

            if tex.noise_basis_2 == 'SAW':
                ts = "saw"
            elif tex.noise_basis_2 == 'TRI':
                ts = "tri"
            else:
                ts = "sin"

            yi.paramsSetString("shape", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'MARBLE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "marble")

            yi.paramsSetInt("depth", tex.noise_depth)
            yi.paramsSetFloat("turbulence", tex.turbulence)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size

            if tex.noise_type == 'HARD_NOISE':
                hard = True
            else:
                hard = False

            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetBool("hard", hard)

            sharp = 4.0
            if tex.marble_type == 'SOFT':
                sharp = 2.0
            elif tex.marble_type == 'SHARP':
                sharp = 4.0
            elif tex.marble_type == 'SHARPER':
                sharp = 8.0

            yi.paramsSetFloat("sharpness", sharp)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            if tex.noise_basis_2 == 'SAW':
                ts = "saw"
            elif tex.noise_basis_2 == 'TRI':
                ts = "tri"
            else:
                ts = "sin"

            yi.paramsSetString("shape", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'VORONOI':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "voronoi")

            if tex.color_mode == 'POSITION':
                ts = "col1"
            elif tex.color_mode == 'POSITION_OUTLINE':
                ts = "col2"
            elif tex.color_mode == 'POSITION_OUTLINE_INTENSITY':
                ts = "col3"
            else:
                ts = "int"

            yi.paramsSetString("color_type", ts)

            yi.paramsSetFloat("weight1", tex.weight_1)
            yi.paramsSetFloat("weight2", tex.weight_2)
            yi.paramsSetFloat("weight3", tex.weight_3)
            yi.paramsSetFloat("weight4", tex.weight_4)

            yi.paramsSetFloat("mk_exponent", tex.minkovsky_exponent)
            yi.paramsSetFloat("intensity", tex.noise_intensity)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)

            switchDistMetric = {
                'DISTANCE_SQUARED': 'squared',
                'MANHATTAN': 'manhattan',
                'CHEBYCHEV': 'chebychev',
                'MINKOVSKY_HALF': 'minkovsky_half',
                'MINKOVSKY_FOOUR': 'minkovsky_four',
                'MINKOVSKY': 'minkovsky',
            }

            ts = switchDistMetric.get(tex.distance_metric, 'minkovsky')  # set distance metric for VORONOI Texture, default is 'minkovsky'
            yi.paramsSetString("distance_metric", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'MUSGRAVE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "musgrave")

            switchMusgraveType = {
                'MULTIFRACTAL': 'multifractal',
                'RIDGED_MULTIFRACTAL': 'ridgedmf',
                'HYBRID_MULTIFRACTAL': 'hybridmf',
                'HETERO_TERRAIN': 'heteroterrain',
                'FBM': 'fBm',
                }
            ts = switchMusgraveType.get(tex.musgrave_type, 'multifractal')  # set MusgraveType, default is 'multifractal'

            yi.paramsSetString("musgrave_type", ts)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))
            yi.paramsSetFloat("H", tex.dimension_max)
            yi.paramsSetFloat("lacunarity", tex.lacunarity)
            yi.paramsSetFloat("octaves", tex.octaves)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetFloat("offset", tex.offset)
            yi.paramsSetFloat("intensity", tex.noise_intensity)
            yi.paramsSetFloat("gain", tex.gain)

            textureConfigured = True

        elif tex.yaf_tex_type == 'DISTORTED_NOISE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "distorted_noise")

            yi.paramsSetFloat("distort", tex.distortion)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)

            yi.paramsSetString("noise_type1", noise2string(tex.noise_basis))
            yi.paramsSetString("noise_type2", noise2string(tex.noise_distortion))

            textureConfigured = True

        elif tex.yaf_tex_type == 'IMAGE' and tex.image and tex.image.source in {'FILE', 'GENERATED'}:

            filename = os.path.splitext(os.path.basename(bpy.data.filepath))[0]

            if not any(filename):
                filename = "untitled"
                save_dir = os.path.expanduser("~")
            else:
                save_dir = "//"

            filename = clean_name(filename)
            fileformat = scene.render.image_settings.file_format.lower()
            extract_path = os.path.join(filename, "{:05d}".format(scene.frame_current))

            if tex.image.source == 'GENERATED':
                image_tex = "yaf_baked_image_{0}.{1}".format(clean_name(tex.name), fileformat)
                image_tex = os.path.join(save_dir, extract_path, image_tex)
                image_tex = abspath(image_tex)
                tex.image.save_render(image_tex, scene)
            if tex.image.source == 'FILE':
                if tex.image.packed_file:
                    image_tex = "yaf_extracted_image_{0}.{1}".format(clean_name(tex.name), fileformat)
                    image_tex = os.path.join(save_dir, extract_path, image_tex)
                    image_tex = abspath(image_tex)
                    tex.image.save_render(image_tex, scene)
                else:
                    if tex.image.library is not None:
                        image_tex = abspath(tex.image.filepath, library=tex.image.library)
                    else:
                        image_tex = abspath(tex.image.filepath)
                    if not os.path.exists(image_tex):
                        yi.printError("Exporter: Image texture {0} not found on: {1}".format(tex.name, image_tex))
                        return False

            image_tex = os.path.realpath(image_tex)
            image_tex = os.path.normpath(image_tex)

            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}: {2}".format(name, tex.yaf_tex_type, image_tex))

            yi.paramsSetString("type", "image")
            yi.paramsSetString("filename", image_tex)

            yi.paramsSetBool("use_alpha", tex.yaf_use_alpha)
            yi.paramsSetBool("calc_alpha", tex.use_calculate_alpha)
            yi.paramsSetBool("normalmap", tex.yaf_is_normal_map)
            yi.paramsSetFloat("gamma", scene.gs_gamma_input)

            # repeat
            repeat_x = 1
            repeat_y = 1

            if tex.extension == 'REPEAT':
                repeat_x = tex.repeat_x
                repeat_y = tex.repeat_y

            yi.paramsSetInt("xrepeat", repeat_x)
            yi.paramsSetInt("yrepeat", repeat_y)

            # clipping
            extension = tex.extension
            switchExtension = {
                'EXTEND': 'extend',
                'CLIP': 'clip',
                'CLIP_CUBE': 'clipcube',
                'CHECKER': 'checker',
                }
            clipping = switchExtension.get(extension, 'repeat')  # set default clipping to 'repeat'
            yi.paramsSetString("clipping", clipping)
            if clipping == 'checker':
                yi.paramsSetBool("even_tiles", tex.use_checker_even)
                yi.paramsSetBool("odd_tiles", tex.use_checker_odd)

            # crop min/max
            yi.paramsSetFloat("cropmin_x", tex.crop_min_x)
            yi.paramsSetFloat("cropmin_y", tex.crop_min_y)
            yi.paramsSetFloat("cropmax_x", tex.crop_max_x)
            yi.paramsSetFloat("cropmax_y", tex.crop_max_y)

            yi.paramsSetBool("rot90", tex.use_flip_axis)
            textureConfigured = True

        if textureConfigured:
            yi.createTexture(name)
            self.loadedTextures.add(name)

        return textureConfigured
Beispiel #12
0
    def createLight(self, yi, object, matrix=None):
        # for use Blender properties
        lamp = object.data
        lamp_name = object.name
        
        if matrix is None:
            matrix = object.matrix_world.copy()
        # matrix indexing (row, colums) changed in Blender rev.42816, for explanation see also:
        # http://wiki.blender.org/index.php/User:TrumanBlending/Matrix_Indexing
        pos = matrix.col[3]
        direct = matrix.col[2]
        # up = matrix[1]  /* UNUSED */
        to = pos - direct

        power = lamp.bounty.energy
        color = lamp.color

        if self.preview:
            if lamp_name == "Lamp":
                pos = (-6, -4, 8, 1.0)
                power = 5
            elif lamp_name == "Lamp.001":
                pos = (6, -6, -2, 1.0)
                power = 6
            elif lamp_name == "Lamp.002":
                pos = (-2.9123109, -7.270790733, 4.439187765, 1.0)
                to = (-0.0062182024121284485, 0.6771485209465027, 1.8015732765197754, 1.0)
                power = 5
            elif lamp_name == "Lamp.008":
                lamp.type = "SUN"
                power = 1.0 #0.8

        yi.paramsClearAll()

        yi.printInfo("Exporting Lamp: {0} [{1}]".format(lamp_name, lamp.type))

        if lamp.bounty.create_geometry:
            yi.paramsClearAll()
            yi.paramsSetColor("color", color[0], color[1], color[2])
            yi.paramsSetString("type", "light_mat")
            self.lightMat = self.yi.createMaterial(lamp_name)
            self.yi.paramsClearAll()

        if lamp.type == "POINT":
            yi.paramsSetString("type", "pointlight")
            yi.paramsSetBool("useGeometry", lamp.bounty.create_geometry)
            power = 0.5 * power * power
            #
            if lamp.bounty.use_sphere:
                yi.paramsSetString("type", "spherelight")
                yi.paramsSetInt("samples", lamp.bounty.samples)
                yi.paramsSetFloat("radius", lamp.bounty.sphere_radius)
                # use sphere light attenuation  
                power /= lamp.bounty.sphere_radius * lamp.bounty.sphere_radius
                #
                if lamp.bounty.create_geometry:
                    ID = self.makeSphere(24, 48, pos[0], pos[1], pos[2], lamp.bounty.sphere_radius, self.lightMat)
                    yi.paramsSetInt("object", ID)

        elif lamp.type == "SPOT":
            if self.preview and lamp_name == "Lamp.002":
                angle = 50
            else:
                #-------------------------------------------------------
                # Blender reports the angle of the full cone in radians
                # and we need half of the apperture angle in degrees
                #-------------------------------------------------------
                angle = degrees(lamp.spot_size) * 0.5
            ###
            light_type = "spotlight"
            if lamp.bounty.ies_file !="":
                ies_file = abspath(lamp.bounty.ies_file)
                if not any(ies_file) and not os.path.exists(ies_file):
                    yi.printWarning("IES file not found for {0}".format(lamp_name))
                    return False
                yi.paramsSetString("file", ies_file)
                light_type = "ieslight"
                            
            else:
                yi.paramsSetFloat("cone_angle", angle)
                yi.paramsSetFloat("blend", lamp.spot_blend)            
                yi.paramsSetFloat("shadowFuzzyness", lamp.bounty.shadow_fuzzyness)
                yi.paramsSetBool("photon_only", lamp.bounty.photon_only)
                
            ## commons values
            yi.paramsSetPoint("to", to[0], to[1], to[2])
            yi.paramsSetBool("soft_shadows", lamp.bounty.spot_soft_shadows)
            yi.paramsSetInt("samples", lamp.bounty.samples)
            
            yi.paramsSetString("type", light_type)

        elif lamp.type == "SUN":
            yi.paramsSetString("type", "sunlight")
            yi.paramsSetInt("samples", lamp.bounty.samples)
            yi.paramsSetFloat("angle", lamp.bounty.angle)
            yi.paramsSetPoint("direction", direct[0], direct[1], direct[2])        
        
        elif lamp.type == "HEMI":
            yi.paramsSetString("type", "directional")
            yi.paramsSetPoint("direction", direct[0], direct[1], direct[2])
            yi.paramsSetBool("infinite", lamp.bounty.infinite)
            if not lamp.bounty.infinite:
                yi.paramsSetFloat("radius", lamp.bounty.shadows_size)
                yi.paramsSetPoint("from", pos[0], pos[1], pos[2])
            
        elif lamp.type == "AREA":
            sizeX = lamp.size
            sizeY = lamp.size
            if lamp.shape == 'RECTANGLE':
                sizeY = lamp.size_y
            matrix = object.matrix_world.copy()

            # generate an untransformed rectangle in the XY plane with the light's position
            # as the centerpoint and transform it using its transformation matrix
            point = Vector((-sizeX / 2, -sizeY / 2, 0))
            corner1 = Vector((-sizeX / 2, sizeY / 2, 0))
            corner2 = Vector((sizeX / 2, sizeY / 2, 0))
            corner3 = Vector((sizeX / 2, -sizeY / 2, 0))

            point = matrix * point      # ----------------------------------
            corner1 = matrix * corner1  # use reverse vector multiply order
            corner2 = matrix * corner2  # API changed with rev. 38674
            corner3 = matrix * corner3  # ----------------------------------

            yi.paramsClearAll()
            if lamp.bounty.create_geometry:
                ID = yi.getNextFreeID()
                yi.startGeometry()
                yi.startTriMesh(ID, 4, 2, False, False, 0)

                yi.addVertex(point[0], point[1], point[2])
                yi.addVertex(corner1[0], corner1[1], corner1[2])
                yi.addVertex(corner2[0], corner2[1], corner2[2])
                yi.addVertex(corner3[0], corner3[1], corner3[2])
                yi.addTriangle(0, 1, 2, self.lightMat)
                yi.addTriangle(0, 2, 3, self.lightMat)
                yi.endTriMesh()
                yi.endGeometry()
                yi.paramsSetInt("object", ID)

            yi.paramsSetString("type", "arealight")
            yi.paramsSetInt("samples", lamp.bounty.samples)
            yi.paramsSetPoint("corner", point[0], point[1], point[2])
            yi.paramsSetPoint("point1", corner1[0], corner1[1], corner1[2])
            yi.paramsSetPoint("point2", corner3[0], corner3[1], corner3[2])

        # sunlight and directional light don't use 'from' parameter
        if lamp.type not in {"SUN", "HEMI"}:
            yi.paramsSetPoint("from", pos[0], pos[1], pos[2])
        
        #
        yi.paramsSetColor("color", color[0], color[1], color[2])
        yi.paramsSetFloat("power", power)
        yi.createLight(lamp_name)

        return True
    def execute(self, context):

        print('execute miura')

        scene = context.scene
        sequence_editor = scene.sequence_editor

        active_strip = sequence_editor.active_strip
        target_path = abspath(active_strip.directory)
        processed_dir = join(target_path, clean_name(active_strip.name))
        window_manager = context.window_manager


        makedirs(processed_dir, exist_ok=True)

        elements = active_strip.elements
        frame_offset_start = active_strip.frame_offset_start
        frame_final_start = active_strip.frame_final_start
        frame_final_duration = active_strip.frame_final_duration

        elements_to_process = elements[
            frame_offset_start:frame_final_duration + frame_offset_start]

        window_manager.progress_begin(0, len(elements_to_process))

        module_name = self.module_name

        if module_name in loaded_modules and self.reload_if_loaded:
            module = importlib.reload(loaded_modules.get(module_name))
        else:
            module = importlib.import_module(module_name)

        loaded_modules[module_name] = module

        use_multiview = active_strip.use_multiview

        if use_multiview:
            print('stereo strip\n', active_strip, dir(active_strip))
            print(active_strip)
            print('—' * 10)
            print(dir(active_strip))
            print(active_strip.views_format)
            print(active_strip.stereo_3d_format)
            print(active_strip.stereo_3d_format.display_mode)
            print('^' * 10)

            assert active_strip.views_format == 'STEREO_3D', 'Only STEREO_3D views formatsupported'
            assert active_strip.stereo_3d_format.display_mode == 'TOPBOTTOM', 'Only TOPBOTTOM display mode supported'

        for i, element in enumerate(elements_to_process):

            window_manager.progress_update(i)

            image_path = join(target_path, element.filename)

            print('image_path', image_path)

            orig = imageio.imread(image_path)
            original_file_name = display_name_from_filepath(element.filename)
            process_name = 'hcy_' + original_file_name 

            print('--- cer cebprff', orig, orig.shape)

            processed = module.process_frame(
                orig, frame_final_start + i, process_name, 
                is_topbottom=use_multiview)

            print('--- cbfg cebprff')

            new_file_name = process_name + '.png'
            process_full_path = path.join(processed_dir, new_file_name)

            print('path to save', process_full_path)

            imageio.imsave(process_full_path, processed)

            print('saved image', process_full_path)

            if i == 0:
                new_sequence_name = active_strip.name + '_processed.000'
                print('Creating new image sequence "{}"', new_sequence_name)
                new_sequence = sequence_editor.sequences.new_image(
                    name=new_sequence_name,
                    filepath=relpath(process_full_path),
                    frame_start=frame_final_start,
                    channel=active_strip.channel + 1)
            else:
                new_sequence.elements.append(new_file_name)

        if use_multiview:
            new_sequence.use_multiview = use_multiview
            new_sequence.views_format = 'STEREO_3D'
            new_sequence.stereo_3d_format.display_mode = 'TOPBOTTOM'

        new_sequence.blend_type = 'ALPHA_OVER'

        window_manager.progress_end()
        print('Done!')

        return {'FINISHED'}
Beispiel #14
0
    def writeTexture(self, scene, tex):
        name = tex.name

        if name in self.loadedTextures:
            return

        yi = self.yi
        yi.paramsClearAll()

        textureConfigured = False
        
        yi.paramsSetBool("img_grayscale", tex.yaf_img_grayscale)
        yi.paramsSetFloat("adj_mult_factor_red", tex.factor_red)
        yi.paramsSetFloat("adj_mult_factor_green", tex.factor_green)
        yi.paramsSetFloat("adj_mult_factor_blue", tex.factor_blue)
        yi.paramsSetFloat("adj_intensity", tex.intensity)
        yi.paramsSetFloat("adj_contrast", tex.contrast)
        yi.paramsSetFloat("adj_saturation", tex.saturation)
        yi.paramsSetFloat("adj_hue", math.degrees(tex.yaf_adj_hue))
        yi.paramsSetFloat("trilinear_level_bias", tex.yaf_trilinear_level_bias)
        yi.paramsSetFloat("ewa_max_anisotropy", tex.yaf_ewa_max_anisotropy)
        yi.paramsSetBool("adj_clamp", tex.use_clamp)

        if tex.use_color_ramp:
            yi.paramsSetBool("use_color_ramp", tex.use_color_ramp)
            yi.paramsSetString("ramp_color_mode", tex.color_ramp.color_mode)
            yi.paramsSetString("ramp_hue_interpolation", tex.color_ramp.hue_interpolation)
            yi.paramsSetString("ramp_interpolation", tex.color_ramp.interpolation)
            i = 0
            for item in tex.color_ramp.elements:
                yi.paramsSetColor("ramp_item_%x_color" % i, item.color[0], item.color[1], item.color[2], item.color[3])
                yi.paramsSetFloat("ramp_item_%x_alpha" % i, item.alpha)
                yi.paramsSetFloat("ramp_item_%x_position" % i, item.position)
                i += 1
            yi.paramsSetInt("ramp_num_items", i)
        
        if tex.yaf_tex_type == 'BLEND':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "blend")

            switchBlendType = {
                'LINEAR': 'lin',
                'QUADRATIC': 'quad',
                'EASING': 'ease',
                'DIAGONAL': 'diag',
                'SPHERICAL': 'sphere',
                'QUADRATIC_SPHERE': 'halo',
                'RADIAL': 'radial',
            }

            stype = switchBlendType.get(tex.progression, 'lin')  # set blend type for blend texture, default is 'lin'
            yi.paramsSetString("stype", stype)
            
            if tex.use_flip_axis == "HORIZONTAL":
                yi.paramsSetBool("use_flip_axis", False)
            if tex.use_flip_axis == "VERTICAL":
                yi.paramsSetBool("use_flip_axis", True)
                
            textureConfigured = True

        elif tex.yaf_tex_type == 'CLOUDS':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "clouds")

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size

            yi.paramsSetFloat("size", noise_size)

            if tex.noise_type == 'HARD_NOISE':
                hard = True
            else:
                hard = False

            yi.paramsSetBool("hard", hard)
            yi.paramsSetInt("depth", tex.noise_depth)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            textureConfigured = True

        elif tex.yaf_tex_type == 'WOOD':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "wood")

            yi.paramsSetInt("depth", 0)

            turb = 0.0
            noise_size = 0.25
            hard = True

            if tex.wood_type == 'BANDNOISE' or tex.wood_type == 'RINGNOISE':

                turb = tex.turbulence
                noise_size = tex.noise_scale

                if  noise_size > 0:
                    noise_size = 1.0 / noise_size
                if tex.noise_type == 'SOFT_NOISE':
                    hard = False

            yi.paramsSetFloat("turbulence", turb)
            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetBool("hard", hard)

            ts = "bands"

            if tex.wood_type == 'RINGS' or tex.wood_type == 'RINGNOISE':
                ts = "rings"

            yi.paramsSetString("wood_type", ts)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            # shape parameter

            if tex.noise_basis_2 == 'SAW':
                ts = "saw"
            elif tex.noise_basis_2 == 'TRI':
                ts = "tri"
            else:
                ts = "sin"

            yi.paramsSetString("shape", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'MARBLE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "marble")

            yi.paramsSetInt("depth", tex.noise_depth)
            yi.paramsSetFloat("turbulence", tex.turbulence)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size

            if tex.noise_type == 'HARD_NOISE':
                hard = True
            else:
                hard = False

            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetBool("hard", hard)

            sharp = 4.0
            if tex.marble_type == 'SOFT':
                sharp = 2.0
            elif tex.marble_type == 'SHARP':
                sharp = 4.0
            elif tex.marble_type == 'SHARPER':
                sharp = 8.0

            yi.paramsSetFloat("sharpness", sharp)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            if tex.noise_basis_2 == 'SAW':
                ts = "saw"
            elif tex.noise_basis_2 == 'TRI':
                ts = "tri"
            else:
                ts = "sin"

            yi.paramsSetString("shape", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'VORONOI':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "voronoi")

            if tex.color_mode == 'POSITION':
                ts = "col1"
            elif tex.color_mode == 'POSITION_OUTLINE':
                ts = "col2"
            elif tex.color_mode == 'POSITION_OUTLINE_INTENSITY':
                ts = "col3"
            else:
                ts = "int"

            yi.paramsSetString("color_type", ts)

            yi.paramsSetFloat("weight1", tex.weight_1)
            yi.paramsSetFloat("weight2", tex.weight_2)
            yi.paramsSetFloat("weight3", tex.weight_3)
            yi.paramsSetFloat("weight4", tex.weight_4)

            yi.paramsSetFloat("mk_exponent", tex.minkovsky_exponent)
            yi.paramsSetFloat("intensity", tex.noise_intensity)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)

            switchDistMetric = {
                'DISTANCE_SQUARED': 'squared',
                'MANHATTAN': 'manhattan',
                'CHEBYCHEV': 'chebychev',
                'MINKOVSKY_HALF': 'minkovsky_half',
                'MINKOVSKY_FOOUR': 'minkovsky_four',
                'MINKOVSKY': 'minkovsky',
            }

            ts = switchDistMetric.get(tex.distance_metric, 'minkovsky')  # set distance metric for VORONOI Texture, default is 'minkovsky'
            yi.paramsSetString("distance_metric", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'MUSGRAVE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "musgrave")

            switchMusgraveType = {
                'MULTIFRACTAL': 'multifractal',
                'RIDGED_MULTIFRACTAL': 'ridgedmf',
                'HYBRID_MULTIFRACTAL': 'hybridmf',
                'HETERO_TERRAIN': 'heteroterrain',
                'FBM': 'fBm',
                }
            ts = switchMusgraveType.get(tex.musgrave_type, 'multifractal')  # set MusgraveType, default is 'multifractal'

            yi.paramsSetString("musgrave_type", ts)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))
            yi.paramsSetFloat("H", tex.dimension_max)
            yi.paramsSetFloat("lacunarity", tex.lacunarity)
            yi.paramsSetFloat("octaves", tex.octaves)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetFloat("offset", tex.offset)
            yi.paramsSetFloat("intensity", tex.noise_intensity)
            yi.paramsSetFloat("gain", tex.gain)

            textureConfigured = True

        elif tex.yaf_tex_type == 'DISTORTED_NOISE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "distorted_noise")

            yi.paramsSetFloat("distort", tex.distortion)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)

            yi.paramsSetString("noise_type1", noise2string(tex.noise_basis))
            yi.paramsSetString("noise_type2", noise2string(tex.noise_distortion))

            textureConfigured = True

        elif tex.yaf_tex_type == 'IMAGE' and tex.image and tex.image.source in {'FILE', 'SEQUENCE', 'GENERATED'}:

            filename = os.path.splitext(os.path.basename(bpy.data.filepath))[0]

            if not any(filename):
                filename = "untitled"
                save_dir = os.path.expanduser("~")
            else:
                save_dir = "//"

            filename = clean_name(filename)
            fileformat = scene.render.image_settings.file_format.lower()
            extract_path = os.path.join(filename, "{:05d}".format(scene.frame_current))

            if tex.image.source == 'GENERATED':
                image_tex = "yaf_baked_image_{0}.{1}".format(clean_name(tex.name), fileformat)
                image_tex = os.path.join(save_dir, extract_path, image_tex)
                image_tex = abspath(image_tex)
                tex.image.save_render(image_tex, scene)
            if tex.image.source == 'FILE':
                if tex.image.packed_file:
                    image_tex = "yaf_extracted_image_{0}.{1}".format(clean_name(tex.name), fileformat)
                    image_tex = os.path.join(save_dir, extract_path, image_tex)
                    image_tex = abspath(image_tex)
                    tex.image.save_render(image_tex, scene)
                else:
                    if tex.image.library is not None:
                        image_tex = abspath(tex.image.filepath, library=tex.image.library)
                    else:
                        image_tex = abspath(tex.image.filepath)
                    if not os.path.exists(image_tex):
                        yi.printError("Exporter: Image texture {0} not found on: {1}".format(tex.name, image_tex))
                        return False
            if tex.image.source == 'SEQUENCE':
                if tex.image.packed_file:
                    image_tex = "yaf_extracted_image_{0}.{1}".format(clean_name(tex.name), fileformat)
                    image_tex = os.path.join(save_dir, extract_path, image_tex)
                    image_tex = abspath(image_tex)
                    tex.image.save_render(image_tex, scene)
                else:
                    #Try to figure out the correct file name depending on the frame, guessing the calculations done by Blender
                    if tex.image_user.use_cyclic:
                        image_number = scene.frame_current - tex.image_user.frame_start
                        if image_number < 0:
                            image_number += (divmod(-1 * image_number, tex.image_user.frame_duration)[0]+1) * tex.image_user.frame_duration

                        image_number = (image_number % tex.image_user.frame_duration) + tex.image_user.frame_offset + 1

                    else:
                        image_number = scene.frame_current - (tex.image_user.frame_start - 1) + tex.image_user.frame_offset
                        if image_number < tex.image_user.frame_start:
                            image_number = tex.image_user.frame_start
                        elif image_number > (tex.image_user.frame_duration + tex.image_user.frame_offset):
                            image_number = (tex.image_user.frame_duration + tex.image_user.frame_offset)

                    tex_image_filepath = abspath(tex.image.filepath)
                    tex_image_filepath_splitext = os.path.splitext(tex_image_filepath)
                    tex_image_filepath_searchnumber = re.search(r'\d+$', tex_image_filepath_splitext[0])
                    tex_image_filepath_base = tex_image_filepath[0:tex_image_filepath_searchnumber.span()[0]] if tex_image_filepath_searchnumber else tex_image_filepath_splitext[0]
                    tex_image_filepath_number = tex_image_filepath_searchnumber.group() if tex_image_filepath_searchnumber else None
                    tex_image_filepath_number_numdigits = len(tex_image_filepath_number) if tex_image_filepath_number else 0
                    tex_image_filepath_ext = tex_image_filepath_splitext[1]
                    if tex_image_filepath_number is not None:
                        tex_image_filepath_sequence = tex_image_filepath_base + str(image_number).zfill(tex_image_filepath_number_numdigits) + tex_image_filepath_ext
                    else:
                        tex_image_filepath_sequence = tex_image_filepath_base + str(image_number) + tex_image_filepath_ext

                    if tex.image.library is not None:
                        image_tex = abspath(tex_image_filepath_sequence, library=tex.image.library)
                    else:
                        image_tex = abspath(tex_image_filepath_sequence)
                    if not os.path.exists(image_tex):
                        yi.printError("Exporter: Image texture {0} not found on: {1}".format(tex.name, image_tex))
                        return False

            image_tex = os.path.realpath(image_tex)
            image_tex = os.path.normpath(image_tex)

            yi.paramsSetString("type", "image")
            yi.paramsSetString("filename", image_tex)

            yi.paramsSetBool("use_alpha", tex.yaf_use_alpha)
            yi.paramsSetBool("calc_alpha", tex.use_calculate_alpha)
            yi.paramsSetBool("normalmap", tex.yaf_is_normal_map)
            yi.paramsSetString("fileformat", fileformat.upper())
            
            texture_color_space = "sRGB"
            texture_gamma = 1.0

            if tex.image.colorspace_settings.name == "sRGB" or tex.image.colorspace_settings.name == "VD16":
                texture_color_space = "sRGB"
                
            elif tex.image.colorspace_settings.name == "XYZ":
                texture_color_space = "XYZ"
                
            elif tex.image.colorspace_settings.name == "Linear" or tex.image.colorspace_settings.name == "Linear ACES" or tex.image.colorspace_settings.name == "Non-Color":
                texture_color_space = "LinearRGB"
                
            elif tex.image.colorspace_settings.name == "Raw":
                texture_color_space = "Raw_Manual_Gamma"
                texture_gamma = tex.yaf_gamma_input  #We only use the selected gamma if the color space is set to "Raw"
                
            yi.paramsSetString("color_space", texture_color_space)
            yi.paramsSetFloat("gamma", texture_gamma)

            if tex.yaf_tex_optimization == "default":
                texture_optimization = scene.gs_tex_optimization
            else:
                texture_optimization = tex.yaf_tex_optimization

            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}: {2}. Texture Color Space: '{3}', gamma={4}. Texture optimization='{5}'".format(name, tex.yaf_tex_type, image_tex, texture_color_space, texture_gamma, texture_optimization))

            yi.paramsSetString("interpolate", tex.yaf_tex_interpolate)
            yi.paramsSetString("texture_optimization", texture_optimization)

            # repeat
            repeat_x = 1
            repeat_y = 1

            if tex.extension == 'REPEAT':
                repeat_x = tex.repeat_x
                repeat_y = tex.repeat_y

            yi.paramsSetInt("xrepeat", repeat_x)
            yi.paramsSetInt("yrepeat", repeat_y)

            # clipping
            extension = tex.extension
            switchExtension = {
                'EXTEND': 'extend',
                'CLIP': 'clip',
                'CLIP_CUBE': 'clipcube',
                'CHECKER': 'checker',
                }
            clipping = switchExtension.get(extension, 'repeat')  # set default clipping to 'repeat'
            yi.paramsSetString("clipping", clipping)
            if clipping == 'checker':
                yi.paramsSetBool("even_tiles", tex.use_checker_even)
                yi.paramsSetBool("odd_tiles", tex.use_checker_odd)

            # crop min/max
            yi.paramsSetFloat("cropmin_x", tex.crop_min_x)
            yi.paramsSetFloat("cropmin_y", tex.crop_min_y)
            yi.paramsSetFloat("cropmax_x", tex.crop_max_x)
            yi.paramsSetFloat("cropmax_y", tex.crop_max_y)

            yi.paramsSetBool("rot90", tex.use_flip_axis)
            
            yi.paramsSetBool("mirror_x", tex.use_mirror_x)
            yi.paramsSetBool("mirror_y", tex.use_mirror_y)
            
            textureConfigured = True

        if textureConfigured:
            yi.createTexture(name)
            self.loadedTextures.add(name)

        return textureConfigured
Beispiel #15
0
def export(filename):

    scn = bpy.context.scene
    basename = filename.split("\\")[-1].split("/")[-1]
    fs = open(filename, "wb")

    def is_iterable(ob):
        return not is_instance(ob, str) and isinstance(ob, Iterable)

    # Appends d to s according to the .EAR file format specification
    def pack(d, s=b""):
        if type(d) == type(0):
            s += b"int4"
            s += struct.pack("i", d)
        elif type(d) == type(0.0):
            s += b"flt4"
            s += struct.pack("f", d)
        elif type(d) == type([]) and len(d) > 1 and len(d) < 10 and type(d[0]) == type(0.0):
            s += ("vec%d" % len(d)).encode("ascii")
            for f in d:
                s += pack(f)
        elif type(d) == type([]) and type(d[0]) == type([]):
            s += b"tri "
            for f in d:
                s += pack(f)
        elif type(d) == type(""):
            e = d.encode("utf8")
            a = d + "\x00" * (4 - len(e) % 4)
            s += b"str "
            s += a.encode("utf8")
        elif type(d) == type(b""):
            return d
        else:
            raise ValueError(str(type(d)))
        return s

    # Writes a variable to the output stream
    def write(d):
        fs.write(pack(d))

    # Serializes the block with header h and arguments p
    def packblock(h, p):
        ret = b""
        if type(h) == type(b""):
            ret += h
        else:
            ret += str(h).encode("ascii")
        b = b""
        for x in p:
            b += pack(x)
        ret += struct.pack("i", len(b))
        ret += b
        return ret

    # Writes the block with header h and arguments p to the output stream
    def writeblock(h, p):
        if type(h) == type(b""):
            write(h)
        else:
            write(str(h).encode("ascii"))
        b = b""
        for x in p:
            b += pack(x)
        write(struct.pack("i", len(b)))
        write(b)

    # Writes header and version identifier
    write(b".EAR")
    writeblock("VRSN", [0])

    # Writes the materials in the blender file
    for mat in bpy.data.materials:
        # First see if the material is used by any sound reflecting meshes
        if not len([o for o in bpy.context.scene.objects if o.is_surface and mat.name in o.data.materials]):
            continue
        if mat.aud_preset != "0":
            bl = [mat.name]
            bl.extend(y for x in materials.lookup(mat.aud_preset) for y in x)
        else:
            bl = [mat.name, mat.refl_low, mat.refl_mid, mat.refl_high]
            bl.extend((mat.refr_low, mat.refr_mid, mat.refr_high))
            bl.extend((mat.exp_low, mat.exp_mid, mat.exp_high))
        writeblock("MAT ", bl)

    # Writes the settings block
    settings = [
        "debug",
        0,
        "absorption",
        [scn.ab_low, scn.ab_mid, scn.ab_high],
        "drylevel",
        scn.drylevel,
        "samples",
        10 ** scn.num_samples,
        "maxthreads",
        scn.max_threads,
    ]
    debug_dir = normpath(abspath(scn.debug_dir))
    if debug_dir != "." and os.path.exists(debug_dir):
        settings.extend(["debugdir", debug_dir])
    writeblock("SET ", settings)

    # A function to determines whether ob has suitable fcurves or its parent object
    def is_animated(ob):
        return (
            ob.animation_data
            and ob.animation_data.action
            and len(ob.animation_data.action.fcurves)
            or (ob.parent and is_animated(ob.parent))
        )

    # A check whether any object that is being exported is animated
    # If one of them is animated all other objects are threated as
    # animated as well.
    contains_animation = (
        len(
            [
                o
                for o in scn.objects
                if o.type == "EMPTY" and (o.is_storyboard or o.is_listener or o.is_emitter) and is_animated(o)
            ]
        )
        > 0
    )

    # Write the global key-frame offsets to the file
    if contains_animation:
        anim_keys = []
        for fr in range(scn.frame_start, scn.frame_end + 1, scn.frame_step):
            anim_keys.append((fr - 1) / scn.render.fps)
        writeblock("KEYS", anim_keys)

    # Write the equalizer frequencies to the file
    writeblock("FREQ", [scn.freq1, scn.freq2, scn.freq3])

    # Keep track of the number of sounds and recorders
    num_sounds = 0
    num_recorders = 0
    recorder_names = []

    old_frame = scn.frame_current

    for ob in scn.objects:
        if ob.type == "MESH":
            # Mesh objects can either be a reflecting surface or an emitter
            if ob.is_surface or ob.is_emitter:
                # Transform the vertex coordinates to world space
                ve = [list(ob.matrix_world * v.co) for v in ob.data.vertices]
                # In case of reflecting surfaces meshes need to be separated by material index
                mi_to_fa = {}
                mis = range(len(ob.data.materials))
                # Use the new tesselated faces api if available (2.63 and onwards)
                if hasattr(ob.data, "tessfaces"):
                    ob.data.update(calc_tessface=True)
                    faces = ob.data.tessfaces
                else:
                    faces = ob.data.faces
                for f in faces:
                    mi = f.material_index
                    if mi in mis:
                        fvs = f.vertices
                        if len(fvs) == 4:
                            vs = [[fvs[0], fvs[1], fvs[2]], [fvs[0], fvs[2], fvs[3]]]
                        else:
                            vs = [fvs]
                        fa = mi_to_fa.get(mi, [])
                        for f in vs:
                            fa.append([ve[i] for i in f])
                        mi_to_fa[mi] = fa
                    else:
                        print("Warning no material assigned to slot %d for object %s" % (mi, ob.name))
                if ob.is_emitter:
                    # In case of an emitter material indices are not important so the dictionary is flattened
                    mesh_block = packblock("mesh", sum([fa for mi, fa in mi_to_fa.items()], []))
                    block_id = "3src" if ob.is_tripleband else "ssrc"
                    fn = "//%s.sine.wav" % (ob.name) if ob.is_sine else ob.filename
                    # The file is a computer generated sine, generate it and write to file
                    if ob.is_sine:
                        sine_args = [
                            normpath(abspath(fn)),
                            ob.sine_attack,
                            ob.sine_attack_exponent,
                            ob.sine_decay,
                            ob.sine_decay_exponent,
                        ]
                        if ob.sine_harmonics:
                            sine_args.extend(
                                (ob.sine_base_frequency, [(x.harmonic, x.amplitude) for x in ob.sine_frequencies])
                            )
                            sines.write_compound_overtones(*sine_args)
                        else:
                            sine_args.append([(x.frequency, x.amplitude) for x in ob.sine_frequencies])
                            sines.write_compound(*sine_args)
                    block_args = [normpath(abspath(fn))]
                    if ob.is_tripleband:
                        block_args.extend((normpath(abspath(ob.filename2)), normpath(abspath(ob.filename3))))
                    block_args.extend((mesh_block, ob.gain))
                    writeblock(block_id, block_args)
                elif ob.is_surface:
                    for mi, fa in mi_to_fa.items():
                        writeblock("MESH", [ob.data.materials[mi].name] + fa)
        elif ob.type == "EMPTY":
            if contains_animation:
                locs = []
                for fr in range(scn.frame_start, scn.frame_end + 1, scn.frame_step):
                    scn.frame_set(fr)
                    locs.append(list(ob.location))
                loc = packblock("anim", locs)
            else:
                loc = list(ob.location)
            if ob.is_storyboard:
                generated_file, step_locs = storyboard.generate(ob, ob.step_size)
                if generated_file:
                    new_locs = []
                    step_index = 0
                    for fr in range(scn.frame_start, scn.frame_end + 1, scn.frame_step):
                        scn.frame_set(fr)
                        step_loc = list(ob.location)
                        step_loc[2] = step_locs[step_index][2]
                        new_locs.append(step_loc)
                        step_index += 1
                    new_loc = packblock("anim", new_locs)
                    writeblock("SSRC", [normpath(generated_file), new_loc, ob.gain])
                    num_sounds += 1
            if ob.is_emitter:
                block_id = "3SRC" if ob.is_tripleband else "SSRC"
                fn = "//%s.sine.wav" % (ob.name) if ob.is_sine else ob.filename
                if ob.is_sine:
                    sine_args = [
                        normpath(abspath(fn)),
                        ob.sine_attack,
                        ob.sine_attack_exponent,
                        ob.sine_decay,
                        ob.sine_decay_exponent,
                    ]
                    if ob.sine_harmonics:
                        sine_args.extend(
                            (ob.sine_base_frequency, [(x.harmonic, x.amplitude) for x in ob.sine_frequencies])
                        )
                        sines.write_compound_overtones(*sine_args)
                    else:
                        sine_args.append([(x.frequency, x.amplitude) for x in ob.sine_frequencies])
                        sines.write_compound(*sine_args)
                block_args = [normpath(abspath(fn))]
                if ob.is_tripleband:
                    block_args.extend((normpath(abspath(ob.filename2)), normpath(abspath(ob.filename3))))
                block_args.extend((loc, ob.gain, ob.sound_offset))
                writeblock(block_id, block_args)
                num_sounds += 1
            if ob.is_listener:
                channels = 2 if ob.is_stereo else 1
                li = [normpath(abspath(ob.filename)), 35.0, loc]
                if ob.is_stereo:
                    if contains_animation:
                        ears = []
                        for fr in range(scn.frame_start, scn.frame_end + 1, scn.frame_step):
                            scn.frame_set(fr)
                            mat = ob.matrix_world.to_3x3()
                            vec = mat * mathutils.Vector((-1, 0, 0))
                            vec.normalize()
                            ears.append(list(vec))
                        ear = packblock("anim", ears)
                    else:
                        mat = ob.matrix_world.to_3x3()
                        vec = mat * mathutils.Vector((-1, 0, 0))
                        vec.normalize()
                        ear = list(vec)
                    li.append(ear)
                    li.append(ob.head_size)
                    li.append([ob.head_ab_low, ob.head_ab_mid, ob.head_ab_high])
                writeblock("OUT%d" % channels, li)
                num_recorders += 1
                recorder_names.append(ob.name)
    fs.close()

    scn.frame_set(old_frame)
Beispiel #16
0
    def setEnvironment(self, scene):
        yi = self.yi
        
        # init..
        world = bpy.context.scene.world
        bg_type = "constant"
        bgColor = (0.0, 0.0, 0.0)
        useIBL = False
        iblSamples = 16
        bgPower = 1 
        
        if scene.world:
            # exporter properties
            world = scene.world.bounty
            bg_type = world.bg_type
            bgColor = world.bg_single_color
            useIBL = world.bg_use_ibl
            iblSamples = world.bg_ibl_samples
            bgPower = world.bg_power
            with_caustic = world.bg_with_caustic
            with_diffuse = world.bg_with_diffuse
            
        yi.paramsClearAll()

        if bg_type == 'textureback':
            #
            worldTexture = None
            if scene.world.active_texture is not None:
                worldTexture = scene.world.active_texture
                
                self.yi.printInfo("World Texture, name: {0}".format(worldTexture.name))

                if worldTexture.type == "IMAGE" and (worldTexture.image is not None):
                    #
                    image_file = ''
                    if worldTexture.image.packed_file:
                        # is packed but too exists on disk..
                        if not os.path.exists(abspath(worldTexture.image.filepath)):
                            worldTexture.image.unpack(method='WRITE_LOCAL')
                            yi.printInfo("Image file unpacked to: {0}".format(abspath(worldTexture.image.filepath)))
                        image_file = abspath(worldTexture.image.filepath)
                            
                    else:
                        # not packed..
                        image_file = abspath(worldTexture.image.filepath)
                    #
                    image_file = realpath(image_file)
                    image_file = normpath(image_file)                        
                    
                    yi.paramsSetString("filename", image_file)
                    
                    # image interpolate
                    yi.paramsSetString("interpolate", worldTexture.interpolation_type)
                    yi.paramsSetString("type", "image")
                    yi.createTexture("world_texture")

                    # Background settings..
                    yi.paramsClearAll()
                    #
                    worldMappingCoord = "angular"
                    if world.bg_mapping_type == "SPHERE":
                        worldMappingCoord = "spherical"
                        
                    yi.paramsSetString("mapping", worldMappingCoord)                    
                        
                    yi.paramsSetString("type", "textureback")
                    yi.paramsSetString("texture", "world_texture")
                    yi.paramsSetBool("ibl", world.bg_use_ibl)
                    yi.paramsSetBool("with_caustic", world.bg_with_caustic)
                    yi.paramsSetBool("with_diffuse", world.bg_with_diffuse)
                    yi.paramsSetInt("ibl_samples", world.bg_ibl_samples)
                    yi.paramsSetFloat("power", world.bg_power)
                    yi.paramsSetFloat("rotation", world.bg_rotation)
                else:
                    self.yi.printWarning("World Texture, name: {0} is not valid format".format(worldTexture.name))
            else:
                self.yi.printWarning('texture background not found')
            
        elif bg_type == 'gradientback':
            c = world.bg_horizon_color
            yi.paramsSetColor("horizon_color", c[0], c[1], c[2])

            c = world.bg_zenith_color
            yi.paramsSetColor("zenith_color", c[0], c[1], c[2])

            c = world.bg_horizon_ground_color
            yi.paramsSetColor("horizon_ground_color", c[0], c[1], c[2])

            c = world.bg_zenith_ground_color
            yi.paramsSetColor("zenith_ground_color", c[0], c[1], c[2])

            yi.paramsSetFloat("power", world.bg_power)
            yi.paramsSetBool("ibl", world.bg_use_ibl)
            yi.paramsSetInt("ibl_samples", world.bg_ibl_samples)

        elif bg_type in {'sunsky', "darksky"}:
            #
            if bg_type == 'sunksky':
                yi.paramsSetFloat("turbidity", world.bg_turbidity)
            
            #-------------------------
            # specific sunsky2 values
            #-------------------------            
            if bg_type == 'darksky':
                yi.paramsSetFloat("turbidity", world.bg_ds_turbidity)
                yi.paramsSetFloat("altitude", world.bg_dsaltitude)
                yi.paramsSetFloat("bright", world.bg_dsbright)
                yi.paramsSetBool("night", world.bg_dsnight)
                yi.paramsSetFloat("exposure", world.bg_exposure)
                yi.paramsSetString("color_space", world.bg_color_space)
                if world.bg_background_light:
                    yi.paramsSetBool("with_caustic", world.bg_with_caustic)
                    yi.paramsSetBool("with_diffuse", world.bg_with_diffuse)
            #---------------
            # common values
            #---------------
            f = world.bg_from
            yi.paramsSetPoint("from", f[0], f[1], f[2])
            yi.paramsSetFloat("a_var", world.bg_a_var)
            yi.paramsSetFloat("b_var", world.bg_b_var)
            yi.paramsSetFloat("c_var", world.bg_c_var)
            yi.paramsSetFloat("d_var", world.bg_d_var)
            yi.paramsSetFloat("e_var", world.bg_e_var)            
            yi.paramsSetBool("add_sun", world.bg_add_sun)
            yi.paramsSetFloat("sun_power", world.bg_sun_power)
            yi.paramsSetBool("background_light", world.bg_background_light)
            yi.paramsSetFloat("power", world.bg_power)            
            yi.paramsSetInt("light_samples", world.bg_light_samples)           

        else:
            yi.paramsSetColor("color", bgColor[0], bgColor[1], bgColor[2])
            yi.paramsSetBool("ibl", useIBL)
            yi.paramsSetInt("ibl_samples", iblSamples)
            yi.paramsSetFloat("power", bgPower)
        #
        yi.paramsSetString("type", bg_type)
        yi.createBackground("world_background")
        self.yi.printInfo("Exporting World, type: {0}".format(bg_type))
        
        return True
Beispiel #17
0
def get_exec_path():
    scn = bpy.context.scene
    path = normpath(abspath(scn.ear_exec_path))
    return path if os.path.isfile(path) and os.access(path, os.X_OK) else "EAR"
Beispiel #18
0
def createMeshFromAudio(scene, verts, faces):
    audio_filepath = scene.cubester_audio_path
    width = scene.cubester_audio_width_blocks
    length = scene.cubester_audio_length_blocks
    size_per_hundred = scene.cubester_size_per_hundred_pixels
    
    size = size_per_hundred / 100   
    
    # create all blocks
    y = -(width / 2) * size + (size / 2)
    for r in range(width):        
        x = -(length / 2) * size + (size / 2)
        for c in range(length):
            createBlock(x, y, size / 2, 1, verts, faces)
            
            x += size            
        y += size
        
    # create object   
    mesh = bpy.data.meshes.new("cubed")
    mesh.from_pydata(verts, [], faces)
    ob = bpy.data.objects.new("cubed", mesh)
    bpy.context.scene.objects.link(ob)
    bpy.context.scene.objects.active = ob
    ob.select = True
        
    # inital vertex colors
    if scene.cubester_materials == "image":
        picture = bpy.data.images[scene.cubester_color_image]
        pixels = list(picture.pixels)
        vert_colors = []
        
        skip_y = int(picture.size[1] / width)
        skip_x = int(picture.size[0] / length)
        
        for row in range(0, picture.size[1], skip_y + 1): 
            # go through each column, step by appropriate amount
            for column in range(0, picture.size[0] * 4, 4 + skip_x * 4):   
                r, g, b, a = getPixelValues(picture, pixels, row, column)
                vert_colors += [(r, g, b) for i in range(24)]
                
        bpy.ops.mesh.vertex_color_add()        
        i = 0
        for c in ob.data.vertex_colors[0].data:
            c.color = vert_colors[i]
            i += 1
                 
        # image squence handling
        if scene.cubester_load_type == "multiple":            
            images = findSequenceImages(bpy.context)
                        
            frames_vert_colors = []
            
            if len(images[0]) > scene.cubester_max_images:
                max = scene.cubester_max_images + 1
            else:
                max = len(images[0])            
            
            # goes through and for each image for each block finds new height
            for image_index in range(0, max, scene.cubester_skip_images):
                filepath = images[0][image_index]
                name = images[1][image_index]                                
                picture = fetchImage(name, filepath)
                pixels = list(picture.pixels)
                
                frame_colors = []               
                
                for row in range(0, picture.size[1], skip_y + 1):        
                    for column in range(0, picture.size[0] * 4, 4 + skip_x * 4): 
                        r, g, b, a = getPixelValues(picture, pixels, row, column)                        
                        frame_colors += [(r, g, b) for i in range(24)]                                                         
                                            
                frames_vert_colors.append(frame_colors)

            scene.cubester_vertex_colors[ob.name] = {"type" : "vertex", "frames" : frames_vert_colors, 
                    "frame_skip" : scene.cubester_frame_step, "total_images" : max}     
                    
        # either add material or create   
        if ("CubeSter_" + "Vertex")  in bpy.data.materials:
            ob.data.materials.append(bpy.data.materials["CubeSter_" + "Vertex"])
        else:
             createMaterial(scene, ob, "Veratex")                         

    # set keyframe for each object as inital point
    frame = [1 for i in range(int(len(verts) / 8))]
    frames = [frame]
    
    area = bpy.context.area
    old_type = area.type
    area.type = "GRAPH_EDITOR"                    
    
    scene.frame_current = 0
    
    createFCurves(mesh, frames, 1, "blocks")
    
    # deselct all fcurves
    fcurves = ob.data.animation_data.action.fcurves.data.fcurves
    for i in fcurves:
        i.select = False
        
    max = scene.cubester_audio_max_freq
    min = scene.cubester_audio_min_freq
    freq_frame = scene.cubester_audio_offset_type
    
    freq_step = (max - min) / length 
    freq_sub_step = freq_step / width
    
    frame_step = scene.cubester_audio_frame_offset                

    # animate each block with a portion of the frequency
    for c in range(length):   
        frame_off = 0                  
        for r in range(width):
            if freq_frame == "frame":
                scene.frame_current = frame_off
                l = c * freq_step
                h = (c + 1) * freq_step  
                frame_off += frame_step           
            else:
                l = c * freq_step + (r * freq_sub_step) 
                h = c * freq_step  + ((r + 1) * freq_sub_step)  
                
            pos = c + (r * length) # block number
            index = pos * 4 # first index for vertex                                            
            
            # select curves
            for i in range(index, index + 4):
                curve = i * 3 + 2 # fcurve location       
                fcurves[curve].select = True                                
                                                               
            bpy.ops.graph.sound_bake(filepath = path.abspath(audio_filepath), low = l, high = h)
            
            # deselect curves   
            for i in range(index, index + 4):
                curve = i * 3 + 2 # fcurve location   
                fcurves[curve].select = False               

    area.type = old_type 
    
    # UV unwrap
    createUVMap(context, rows, int(len(faces) / 6 / rows))
    
    # if radial apply needed modifiers
    if scene.cubester_audio_block_layout == "radial":
        # add bezier curve of correct width
        bpy.ops.curve.primitive_bezier_circle_add()
        curve = bpy.context.object
        curve_size = (0.319 * (width * (size * 100)) - 0.0169) / 100 # slope determined off of collected data
        curve.dimensions = (curve_size, curve_size, 0.0)
        curve.scale = (curve.scale[0], curve.scale[0], curve.scale[0]) # correct for z height   

        ob.select = True    
        curve.select = False
        scene.objects.active = ob
        
        # data was collected and then multi-variable regression was done in Excel
        width_infl, length_infl, intercept = -0.159125, 0.49996, 0.007637 # influence of width and length
        x_offset = ((width * (size * 100) * width_infl) + (length * (size * 100) * length_infl) + intercept) / 100
        ob.location = (ob.location[0] + x_offset, ob.location[1], ob.location[2])
        
        ob.rotation_euler = (radians(-90), 0.0, 0.0)
        bpy.ops.object.modifier_add(type = "CURVE")
        ob.modifiers["Curve"].object = curve
        ob.modifiers["Curve"].deform_axis = "POS_Z"            
    def createLight(self, yi, lamp_object, matrix=None):

        lamp = lamp_object.data
        name = lamp_object.name

        if matrix is None:
            matrix = lamp_object.matrix_world.copy()
        pos = matrix[3]
        dir = matrix[2]
        # up = matrix[1]  /* UNUSED */
        to = pos - dir

        lampType = lamp.lamp_type
        power = lamp.yaf_energy
        color = lamp.color

        if self.preview:
            if name == "Lamp":
                pos = (-6, -4, 8, 1.0)
                power = 5
            elif name == "Lamp.001":
                pos = (6, -6, -2, 1.0)
                power = 6
            elif name == "Lamp.002":
                pos = (-2.9123109, -7.270790733, 4.439187765, 1.0)
                to = (-0.0062182024121284485, 0.6771485209465027, 1.8015732765197754, 1.0)
                power = 5
            elif name == "Lamp.008":
                lampType = "sun"
                power = 0.8

        yi.paramsClearAll()

        yi.printInfo("Exporting Lamp: {0} [{1}]".format(name, lampType))

        if lamp.create_geometry and not self.lightMat:
            self.yi.paramsClearAll()
            self.yi.paramsSetString("type", "light_mat")
            self.lightMat = self.yi.createMaterial("lm")
            self.yi.paramsClearAll()

        if lampType == "point":
            yi.paramsSetString("type", "pointlight")
            power = 0.5 * power * power  # original value

            if getattr(lamp, "use_sphere", False):
                radius = lamp.shadow_soft_size
                power /= (radius * radius)  # radius < 1 crash geometry ?

                if lamp.create_geometry:
                    ID = self.makeSphere(24, 48, pos[0], pos[1], pos[2], radius, self.lightMat)
                    yi.paramsSetInt("object", ID)

                yi.paramsSetString("type", "spherelight")
                yi.paramsSetInt("samples", lamp.yaf_samples)
                yi.paramsSetFloat("radius", radius)

        elif lampType == "spot":
            if self.preview and name == "Lamp.002":
                angle = 50
            else:
                # Blender reports the angle of the full cone in radians
                # and we need half of the apperture angle in degrees
                angle = degrees(lamp.spot_size) * 0.5

            yi.paramsSetString("type", "spotlight")

            yi.paramsSetFloat("cone_angle", angle)
            yi.paramsSetFloat("blend", lamp.spot_blend)
            yi.paramsSetPoint("to", to[0], to[1], to[2])
            yi.paramsSetBool("soft_shadows", lamp.spot_soft_shadows)
            yi.paramsSetFloat("shadowFuzzyness", lamp.shadow_fuzzyness)
            yi.paramsSetBool("photon_only", lamp.photon_only)
            yi.paramsSetInt("samples", lamp.yaf_samples)
            power = 0.5 * power * power

        elif lampType == "sun":
            yi.paramsSetString("type", "sunlight")
            yi.paramsSetInt("samples", lamp.yaf_samples)
            yi.paramsSetFloat("angle", lamp.angle)
            yi.paramsSetPoint("direction", dir[0], dir[1], dir[2])
            if lamp.directional:
                yi.paramsSetString("type", "directional")
                yi.paramsSetBool("infinite", lamp.infinite)
                yi.paramsSetFloat("radius", lamp.shadow_soft_size)

        elif lampType == "ies":
            # use for IES light
            yi.paramsSetString("type", "ieslight")
            yi.paramsSetPoint("to", to[0], to[1], to[2])
            ies_file = abspath(lamp.ies_file)
            if ies_file != "" and not os.path.exists(ies_file):
                return False
            yi.paramsSetString("file", ies_file)
            yi.paramsSetInt("samples", lamp.yaf_samples)
            yi.paramsSetBool("soft_shadows", lamp.ies_soft_shadows)
            # yi.paramsSetFloat("cone_angle", degrees(lamp.spot_size))  # not used for IES, cone angle is defined in IES File?

        elif lampType == "area":

            sizeX = 1.0
            sizeY = 1.0

            matrix = lamp_object.matrix_world.copy()

            # generate an untransformed rectangle in the XY plane with
            # the light's position as the centerpoint and transform it
            # using its transformation matrix

            point = mathutils.Vector((-sizeX / 2, -sizeY / 2, 0))
            corner1 = mathutils.Vector((-sizeX / 2, sizeY / 2, 0))
            corner2 = mathutils.Vector((sizeX / 2, sizeY / 2, 0))
            corner3 = mathutils.Vector((sizeX / 2, -sizeY / 2, 0))
            point = matrix * point  # use reverse vector multiply order, API changed with rev. 38674
            corner1 = matrix * corner1  # use reverse vector multiply order, API changed with rev. 38674
            corner2 = matrix * corner2  # use reverse vector multiply order, API changed with rev. 38674
            corner3 = matrix * corner3  # use reverse vector multiply order, API changed with rev. 38674

            yi.paramsClearAll()
            if lamp.create_geometry:
                ID = yi.getNextFreeID()
                yi.startGeometry()
                yi.startTriMesh(ID, 4, 2, False, False, 0)

                yi.addVertex(point[0], point[1], point[2])
                yi.addVertex(corner1[0], corner1[1], corner1[2])
                yi.addVertex(corner2[0], corner2[1], corner2[2])
                yi.addVertex(corner3[0], corner3[1], corner3[2])
                yi.addTriangle(0, 1, 2, self.lightMat)
                yi.addTriangle(0, 2, 3, self.lightMat)
                yi.endTriMesh()
                yi.endGeometry()
                yi.paramsSetInt("object", ID)

            yi.paramsSetString("type", "arealight")
            yi.paramsSetInt("samples", lamp.yaf_samples)

            yi.paramsSetPoint("corner", point[0], point[1], point[2])
            yi.paramsSetPoint("point1", corner1[0], corner1[1], corner1[2])
            yi.paramsSetPoint("point2", corner3[0], corner3[1], corner3[2])

        yi.paramsSetPoint("from", pos[0], pos[1], pos[2])
        yi.paramsSetColor("color", color[0], color[1], color[2])
        yi.paramsSetFloat("power", power)
        yi.createLight(name)

        return True
    def exportWorld(self, scene):
        yi = self.yi

        world = scene.world

        if world:
            bg_type = world.bg_type
            useIBL = world.bg_use_ibl
            iblSamples = world.bg_ibl_samples
            bgPower = world.bg_power
            with_caustic = world.bg_with_caustic
            with_diffuse = world.bg_with_diffuse
            c = world.bg_single_color
        else:
            bg_type = "Single Color"
            c = (0.0, 0.0, 0.0)
            useIBL = False
            iblSamples = 16
            bgPower = 1

        self.yi.printInfo("Exporting World, type: {0}".format(bg_type))
        yi.paramsClearAll()

        if bg_type == 'Texture':
            if world.active_texture is not None:
                worldTex = world.active_texture
                self.yi.printInfo("World Texture, name: {0}".format(worldTex.name))
            else:
                worldTex = None

            if worldTex is not None:

                if worldTex.type == "IMAGE" and (worldTex.image is not None):

                    yi.paramsSetString("type", "image")

                    image_file = abspath(worldTex.image.filepath)
                    image_file = realpath(image_file)
                    image_file = normpath(image_file)

                    yi.paramsSetString("filename", image_file)

                    # exposure_adjust not restricted to integer range anymore
                    yi.paramsSetFloat("exposure_adjust", world.bg_exposure)

                    if worldTex.use_interpolation == True:
                        yi.paramsSetString("interpolate", "bilinear")
                    else:
                        yi.paramsSetString("interpolate", "none")
                    
                    yi.createTexture("world_texture")

                    # Export the actual background
                    #texco = world.texture_slots[world.active_texture_index].texture_coords
                    texco = world.yaf_mapworld_type
                    yi.paramsClearAll()

                    if texco == 'ANGMAP':
                        yi.paramsSetString("mapping", "probe")
                    elif texco == 'SPHERE':
                        yi.paramsSetString("mapping", "sphere")
                    else:
                        yi.printWarning("World texture mapping neither Sphere or AngMap, set it to Sphere now by default!")
                        yi.paramsSetString("mapping", "sphere")

                    yi.paramsSetString("type", "textureback")
                    yi.paramsSetString("texture", "world_texture")
                    yi.paramsSetBool("ibl", useIBL)
                    # 'with_caustic' and 'with_diffuse' settings gets checked in textureback.cc,
                    # so if IBL enabled when they are used...
                    yi.paramsSetBool("with_caustic", with_caustic)
                    yi.paramsSetBool("with_diffuse", with_diffuse)
                    yi.paramsSetInt("ibl_samples", iblSamples)
                    yi.paramsSetFloat("power", bgPower)
                    yi.paramsSetFloat("rotation", world.bg_rotation)

        elif bg_type == 'Gradient':
            c = world.bg_horizon_color
            yi.paramsSetColor("horizon_color", c[0], c[1], c[2])

            c = world.bg_zenith_color
            yi.paramsSetColor("zenith_color", c[0], c[1], c[2])

            c = world.bg_horizon_ground_color
            yi.paramsSetColor("horizon_ground_color", c[0], c[1], c[2])

            c = world.bg_zenith_ground_color
            yi.paramsSetColor("zenith_ground_color", c[0], c[1], c[2])

            yi.paramsSetFloat("power", bgPower)
            yi.paramsSetBool("ibl", useIBL)
            yi.paramsSetInt("ibl_samples", iblSamples)
            yi.paramsSetString("type", "gradientback")

        elif bg_type == 'Sunsky1':
            f = world.bg_from
            yi.paramsSetPoint("from", f[0], f[1], f[2])
            yi.paramsSetFloat("turbidity", world.bg_turbidity)
            yi.paramsSetFloat("a_var", world.bg_a_var)
            yi.paramsSetFloat("b_var", world.bg_b_var)
            yi.paramsSetFloat("c_var", world.bg_c_var)
            yi.paramsSetFloat("d_var", world.bg_d_var)
            yi.paramsSetFloat("e_var", world.bg_e_var)
            yi.paramsSetBool("add_sun", world.bg_add_sun)
            yi.paramsSetFloat("sun_power", world.bg_sun_power)
            yi.paramsSetBool("background_light", world.bg_background_light)
            yi.paramsSetInt("light_samples", world.bg_light_samples)
            yi.paramsSetFloat("power", world.bg_power)
            yi.paramsSetString("type", "sunsky")

        elif bg_type == "Sunsky2":
            f = world.bg_from
            yi.paramsSetPoint("from", f[0], f[1], f[2])
            yi.paramsSetFloat("turbidity", world.bg_ds_turbidity)
            yi.paramsSetFloat("altitude", world.bg_dsaltitude)
            yi.paramsSetFloat("a_var", world.bg_a_var)
            yi.paramsSetFloat("b_var", world.bg_b_var)
            yi.paramsSetFloat("c_var", world.bg_c_var)
            yi.paramsSetFloat("d_var", world.bg_d_var)
            yi.paramsSetFloat("e_var", world.bg_e_var)
            yi.paramsSetBool("add_sun", world.bg_add_sun)
            if world.bg_add_sun:
                yi.paramsSetFloat("sun_power", world.bg_sun_power)
            yi.paramsSetBool("background_light", world.bg_background_light)
            if world.bg_background_light:
                yi.paramsSetBool("with_caustic", world.bg_with_caustic)
                yi.paramsSetBool("with_diffuse", world.bg_with_diffuse)
                yi.paramsSetFloat("power", world.bg_power)
            yi.paramsSetInt("light_samples", world.bg_light_samples)
            yi.paramsSetFloat("bright", world.bg_dsbright)
            yi.paramsSetBool("night", world.bg_dsnight)
            yi.paramsSetFloat("exposure", world.bg_exposure)
            yi.paramsSetBool("clamp_rgb", world.bg_clamp_rgb)
            yi.paramsSetBool("gamma_enc", world.bg_gamma_enc)
            yi.paramsSetString("color_space", world.bg_color_space)
            yi.paramsSetString("type", "darksky")

        else:
            yi.paramsSetColor("color", c[0], c[1], c[2])
            yi.paramsSetBool("ibl", useIBL)
            yi.paramsSetInt("ibl_samples", iblSamples)
            yi.paramsSetFloat("power", bgPower)
            yi.paramsSetString("type", "constant")

        yi.createBackground("world_background")

        return True
Beispiel #21
0
    def writeTexture(self, scene, tex):
        name = tex.name

        if name in self.loadedTextures:
            return

        yi = self.yi
        yi.paramsClearAll()

        textureConfigured = False

        if tex.yaf_tex_type == 'BLEND':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "blend")

            stype = switchBlendType.get(tex.progression, 'lin')  # set blend type for blend texture, default is 'lin'
            yi.paramsSetString("stype", stype)

            textureConfigured = True

        elif tex.yaf_tex_type == 'CLOUDS':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "clouds")

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size

            yi.paramsSetFloat("size", noise_size)

            if tex.noise_type == 'HARD_NOISE':
                hard = True
            else:
                hard = False

            yi.paramsSetBool("hard", hard)
            yi.paramsSetInt("depth", tex.noise_depth)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            textureConfigured = True

        elif tex.yaf_tex_type == 'WOOD':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "wood")

            yi.paramsSetInt("depth", 0)

            turb = 0.0
            noise_size = 0.25
            hard = True

            if tex.wood_type == 'BANDNOISE' or tex.wood_type == 'RINGNOISE':

                turb = tex.turbulence
                noise_size = tex.noise_scale

                if  noise_size > 0:
                    noise_size = 1.0 / noise_size
                if tex.noise_type == 'SOFT_NOISE':
                    hard = False

            yi.paramsSetFloat("turbulence", turb)
            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetBool("hard", hard)

            ts = "bands"

            if tex.wood_type == 'RINGS' or tex.wood_type == 'RINGNOISE':
                ts = "rings"

            yi.paramsSetString("wood_type", ts)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            # shape parameter

            if tex.noise_basis_2 == 'SAW':
                ts = "saw"
            elif tex.noise_basis_2 == 'TRI':
                ts = "tri"
            else:
                ts = "sin"

            yi.paramsSetString("shape", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'MARBLE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "marble")

            yi.paramsSetInt("depth", tex.noise_depth)
            yi.paramsSetFloat("turbulence", tex.turbulence)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size

            if tex.noise_type == 'HARD_NOISE':
                hard = True
            else:
                hard = False

            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetBool("hard", hard)

            sharp = 4.0
            if tex.marble_type == 'SOFT':
                sharp = 2.0
            elif tex.marble_type == 'SHARP':
                sharp = 4.0
            elif tex.marble_type == 'SHARPER':
                sharp = 8.0

            yi.paramsSetFloat("sharpness", sharp)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))

            if tex.noise_basis_2 == 'SAW':
                ts = "saw"
            elif tex.noise_basis_2 == 'TRI':
                ts = "tri"
            else:
                ts = "sin"

            yi.paramsSetString("shape", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'VORONOI':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "voronoi")

            if tex.color_mode == 'POSITION':
                ts = "col1"
            elif tex.color_mode == 'POSITION_OUTLINE':
                ts = "col2"
            elif tex.color_mode == 'POSITION_OUTLINE_INTENSITY':
                ts = "col3"
            else:
                ts = "int"

            yi.paramsSetString("color_type", ts)

            yi.paramsSetFloat("weight1", tex.weight_1)
            yi.paramsSetFloat("weight2", tex.weight_2)
            yi.paramsSetFloat("weight3", tex.weight_3)
            yi.paramsSetFloat("weight4", tex.weight_4)

            yi.paramsSetFloat("mk_exponent", tex.minkovsky_exponent)
            yi.paramsSetFloat("intensity", tex.noise_intensity)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)

            ts = switchDistMetric.get(tex.distance_metric, 'minkovsky')
            yi.paramsSetString("distance_metric", ts)

            textureConfigured = True

        elif tex.yaf_tex_type == 'MUSGRAVE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "musgrave")

            ts = switchMusgraveType.get(tex.musgrave_type, 'multifractal')

            yi.paramsSetString("musgrave_type", ts)
            yi.paramsSetString("noise_type", noise2string(tex.noise_basis))
            yi.paramsSetFloat("H", tex.dimension_max)
            yi.paramsSetFloat("lacunarity", tex.lacunarity)
            yi.paramsSetFloat("octaves", tex.octaves)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)
            yi.paramsSetFloat("offset", tex.offset)
            yi.paramsSetFloat("intensity", tex.noise_intensity)
            yi.paramsSetFloat("gain", tex.gain)

            textureConfigured = True

        elif tex.yaf_tex_type == 'DISTORTED_NOISE':
            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}".format(name, tex.yaf_tex_type))
            yi.paramsSetString("type", "distorted_noise")

            yi.paramsSetFloat("distort", tex.distortion)

            noise_size = tex.noise_scale
            if  noise_size > 0:
                noise_size = 1.0 / noise_size
            yi.paramsSetFloat("size", noise_size)

            yi.paramsSetString("noise_type1", noise2string(tex.noise_basis))
            yi.paramsSetString("noise_type2", noise2string(tex.noise_distortion))

            textureConfigured = True

        elif tex.yaf_tex_type == 'IMAGE' and tex.image and tex.image.source in {'FILE', 'GENERATED'}:

            filename = os.path.splitext(os.path.basename(bpy.data.filepath))[0]

            if not any(filename):
                filename = "untitled"
                save_dir = os.path.expanduser("~")
            else:
                save_dir = "//"

            filename = clean_name(filename)
            # 
            fileformat = lowerImageFileExtension.get(scene.render.image_settings.file_format,'PNG')
            extract_path = os.path.join(filename, "{:05d}".format(scene.frame_current))

            if tex.image.source == 'GENERATED':
                image_tex = "baked_image_{0}.{1}".format(clean_name(tex.name), fileformat)
                image_tex = os.path.join(save_dir, extract_path, image_tex)
                image_tex = abspath(image_tex)
                # test for not overwrite current file (or non extract every time)
                if not os.path.exists(image_tex):
                    tex.image.save_render(image_tex, scene)
                    
            if tex.image.source == 'FILE':
                #
                image_tex = ''
                if tex.image.packed_file:
                    # checking local path
                    if not os.path.exists(abspath(tex.image.filepath)):
                        tex.image.unpack(method='WRITE_LOCAL')
                    image_tex = abspath(tex.image.filepath)                        
                    
                else:
                    if tex.image.library is not None:
                        image_tex = abspath(tex.image.filepath, library=tex.image.library)
                    else:
                        image_tex = abspath(tex.image.filepath)
                    if not os.path.exists(image_tex):
                        yi.printError("Exporter: Image texture {0} not found on: {1}".format(tex.name, image_tex))
                        return False

            image_tex = os.path.realpath(image_tex)
            image_tex = os.path.normpath(image_tex)

            yi.printInfo("Exporter: Creating Texture: '{0}' type {1}: {2}".format(name, tex.yaf_tex_type, image_tex))

            yi.paramsSetString("type", "image")
            yi.paramsSetString("filename", image_tex)

            yi.paramsSetBool("use_alpha", tex.yaf_use_alpha)
            yi.paramsSetBool("calc_alpha", tex.use_calculate_alpha)
            yi.paramsSetBool("normalmap", tex.yaf_is_normal_map)
            yi.paramsSetFloat("gamma", scene.bounty.gs_gamma_input)

            # repeat
            repeat_x = 1
            repeat_y = 1

            if tex.extension == 'REPEAT':
                repeat_x = tex.repeat_x
                repeat_y = tex.repeat_y

            yi.paramsSetInt("xrepeat", repeat_x)
            yi.paramsSetInt("yrepeat", repeat_y)

            # clipping
            clipping = switchExtension.get(tex.extension, 'repeat')  # set default clipping to 'repeat'
            yi.paramsSetString("clipping", clipping)
            if clipping == 'checker':
                yi.paramsSetBool("even_tiles", tex.use_checker_even)
                yi.paramsSetBool("odd_tiles", tex.use_checker_odd)

            # crop min/max
            yi.paramsSetFloat("cropmin_x", tex.crop_min_x)
            yi.paramsSetFloat("cropmin_y", tex.crop_min_y)
            yi.paramsSetFloat("cropmax_x", tex.crop_max_x)
            yi.paramsSetFloat("cropmax_y", tex.crop_max_y)

            yi.paramsSetBool("rot90", tex.use_flip_axis)
            #yi.paramsSetString("interpolate", tex.interpolation_type)
            textureConfigured = True

        if textureConfigured:
            yi.createTexture(name)
            self.loadedTextures.add(name)

        return textureConfigured
Beispiel #22
0
    def exportWorld(self, scene, is_preview):
        yi = self.yi

        world = scene.world

        if world:
            bg_type = world.bg_type
            useIBL = world.bg_use_ibl
            iblSamples = world.bg_ibl_samples
            bgPower = world.bg_power
            c = world.bg_single_color
        else:
            bg_type = "Single Color"
            c = (0.0, 0.0, 0.0)
            useIBL = False
            iblSamples = 16
            bgPower = 1

        self.yi.printInfo("Exporting World, type: {0}".format(bg_type))
        yi.paramsClearAll()

        if bg_type == 'Texture':
            if world.active_texture is not None:
                worldTex = world.active_texture
                self.yi.printInfo("World Texture, name: {0}".format(worldTex.name))
            else:
                worldTex = None

            if worldTex is not None:
        
                yi.paramsSetFloat("adj_mult_factor_red", worldTex.factor_red)
                yi.paramsSetFloat("adj_mult_factor_green", worldTex.factor_green)
                yi.paramsSetFloat("adj_mult_factor_blue", worldTex.factor_blue)
                yi.paramsSetFloat("adj_intensity", worldTex.intensity)
                yi.paramsSetFloat("adj_contrast", worldTex.contrast)
                yi.paramsSetFloat("adj_saturation", worldTex.saturation)
                yi.paramsSetFloat("adj_hue", math.degrees(worldTex.yaf_adj_hue))
                yi.paramsSetBool("adj_clamp", worldTex.use_clamp)

                if worldTex.type == "IMAGE" and (worldTex.image is not None):

                    yi.paramsSetString("type", "image")

                    image_file = abspath(worldTex.image.filepath)
                    image_file = realpath(image_file)
                    image_file = normpath(image_file)

                    yi.paramsSetString("filename", image_file)

                    # exposure_adjust not restricted to integer range anymore
                    #yi.paramsSetFloat("exposure_adjust", world.exposure) #bg_exposure)

                    interpolate = 'none'
                    if worldTex.use_interpolation == True:
                        interpolate = 'bilinear'
                    #
                    yi.paramsSetString("interpolate", interpolate)

                    texture_color_space = "sRGB"
                    texture_gamma = 1.0

                    if worldTex.image.colorspace_settings.name == "sRGB" or worldTex.image.colorspace_settings.name == "VD16":
                        texture_color_space = "sRGB"
                        
                    elif worldTex.image.colorspace_settings.name == "XYZ":
                        texture_color_space = "XYZ"
                        
                    elif worldTex.image.colorspace_settings.name == "Linear" or worldTex.image.colorspace_settings.name == "Linear ACES" or worldTex.image.colorspace_settings.name == "Non-Color":
                        texture_color_space = "LinearRGB"
                        
                    elif worldTex.image.colorspace_settings.name == "Raw":
                        texture_color_space = "Raw_manualGamma"
                        texture_gamma = worldTex.yaf_gamma_input  #We only use the selected gamma if the color space is set to "Raw"
                
                    yi.paramsSetString("color_space", texture_color_space)
                    yi.paramsSetFloat("gamma", texture_gamma)
                    
                    yi.createTexture("world_texture")

                    # Export the actual background
                    #texco = world.texture_slots[world.active_texture_index].texture_coords
                    textcoord = world.yaf_mapworld_type
                    yi.paramsClearAll()
                    #
                    mappingType = {'ANGMAP': 'angular',
                                   'SPHERE': 'sphere'}                    
                    texco = mappingType.get(textcoord, "angular")
                    yi.paramsSetString("mapping", texco)
                    
                    # now, this msg is not need , but....
                    if textcoord not in {'ANGMAP', 'SPHERE'}:
                        yi.printWarning("World texture mapping neither Sphere or AngMap, set it to AngMap now by default!")
                        
                    yi.paramsSetString("type", "textureback")
                    yi.paramsSetString("texture", "world_texture")
                    yi.paramsSetBool("ibl", useIBL)
                    #yi.paramsSetFloat("ibl_clamp_sampling", world.ibl_clamp_sampling) #No longer needed after this issue was solved in Core (http://www.yafaray.org/node/752#comment-1621), but I will leave it here for now just in case...
                    if is_preview:
                        yi.paramsSetFloat("smartibl_blur", 0.0) #To avoid causing Blender UI freezing while waiting for the blur process to complete in the material/world previews
                    else:
                        yi.paramsSetFloat("smartibl_blur", world.bg_smartibl_blur)
                    # 'with_caustic' and 'with_diffuse' settings gets checked in textureback.cc,
                    # so if IBL enabled when they are used...
                    yi.paramsSetInt("ibl_samples", iblSamples)
                    yi.paramsSetFloat("power", bgPower)
                    yi.paramsSetFloat("rotation", world.bg_rotation)

        elif bg_type == 'Gradient':
            c = world.bg_horizon_color
            yi.paramsSetColor("horizon_color", c[0], c[1], c[2])

            c = world.bg_zenith_color
            yi.paramsSetColor("zenith_color", c[0], c[1], c[2])

            c = world.bg_horizon_ground_color
            yi.paramsSetColor("horizon_ground_color", c[0], c[1], c[2])

            c = world.bg_zenith_ground_color
            yi.paramsSetColor("zenith_ground_color", c[0], c[1], c[2])

            yi.paramsSetFloat("power", bgPower)
            yi.paramsSetBool("ibl", useIBL)
            yi.paramsSetInt("ibl_samples", iblSamples)
            yi.paramsSetString("type", "gradientback")

        elif bg_type == 'Sunsky1':
            f = world.bg_from
            yi.paramsSetPoint("from", f[0], f[1], f[2])
            yi.paramsSetFloat("turbidity", world.bg_turbidity)
            yi.paramsSetFloat("a_var", world.bg_a_var)
            yi.paramsSetFloat("b_var", world.bg_b_var)
            yi.paramsSetFloat("c_var", world.bg_c_var)
            yi.paramsSetFloat("d_var", world.bg_d_var)
            yi.paramsSetFloat("e_var", world.bg_e_var)
            yi.paramsSetBool("add_sun", world.bg_add_sun)
            yi.paramsSetFloat("sun_power", world.bg_sun_power)
            yi.paramsSetBool("background_light", world.bg_background_light)
            yi.paramsSetInt("light_samples", world.bg_light_samples)
            yi.paramsSetFloat("power", world.bg_power)
            yi.paramsSetString("type", "sunsky")

        elif bg_type == "Sunsky2":
            f = world.bg_from
            yi.paramsSetPoint("from", f[0], f[1], f[2])
            yi.paramsSetFloat("turbidity", world.bg_ds_turbidity)
            yi.paramsSetFloat("altitude", world.bg_dsaltitude)
            yi.paramsSetFloat("a_var", world.bg_a_var)
            yi.paramsSetFloat("b_var", world.bg_b_var)
            yi.paramsSetFloat("c_var", world.bg_c_var)
            yi.paramsSetFloat("d_var", world.bg_d_var)
            yi.paramsSetFloat("e_var", world.bg_e_var)
            yi.paramsSetBool("add_sun", world.bg_add_sun)
            if world.bg_add_sun:
                yi.paramsSetFloat("sun_power", world.bg_sun_power)
            yi.paramsSetBool("background_light", world.bg_background_light)
            if world.bg_background_light:
                yi.paramsSetFloat("power", world.bg_power)
            yi.paramsSetInt("light_samples", world.bg_light_samples)
            yi.paramsSetFloat("bright", world.bg_dsbright)
            yi.paramsSetBool("night", world.bg_dsnight)
            yi.paramsSetFloat("exposure", world.bg_exposure)
            yi.paramsSetBool("clamp_rgb", world.bg_clamp_rgb)
            yi.paramsSetBool("gamma_enc", world.bg_gamma_enc)
            yi.paramsSetString("color_space", world.bg_color_space)
            yi.paramsSetString("type", "darksky")

        else:
            yi.paramsSetColor("color", c[0], c[1], c[2])
            yi.paramsSetBool("ibl", useIBL)
            yi.paramsSetInt("ibl_samples", iblSamples)
            yi.paramsSetFloat("power", bgPower)
            yi.paramsSetString("type", "constant")
            
                    
        if world is not None:
            yi.paramsSetBool("cast_shadows", world.bg_cast_shadows)
            yi.paramsSetBool("cast_shadows_sun", world.bg_cast_shadows_sun)
            yi.paramsSetBool("with_caustic", world.bg_with_caustic)
            yi.paramsSetBool("with_diffuse", world.bg_with_diffuse)
            
        yi.createBackground("world_background")

        return True
Beispiel #23
0
    def createLight(self, yi, lamp_object, matrix=None):

        lamp = lamp_object.data
        name = lamp_object.name

        if matrix is None:
            matrix = lamp_object.matrix_world.copy()
        # matrix indexing (row, colums) changed in Blender rev.42816, for explanation see also:
        # http://wiki.blender.org/index.php/User:TrumanBlending/Matrix_Indexing
        pos = matrix.col[3]
        direct = matrix.col[2] # msg 'Assignment to reserved built-in symbol: dir' ( change to direct)
        # up = matrix[1]  /* UNUSED */
        to = pos - direct

        lampType = lamp.lamp_type
        power = lamp.yaf_energy
        color = lamp.color

        if self.preview:
            if name == "Lamp":
                pos = (-6, -4, 8, 1.0)
                power = 5
                if bpy.data.scenes[0].yafaray.preview.enable:
                    power *= bpy.data.scenes[0].yafaray.preview.fillLightPowerFactor
                    color = bpy.data.scenes[0].yafaray.preview.fillLightColor

            elif name == "Lamp.001":
                pos = (6, -6, -2, 1.0)
                power = 6
                if bpy.data.scenes[0].yafaray.preview.enable:
                    power *= bpy.data.scenes[0].yafaray.preview.fillLightPowerFactor
                    color = bpy.data.scenes[0].yafaray.preview.fillLightColor
                    
            elif name == "Lamp.002":
                pos = (-2.9123109, -7.270790733, 4.439187765, 1.0)
                to = (-0.0062182024121284485, 0.6771485209465027, 1.8015732765197754, 1.0)
                power = 5
                if bpy.data.scenes[0].yafaray.preview.enable:
                    power *= bpy.data.scenes[0].yafaray.preview.keyLightPowerFactor
                    color = bpy.data.scenes[0].yafaray.preview.keyLightColor
                    
            elif name == "Lamp.008":
                lampType = "sun"
                power = 0.8
                if bpy.data.scenes[0].yafaray.preview.enable:
                    power *= bpy.data.scenes[0].yafaray.preview.keyLightPowerFactor
                    color = bpy.data.scenes[0].yafaray.preview.keyLightColor
            
            if bpy.data.scenes[0].yafaray.preview.enable:
                matrix2 = mathutils.Matrix.Rotation(bpy.data.scenes[0].yafaray.preview.lightRotZ, 4, 'Z')
                pos = multiplyMatrix4x4Vector4(matrix2, mathutils.Vector((pos[0], pos[1], pos[2], pos[3])))

        yi.paramsClearAll()

        yi.printInfo("Exporting Lamp: {0} [{1}]".format(name, lampType))

        if lamp.create_geometry:  # and not self.lightMat:
            yi.paramsClearAll()
            yi.paramsSetColor("color", color[0], color[1], color[2])  # color for spherelight and area light geometry
            yi.paramsSetString("type", "light_mat")
            power_sphere = power / lamp.yaf_sphere_radius
            yi.paramsSetFloat("power", power_sphere)
        
            self.lightMat = self.yi.createMaterial(name)
            self.yi.paramsClearAll()
            #yi.paramsSetBool("light_enabled", lamp.light_enabled)

        if lampType == "point":
            yi.paramsSetString("type", "pointlight")
            if getattr(lamp, "use_sphere", False):
                if lamp.create_geometry:
                    ID = self.makeSphere(24, 48, pos[0], pos[1], pos[2], lamp.yaf_sphere_radius, self.lightMat)
                    yi.paramsSetInt("object", ID)
                yi.paramsSetString("type", "spherelight")
                yi.paramsSetInt("samples", lamp.yaf_samples)
                yi.paramsSetFloat("radius", lamp.yaf_sphere_radius)
                yi.paramsSetBool("light_enabled", lamp.light_enabled)
                yi.paramsSetBool("cast_shadows", lamp.cast_shadows)

        elif lampType == "spot":
            if self.preview and name == "Lamp.002":
                angle = 50
            else:
                # Blender reports the angle of the full cone in radians
                # and we need half of the apperture angle in degrees
                angle = degrees(lamp.spot_size) * 0.5

            yi.paramsSetString("type", "spotlight")

            yi.paramsSetFloat("cone_angle", angle)
            yi.paramsSetFloat("blend", lamp.spot_blend)
            yi.paramsSetPoint("to", to[0], to[1], to[2])
            yi.paramsSetBool("soft_shadows", lamp.spot_soft_shadows)
            yi.paramsSetFloat("shadowFuzzyness", lamp.shadow_fuzzyness)
            yi.paramsSetInt("samples", lamp.yaf_samples)
            yi.paramsSetBool("light_enabled", lamp.light_enabled)
            yi.paramsSetBool("cast_shadows", lamp.cast_shadows)

        elif lampType == "sun":
            yi.paramsSetString("type", "sunlight")
            yi.paramsSetInt("samples", lamp.yaf_samples)
            yi.paramsSetFloat("angle", lamp.angle)
            yi.paramsSetPoint("direction", direct[0], direct[1], direct[2])
            yi.paramsSetBool("light_enabled", lamp.light_enabled)
            yi.paramsSetBool("cast_shadows", lamp.cast_shadows)

        elif lampType == "directional":
            yi.paramsSetString("type", "directional")
            yi.paramsSetPoint("direction", direct[0], direct[1], direct[2])
            yi.paramsSetBool("infinite", lamp.infinite)
            if not lamp.infinite:
                yi.paramsSetFloat("radius", lamp.shadow_soft_size)
                yi.paramsSetPoint("from", pos[0], pos[1], pos[2])
            yi.paramsSetBool("light_enabled", lamp.light_enabled)
            yi.paramsSetBool("cast_shadows", lamp.cast_shadows)

        elif lampType == "ies":
            yi.paramsSetString("type", "ieslight")
            yi.paramsSetPoint("to", to[0], to[1], to[2])
            ies_file = abspath(lamp.ies_file)
            if not any(ies_file) and not os.path.exists(ies_file):
                yi.printWarning("IES file not found for {0}".format(name))
                return False
            yi.paramsSetString("file", ies_file)
            yi.paramsSetInt("samples", lamp.yaf_samples)
            yi.paramsSetBool("soft_shadows", lamp.ies_soft_shadows)
            yi.paramsSetBool("light_enabled", lamp.light_enabled)
            yi.paramsSetBool("cast_shadows", lamp.cast_shadows)

        elif lampType == "area":
            sizeX = lamp.size
            sizeY = lamp.size
            if lamp.shape == 'RECTANGLE':
                sizeY = lamp.size_y                       
            matrix = lamp_object.matrix_world.copy()           
            

            # generate an untransformed rectangle in the XY plane with
            # the light's position as the centerpoint and transform it
            # using its transformation matrix
            point = Vector((-sizeX / 2, -sizeY / 2, 0))
            corner1 = Vector((-sizeX / 2, sizeY / 2, 0))
            corner2 = Vector((sizeX / 2, sizeY / 2, 0))
            corner3 = Vector((sizeX / 2, -sizeY / 2, 0))
            
            point = matrix * point  # use reverse vector multiply order, API changed with rev. 38674
            corner1 = matrix * corner1  # use reverse vector multiply order, API changed with rev. 38674
            corner2 = matrix * corner2  # use reverse vector multiply order, API changed with rev. 38674
            corner3 = matrix * corner3  # use reverse vector multiply order, API changed with rev. 38674
            
            yi.paramsClearAll()
            if lamp.create_geometry:
                ID = yi.getNextFreeID()
                yi.startGeometry()
                yi.startTriMesh(ID, 4, 2, False, False, 0)

                yi.addVertex(point[0], point[1], point[2])
                yi.addVertex(corner1[0], corner1[1], corner1[2])
                yi.addVertex(corner2[0], corner2[1], corner2[2])
                yi.addVertex(corner3[0], corner3[1], corner3[2])
                yi.addTriangle(0, 1, 2, self.lightMat)
                yi.addTriangle(0, 2, 3, self.lightMat)
                yi.endTriMesh()
                yi.endGeometry()
                yi.paramsSetInt("object", ID)

            yi.paramsSetString("type", "arealight")
            yi.paramsSetInt("samples", lamp.yaf_samples)
            yi.paramsSetPoint("corner", point[0], point[1], point[2])
            yi.paramsSetPoint("point1", corner1[0], corner1[1], corner1[2])
            yi.paramsSetPoint("point2", corner3[0], corner3[1], corner3[2])
            yi.paramsSetBool("light_enabled", lamp.light_enabled)
            yi.paramsSetBool("cast_shadows", lamp.cast_shadows)

        if lampType not in {"sun", "directional"}:
            # "from" is not used for sunlight and infinite directional light
            yi.paramsSetPoint("from", pos[0], pos[1], pos[2])
        if lampType in {"point", "spot"}:
            if getattr(lamp, "use_sphere", False) and lampType == "point":
                power = 0.5 * power * power / (lamp.yaf_sphere_radius * lamp.yaf_sphere_radius)
            else:
                power = 0.5 * power * power

        yi.paramsSetColor("color", color[0], color[1], color[2])
        yi.paramsSetFloat("power", power)
        yi.paramsSetBool("light_enabled", lamp.light_enabled)
        yi.paramsSetBool("cast_shadows", lamp.cast_shadows)
        yi.paramsSetBool("with_caustic", lamp.caustic_photons)
        yi.paramsSetBool("with_diffuse", lamp.diffuse_photons)
        yi.paramsSetBool("photon_only", lamp.photon_only)
        yi.createLight(name)

        return True