Esempio n. 1
0
 def checkAdviseFailsInCallContext(self):
     try:
         advise()
     except SyntaxError:
         pass
     else:
         raise AssertionError("Should've got SyntaxError for advise() in function")
Esempio n. 2
0
# an English class used for adapting differnt things in adapters.

# system imports

# pub imports
from pub.interfaces import ILangMod 
import core
#import components
#import verbs
#import objs
#import gadgets

# protocols imports
from protocols import advise

advise(moduleProvides=[ILangMod])

#--------------------------------------------------------------------
# Language specific variables

name = 'english'

# words known to the parser
adverbs = [] # might be provided in verbs or objs
conjs = ['and', 'then'] 
garbs = ['the', 'a']
nouns = ['it', 'self', 'me', 'here', 'room'] 
preps = [] # supplied by each obj
verbs = []
translations = {}
Esempio n. 3
0
 class A(StickyAdapter):
     attachForProtocols = I,
     advise(instancesProvide=[I], asAdapterForTypes=[T])
Esempio n. 4
0
 class ISequenceLike(Interface):
     advise(protocolIsSubsetOf=[multimap])
Esempio n. 5
0
class Expression(Component):
    """Compute an output value using a user defined expression.

    This component outputs a single value that is driven by a user defined
    expression. The expression is specified by a string and can use an
    arbitrary number of parameters. The parameters and their default values
    have to be provided to the constructor via keyword arguments. An exception
    is the special variable "t" which will always hold the current time
    (unless you declare it explicitly).
    For each parameter a slot is created (<name>_slot), so it is also
    possible to animate the parameters. The output value can be accessed via
    the "output" and "output_slot" attributes.

    Example:

    \code
    s = Sphere()
    e = Expression("1.0 + amp*sin(freq*t)", amp=0.2, freq=2.0)
    e.output_slot.connect(s.radius_slot)
    \endcode
    
    """

    protocols.advise(instancesProvide=[ISceneItem])

    def __init__(self, expr="", exprtype=None, name="Expression", **keyargs):
        """Constructor.

        If no expression type is given the component tries to determine
        the type itself by executing the expression and inspecting the
        return type.

        \param expr (\c str) Expression
        \param exprtype (\c str) Output type or None
        \param name (\c str) Component name
        \param keyargs Parameters used in the expression
        """
        Component.__init__(self, name=name)

        self.expr = expr
        self.exprtype = exprtype

        # Create a parameter slot for every extra key arg...
        for k in keyargs:
            T = type(keyargs[k])
            if T == float or T == int:
                typ = "double"
                valstr = str(keyargs[k])
            elif T == vec3:
                typ = "vec3"
                x, y, z = keyargs[k]
                valstr = "vec3(%s, %s, %s)" % (x, y, z)
            elif T == vec4:
                typ = "vec4"
                x, y, z, w = keyargs[k]
                valstr = "vec4(%s, %s, %s, %s)" % (x, y, z, w)
            elif T == mat3:
                typ = "mat3"
                valstr = "mat3(%s)" % keyargs[k].toList(rowmajor=True)
            elif T == mat4:
                typ = "mat4"
                valstr = "mat4(%s)" % keyargs[k].toList(rowmajor=True)
            elif T == quat:
                typ = "quat"
                w, x, y, z = keyargs[k]
                valstr = "quat(%s, %s, %s, %s)" % (w, x, y, z)
            else:
                typ = "py"
                valstr = "keyargs[k]"
#                raise ValueError("Unsupported type: %s"%T)
# Create slot
            exec "self.%s_slot = %sSlot(%s)" % (k, typ.capitalize(), valstr)
            exec "self.addSlot(k, self.%s_slot)" % k

        # If t was not explicitly given use the timer...
        if "t" not in keyargs:
            self.t_slot = DoubleSlot()
            getScene().timer().time_slot.connect(self.t_slot)
            self.addSlot("t", self.t_slot)

        # Store a list of all parameter names
        self.vars = keyargs.keys()
        if "t" not in self.vars:
            self.vars.append("t")

        if self.exprtype == None:
            self.exprtype = self._determineReturnType()

        # Create the output slot
        e = self.exprtype
        if e.lower() == "float":
            e = "double"
        exec "self.output_slot = Procedural%sSlot(self.outProc)" % e.capitalize(
        )
        self.addSlot("output", self.output_slot)

        # Create dependencies
        for v in self.vars:
            exec "self.%s_slot.addDependent(self.output_slot)" % (v)

    def protocols(self):
        return [ISceneItem, IComponent]

    def outProc(self):
        for _v in self.vars:
            exec "%s = self.%s_slot.getValue()" % (_v, _v)
        return eval("%s(%s)" % (self.exprtype, self.expr))

    ## protected:

    # "output" property...
    exec slotPropertyCode("output")

    def _determineReturnType(self):
        """Try to execute the stored expression and return the output type.
        """
        for _v in self.vars:
            exec "%s = self.%s_slot.getValue()" % (_v, _v)
        out = eval(self.expr)
        T = type(out)
        if T == float or T == int:
            return "float"
        if isinstance(out, _core.vec3):
            return "vec3"
        if isinstance(out, _core.vec4):
            return "vec4"
        if isinstance(out, _core.mat3):
            return "mat3"
        if isinstance(out, _core.mat4):
            return "mat4"
        if isinstance(out, _core.quat):
            return "quat"

        if T == tuple or T == list:
            if len(out) == 3:
                return "vec3"
            if len(out) == 4:
                return "vec4"
            if len(out) == 9:
                return "mat3"
            if len(out) == 16:
                return "mat4"
            raise ValueError("Unsupported sequence size: %d" % len(out))

        raise ValueError("Unknown expression type: %s" % T)
Esempio n. 6
0
class EnglishVerb:
    """
    EnglishVerb:
      Base class of all english verbs.
    """

    advise(instancesProvide=[IVerb])

    def __init__(self, pNames=''):
        self.synonyms = pNames.split(',').lower()
        self.duration = 1    # time (in minutes) to execute
        self.succ = 'You ' + self.synonyms[0] + '.'
        self.osucc = '<The actor> ' + self.synonyms[0] + 's.'
        

    def __str__(self):
        """
        returns a string containing Verb: 
        followed by a verbs primary name

        called with str(self)
        """
        return '< Verb: ' + self.synonyms[0] + ' >'
                           
    def getDuration(self, cmd):
        return self.duration

    
    def doPreChecks(self, cmd):  # return OK or CANCEL
        """
        Check that everythings is ok, calls all relevant preChecks
        preWitness, preObj, preAct
        """
        
        #call romm hierarchy's preWitness method if any
        obj = cmd.actor.container
        
        while obj:
            if adapt(obj, IPreWitness, None) != None:
                if not obj.preWitness(cmd): return CANCEL
            obj = obj.container
        
        #call objects' preObj methods, if any
        for obj in cmd.objects: # should be a list of relevant cmd objects
            if adapt(obj, IPreObj, None):
                if not obj.preObj(cmd): return CANCEL
        
        #call actors preAct method, if any
        if adapt(cmd.actor, IPreAct, None) != None:
            if not cmd.actor.preAct(cmd): return CANCEL

        #if all checks have passed, return OK
        return OK

    def doPostChecks(self, cmd):    # return OK or CANCEL
        """
        finish up
        calls all relevant postChecks
        postWitness, postObj, postAct
        """
        #call romm hierarchy's postWitness method if any
        obj = cmd.actor.container
        
        while obj:
            if adapt(obj, IPostWitness, None) != None:
                if not obj.postWitness(cmd): return CANCEL
            obj = obj.container
        
        #call objects' postObj methods, if any
        for obj in cmd.objects: # should be a list of relevant cmd objects
            if adapt(obj, IPostObj, None):
                if not obj.postObj(cmd): return CANCEL
        
        #call actors postAct method, if any
        if adapt(cmd.actor, IPostAct, None) != None:
            if not cmd.actor.postAct(cmd): return CANCEL

        #if all checks have passed, return OK
        return OK

    #XXX: Write interfaces that show how preChecks and postChecks should work. 

    def do(self, cmd):
        """
        schedule command for execution, if actor isn't busy
        initiate immediatly
        """

        if cmd.actor.busytill > pub.scheduler.minutes:
            pub.scheduler.AddAbsEvent(cmd.actor.busytill, \
                                      pub.Event(self, 'object.begin(cmd)',cmd) )
            return
        # if actor is not busy, then begin command immediatly
        if self.begin(cmd): cmd.tell()

    def begin(self, cmd):
        """
        handle the command
        """
       
        #XXX: This is where prechecks would be handled
        # might be something like invoke(cmd.actor, IPreAct, 'preAct' cmd)
        
        if self.doPreChecks(cmd) == CANCEL: return CANCEL
        
        self.finish(cmd)

        delay = self.getDuration(cmd)

        if cmd.actor.busytill > pub.scheduler.minutes:
            cmd.actor.busytill = cmd.actor.busytill + delay
        else: cmd.actor.busytill = pub.scheduler.minutes + delay

       return OK

    def finish(self, cmd):
        """
        execute and output the event

        do the actual action i.e changes to the game objects
        """
        
        #XXX: handle postchecks
       
        if self.doPostChecks(cmd) == OK:
            cmd.tell()
        return OK
Esempio n. 7
0
class Material3DS(Material):
    """This class represents a material as it appears in 3DS files.

    """

    protocols.advise(instancesProvide=[ribexport.IMaterial])

    #    protocols.advise(instancesProvide=[ISceneItem])

    def __init__(
            self,
            name="Material3DS",
            ambient=(0, 0, 0, 0),
            diffuse=(1.0, 1.0, 1.0, 1.0),
            specular=(1.0, 1.0, 1.0, 1.0),
            shininess=1,
            shin_strength=0,
            use_blur=0,
            transparency=0.0,
            falloff=0,
            additive=0,
            use_falloff=0,
            self_illum=False,
            self_ilpct=0.0,
            shading=0,
            soften=0,
            face_map=0,
            two_sided=0,
            map_decal=0,
            use_wire=0,
            use_wire_abs=0,
            wire_size=0,
            density=1.0,
            texture1_map=None,
            texture1_mask=None,
            texture2_map=None,
            texture2_mask=None,
            opacity_map=None,
            opacity_mask=None,
            bump_map=None,
            bump_mask=None,
            specular_map=None,
            specular_mask=None,
            shininess_map=None,
            shininess_mask=None,
            self_illum_map=None,
            self_illum_mask=None,
            reflection_map=None,
            reflection_mask=None,
            bump_size=1.0  # Extra parameter to control the bump map
    ):

        Material.__init__(self, name=name, density=density)

        self.ambient = ambient
        self.diffuse = diffuse
        self.specular = specular
        self.shininess = shininess
        self.shin_strength = shin_strength
        self.transparency = transparency
        self.self_illum = self_illum
        self.self_ilpct = self_ilpct
        self.texture1_map = texture1_map
        self.texture1_mask = texture1_mask
        self.texture2_map = texture2_map
        self.texture2_mask = texture2_mask
        self.opacity_map = opacity_map
        self.opacity_mask = opacity_mask
        self.bump_map = bump_map
        self.bump_mask = bump_mask
        self.specular_map = specular_map
        self.specular_mask = specular_mask
        self.shininess_map = shininess_map
        self.shininess_mask = shininess_mask
        self.self_illum_map = self_illum_map
        self.self_illum_mask = self_illum_mask
        self.reflection_map = reflection_map
        self.reflection_mask = reflection_mask
        self.bump_size = bump_size

        if texture1_map == None:
            self._gltexture = None
            glambient = ambient
            gldiffuse = diffuse
        else:
            map = texture1_map
            T = mat4(1, 0, 0, -map.offset[0] - 0.5, 0, -1, 0,
                     0.5 - map.offset[1], 0, 0, 1, 0, 0, 0, 0, 1)
            a = sl.radians(map.rotation)
            ca = math.cos(a)
            sa = math.sin(a)
            R = mat4(ca, -sa, 0, 0, sa, ca, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
            S = mat4(map.scale[0], 0, 0, 0.5, 0, map.scale[1], 0, 0.5, 0, 0, 1,
                     0, 0, 0, 0, 1)
            self._gltexture = GLTexture(
                imagename=map.name,
                mode=GL_MODULATE,
                #                                        transform = mat4().scaling(vec3(1,-1,1))
                transform=S * R * T)
            glambient = map.percent * vec4(
                1, 1, 1, 1) + (1 - map.percent) * vec4(ambient)
            gldiffuse = map.percent * vec4(
                1, 1, 1, 1) + (1 - map.percent) * vec4(diffuse)

        self._glmaterial = GLMaterial(ambient=glambient,
                                      diffuse=gldiffuse,
                                      specular=shin_strength * specular,
                                      shininess=25 * shininess,
                                      texture=self._gltexture)

##        print >>sys.stderr, "---",name,"---"
##        print >>sys.stderr, "ambient",self.ambient
##        print >>sys.stderr, "diffuse",self.diffuse
##        print >>sys.stderr, "Map1:"
##        print >>sys.stderr, self.texture1_map
##        print >>sys.stderr, "Map2:"
##        print >>sys.stderr, self.texture2_map
##        print >>sys.stderr, "Opacity:"
##        print >>sys.stderr, self.opacity_map
##        print >>sys.stderr, "Bump:"
##        print >>sys.stderr, self.bump_map
##        print >>sys.stderr, "Specular:"
##        print >>sys.stderr, self.specular_map
##        print >>sys.stderr, "Shininess:"
##        print >>sys.stderr, self.shininess_map
##        print >>sys.stderr, "Self illum:"
##        print >>sys.stderr, self.self_illum_map
##        print >>sys.stderr, "Reflection:"
##        print >>sys.stderr, self.reflection_map
##        print >>sys.stderr, "shininess",shininess
##        print >>sys.stderr, "shin_strength",shin_strength
##        print >>sys.stderr, "transparency",transparency
##        print >>sys.stderr, "falloff",falloff
##        print >>sys.stderr, "use_falloff",use_falloff
##        print >>sys.stderr, "use_blur", use_blur
##        print >>sys.stderr, "additive",additive
##        print >>sys.stderr, "shading",shading
##        print >>sys.stderr, "soften",soften
##        print >>sys.stderr, "self_illum", self_illum
##        print >>sys.stderr, "face_map", face_map
##        print >>sys.stderr, "two_sided", two_sided
##        print >>sys.stderr, "map_decal", map_decal
##        print >>sys.stderr, "use_wire", use_wire
##        print >>sys.stderr, "use_wire_abs", use_wire_abs
##        print >>sys.stderr, "wire_size", wire_size

    def applyGL(self):
        self._glmaterial.applyGL()

    def usesBlending(self):
        return self._glmaterial.usesBlending()

    def createPasses(self):
        """Returns a list of RenderPass objects."""
        texdefs = []
        texdefs += self._createTexDef(self.texture1_map)
        texdefs += self._createTexDef(self.opacity_map)
        texdefs += self._createTexDef(self.bump_map)
        texdefs += self._createTexDef(self.specular_map)
        texdefs += self._createTexDef(self.shininess_map)
        texdefs += self._createTexDef(self.self_illum_map)
        texdefs += self._createTexDef(self.reflection_map)

        if texdefs != []:
            return [ribexport.TexPass(maps=texdefs)]
        else:
            return []

    def preProcess(self, exporter):
        """Preprocessing method.

        This method is called before the image is rendered and can be used
        to create or copy image maps.
        """
        pass
#        self._copyImageMap(self.texture1_map, exporter)
#        self._copyImageMap(self.opacity_map, exporter)
#        self._copyImageMap(self.bump_map, exporter)
#        self._copyImageMap(self.specular_map, exporter)
#        self._copyImageMap(self.shininess_map, exporter)
#        self._copyImageMap(self.self_illum_map, exporter)
#        self._copyImageMap(self.reflection_map, exporter)

    def color(self):
        """Return the color for the RiColor() call or None.
        """
        return self.diffuse

    def opacity(self):
        """Return the opacity for the RiOpacity() call or None.
        """
        a = 1.0 - self.transparency
        return (a, a, a)

    def surfaceShaderName(self):
        """Returns the name of the corresponding surface shader or None.
        """
        return "mat3ds"

    def surfaceShaderSource(self):
        """Returns surface shader source code as a string or None.

        If the return value is None, then shaderName() must return
        the name of the shader to use.
        """
        return """// 3DS material shader
        
surface $SHADERNAME(color ambient_col = color "rgb" (0, 0, 0);
           color diffuse_col = color "rgb" (1, 1, 1);
           color specular_col = color "rgb" (1, 1, 1);
           float shininess = 0.0;
           float shin_strength = 0.0;
           float self_ilpct = 0.0;
           // Texture map 1
           string texture1_map = "";
           float t1_uscale = 1.0;
           float t1_vscale = 1.0;
           float t1_uoffset = 0;
           float t1_voffset = 0;
           float t1_rotation = 0;
           float t1_blur = 0.0;
           // Specular map
           string specular_map = "";
           float sp_uscale = 1.0;
           float sp_vscale = 1.0;
           float sp_uoffset = 0;
           float sp_voffset = 0;
           float sp_rotation = 0;
           float sp_blur = 0.0;
           // Shininess map
           string shininess_map = "";
           float sh_uscale = 1.0;
           float sh_vscale = 1.0;
           float sh_uoffset = 0;
           float sh_voffset = 0;
           float sh_rotation = 0;
           float sh_blur = 0.0;
           // Opacity map
           string opacity_map = "";
           float op_uscale = 1.0;
           float op_vscale = 1.0;
           float op_uoffset = 0;
           float op_voffset = 0;
           float op_rotation = 0;
           float op_blur = 0.0;
           // Self illumination map
           string self_illum_map = "";
           float si_uscale = 1.0;
           float si_vscale = 1.0;
           float si_uoffset = 0;
           float si_voffset = 0;
           float si_rotation = 0;
           float si_blur = 0.0;
           // Reflection map
           string reflection_map = "";
           float refl_uscale = 1.0;
           float refl_vscale = 1.0;
           float refl_uoffset = 0;
           float refl_voffset = 0;
           float refl_rotation = 0;
           float refl_percent = 0.0;
           float refl_blur = 0.0;
           varying point Pref = point(0,0,0);
           )
{
  BAKE_BEGIN
  normal Nf = BAKE_NORMAL(N);
  color C_diffuse = diffuse_col;
  color C_specular = specular_col;
  color C_opacity = Os;
  color C_refl = 0;
  float final_shininess = shininess;
  float final_self_ilpct = self_ilpct;
  float s0, t0, ss, tt, a, ca, sa;
  color col;

  if (texture1_map!="")
  {
    a = radians(t1_rotation);
    ca = cos(a);
    sa = sin(a);
    s0 = s-t1_uoffset-0.5;
    t0 = 0.5-t-t1_voffset;
    ss = ca*s0 - sa*t0;
    tt = sa*s0 + ca*t0;
    ss = t1_uscale*ss+0.5;
    tt = t1_vscale*tt+0.5;
    C_diffuse = texture(texture1_map, ss, tt, "blur", t1_blur);
  }

  if (specular_map!="")
  {
    a = radians(sp_rotation);
    ca = cos(a);
    sa = sin(a);
    s0 = s-sp_uoffset-0.5;
    t0 = 0.5-t-sp_voffset;
    ss = ca*s0 - sa*t0;
    tt = sa*s0 + ca*t0;
    ss = sp_uscale*ss+0.5;
    tt = sp_vscale*tt+0.5;
    C_specular = texture(specular_map, ss, tt, "blur", sp_blur);
  }

  if (shininess_map!="")
  {
    a = radians(sh_rotation);
    ca = cos(a);
    sa = sin(a);
    s0 = s-sh_uoffset-0.5;
    t0 = 0.5-t-sh_voffset;
    ss = ca*s0 - sa*t0;
    tt = sa*s0 + ca*t0;
    ss = sh_uscale*ss+0.5;
    tt = sh_vscale*tt+0.5;
    col = texture(shininess_map, ss, tt, "blur", sh_blur);
    final_shininess = (comp(col,0)+comp(col,1)+comp(col,2))/3;
  }

  if (opacity_map!="")
  {
    a = radians(op_rotation);
    ca = cos(a);
    sa = sin(a);
    s0 = s-op_uoffset-0.5;
    t0 = 0.5-t-op_voffset;
    ss = ca*s0 - sa*t0;
    tt = sa*s0 + ca*t0;
    ss = op_uscale*ss+0.5;
    tt = op_vscale*tt+0.5;
    float op = texture(opacity_map, ss, tt, "blur", op_blur);
    C_opacity = color "rgb" (op, op, op);
  }

  if (self_illum_map!="")
  {
    a = radians(si_rotation);
    ca = cos(a);
    sa = sin(a);
    s0 = s-si_uoffset-0.5;
    t0 = 0.5-t-si_voffset;
    ss = ca*s0 - sa*t0;
    tt = sa*s0 + ca*t0;
    ss = si_uscale*ss+0.5;
    tt = si_vscale*tt+0.5;
    col = texture(self_illum_map, ss, tt, "blur", si_blur);
    final_self_ilpct = (comp(col,0)+comp(col,1)+comp(col,2))/3;
  }

  if (reflection_map!="")
  {
    vector R = normalize(vtransform("world", reflect(I, Nf)));
    float lat = acos(zcomp(R));
    float long = acos(ycomp(R)/sin(lat));
    lat = lat/PI;
    long = long/(2*PI);
    if (xcomp(R)>0)
      long = -long;
    C_refl = texture(reflection_map, long, lat, "blur", refl_blur);
  }

  Ci = C_diffuse*diffuse(Nf) +
       shin_strength*C_specular*phong(Nf, -normalize(I), 25*final_shininess) +
       refl_percent*C_refl;
  Ci = mix(Ci, C_diffuse, final_self_ilpct);
  Oi = C_opacity;
  Ci *= Oi;
  BAKE_END
}        
        """

    def surfaceShaderParams(self, passes):
        """Return a dictionary with shader parameters and their values."""
        a = self.ambient
        d = self.diffuse
        s = self.specular
        res = {
            "uniform color ambient_col": (a[0], a[1], a[2]),
            "uniform color diffuse_col": (d[0], d[1], d[2]),
            "uniform color specular_col": (s[0], s[1], s[2]),
            "uniform float shininess": self.shininess,
            "uniform float shin_strength": self.shin_strength,
            "uniform float self_ilpct": self.self_ilpct
        }

        if self.texture1_map != None:
            texname = os.path.basename(self.texture1_map.name)
            name, ext = os.path.splitext(texname)
            res["uniform string texture1_map"] = name + ".tex"
            res["uniform float t1_uscale"] = self.texture1_map.scale[0]
            res["uniform float t1_vscale"] = self.texture1_map.scale[1]
            res["uniform float t1_uoffset"] = self.texture1_map.offset[0]
            res["uniform float t1_voffset"] = self.texture1_map.offset[1]
            res["uniform float t1_rotation"] = self.texture1_map.rotation

        if self.specular_map != None:
            texname = os.path.basename(self.specular_map.name)
            name, ext = os.path.splitext(texname)
            res["uniform string specular_map"] = name + ".tex"
            res["uniform float sp_uscale"] = self.specular_map.scale[0]
            res["uniform float sp_vscale"] = self.specular_map.scale[1]
            res["uniform float sp_uoffset"] = self.specular_map.offset[0]
            res["uniform float sp_voffset"] = self.specular_map.offset[1]
            res["uniform float sp_rotation"] = self.specular_map.rotation

        if self.shininess_map != None:
            texname = os.path.basename(self.shininess_map.name)
            name, ext = os.path.splitext(texname)
            res["uniform string shininess_map"] = name + ".tex"
            res["uniform float sh_uscale"] = self.shininess_map.scale[0]
            res["uniform float sh_vscale"] = self.shininess_map.scale[1]
            res["uniform float sh_uoffset"] = self.shininess_map.offset[0]
            res["uniform float sh_voffset"] = self.shininess_map.offset[1]
            res["uniform float sh_rotation"] = self.shininess_map.rotation

        if self.opacity_map != None:
            texname = os.path.basename(self.opacity_map.name)
            name, ext = os.path.splitext(texname)
            res["uniform string opacity_map"] = name + ".tex"
            res["uniform float op_uscale"] = self.opacity_map.scale[0]
            res["uniform float op_vscale"] = self.opacity_map.scale[1]
            res["uniform float op_uoffset"] = self.opacity_map.offset[0]
            res["uniform float op_voffset"] = self.opacity_map.offset[1]
            res["uniform float op_rotation"] = self.opacity_map.rotation

        if self.self_illum_map != None:
            texname = os.path.basename(self.self_illum_map.name)
            name, ext = os.path.splitext(texname)
            res["uniform string self_illum_map"] = name + ".tex"
            res["uniform float si_uscale"] = self.self_illum_map.scale[0]
            res["uniform float si_vscale"] = self.self_illum_map.scale[1]
            res["uniform float si_uoffset"] = self.self_illum_map.offset[0]
            res["uniform float si_voffset"] = self.self_illum_map.offset[1]
            res["uniform float si_rotation"] = self.self_illum_map.rotation

        if self.reflection_map != None:
            texname = os.path.basename(self.reflection_map.name)
            name, ext = os.path.splitext(texname)
            res["uniform string reflection_map"] = name + ".tex"
            res["uniform float refl_uscale"] = self.reflection_map.scale[0]
            res["uniform float refl_vscale"] = self.reflection_map.scale[1]
            res["uniform float refl_uoffset"] = self.reflection_map.offset[0]
            res["uniform float refl_voffset"] = self.reflection_map.offset[1]
            res["uniform float refl_rotation"] = self.reflection_map.rotation
            res["uniform float refl_percent"] = self.reflection_map.percent
            res["uniform float refl_blur"] = self.reflection_map.blur

        return res

    def surfaceShaderTransform(self):
        return mat4(1)

    def displacementShaderName(self):
        if self.bump_map == None:
            return None

        return "mat3ds_bump"

    def displacementShaderSource(self):
        if self.bump_map == None:
            return None

        return """// 3DS material shader (bump)
        
displacement $SHADERNAME(
           // Bump map
           string bump_map = "";
           float uscale = 1.0;
           float vscale = 1.0;
           float uoffset = 0;
           float voffset = 0;
           float rotation = 0;
           float blur = 0;
           float bump_size = 1.0;
           )
{
  float s0, t0, ss, tt, a, ca, sa;
  color bc;
  float amount = 0.0;

  if (bump_map!="")
  {
    a = radians(rotation);
    ca = cos(a);
    sa = sin(a);
    s0 = s-uoffset-0.5;
    t0 = 0.5-t-voffset;
    ss = ca*s0 - sa*t0;
    tt = sa*s0 + ca*t0;
    ss = uscale*ss+0.5;
    tt = vscale*tt+0.5;
    bc = texture(bump_map, ss, tt, "blur", blur);
    amount = (comp(bc,0)+comp(bc,1)+comp(bc,2))/3;
  }

  P = P - bump_size*amount*normalize(N);
  N = calculatenormal(P);
}
        """

    def displacementShaderParams(self, passes):
        if self.bump_map == None:
            return {}

        res = {}
        texname = os.path.basename(self.bump_map.name)
        name, ext = os.path.splitext(texname)
        res["uniform string bump_map"] = name + ".tex"
        res["uniform float uscale"] = self.bump_map.scale[0]
        res["uniform float vscale"] = self.bump_map.scale[1]
        res["uniform float uoffset"] = self.bump_map.offset[0]
        res["uniform float voffset"] = self.bump_map.offset[1]
        res["uniform float rotation"] = self.bump_map.rotation
        res["uniform float blur"] = self.bump_map.blur
        res["uniform float bump_size"] = self.bump_size
        return res

    def displacementBound(self):
        if self.bump_map == None:
            return "current", 0
        else:
            return "current", self.bump_size

    def displacementShaderTransform(self):
        return mat4(1)

    def interiorShaderName(self):
        return None

    def interiorShaderSource(self):
        return None

    def interiorShaderParams(self, passes):
        return {}

    def interiorShaderTransform(self):
        return mat4(1)

##    def _copyImageMap(self, texmap, exporter):
##        """Copy the texture map image into the map folder.

##        \param texmap (\c TextureMap3DS) Texture map object or None
##        \param exporter Exporter instance
##        """
##        return
##        if texmap==None:
##            return

##        exporter.checkMapPath()
##        texname = os.path.basename(texmap.name)
##        name, ext = os.path.splitext(texname)
##        if ext.lower()!=".tif":
##            print 'Converting "%s"'%texmap.name
##            tifname = os.path.join(exporter.map_path, name+".tif")
##            # Read original map
##            try:
##                img = Image.open(texmap.name)
##            except IOError, e:
##                print e
##                return
##            # Save map as TIF file
##            img.save(tifname)
##        else:
##            print 'Copying "%s"'%texmap.name
##            shutil.copyfile(texmap.name, os.path.join(exporter.map_path, texmap.name))

    def _createTexDef(self, texmap):
        """Create texture definition for the TexPass.

        The method returns a list that is either empty or contains
        one texture definition tuple.

        \param texmap (\c TextureMap3DS) Texture map object or None
        \return An empty list or a list containing one texture def
        """
        if texmap == None:
            return []

#        texname = os.path.basename(texmap.name)
        texname = texmap.name
        #        texname, ext = os.path.splitext(texname)
        blur = texmap.blur + 1.0
        texdef = (
            texname,  #+".tif",
            "periodic",
            "periodic",
            "gaussian",
            blur,
            blur,
            {})
        return [texdef]
Esempio n. 8
0
class TargetCamera(camerabase.CameraBase):
    """A camera object that always looks at a particular target.
    """

    protocols.advise(instancesProvide=[ISceneItem, ICamera])

    def __init__(self,
                 name="TargetCamera",
                 fov=45.0,
                 target=vec3(0, 0, 0),
                 roll=0.0,
                 up=None,
                 fstop=0,
                 focallength=0,
                 **params):

        camerabase.CameraBase.__init__(self, name=name, **params)

        target = vec3(target)

        # FOV
        self.fov_slot = slots.DoubleSlot(fov)
        self.addSlot("fov", self.fov_slot)

        # Target
        self.target_slot = slots.Vec3Slot(target)
        self.addSlot("target", self.target_slot)

        # Roll
        self.roll_slot = slots.DoubleSlot(roll)
        self.addSlot("roll", self.roll_slot)

        # Up
        self.up_slot = slots.Vec3Slot()
        self.addSlot("up", self.up_slot)
        if up == None:
            self.up_slot.setValue(getScene().up)
        else:
            self.up_slot.setValue(vec3(up))

        self._lookat = lookat.LookAt()
        self._lookat.name = "TargetCamera_LookAt"
        self._lookat.output_slot.connect(self.rot_slot)
        self.pos_slot.connect(self._lookat.pos_slot)
        self.target_slot.connect(self._lookat.target_slot)
        self.roll_slot.connect(self._lookat.roll_slot)
        self.up_slot.connect(self._lookat.up_slot)

        # fstop
        self.fstop_slot = slots.DoubleSlot(fstop)
        self.addSlot("fstop", self.fstop_slot)

        # focal length
        self.focallength_slot = slots.DoubleSlot(focallength)
        self.addSlot("focallength", self.focallength_slot)

    def destroy(self):
        #        self.fov_slot.setController(None)
        #        self.target_slot.setController(None)
        #        self._lookat.pos_slot.setController(None)
        #        self._lookat.target_slot.setController(None)
        #        self.transform_slot.setController(None)
        #        self.pos_slot.setController(None)
        #        self.rot_slot.setController(None)
        #        self.scale_slot.setController(None)
        del self.fov_slot
        del self.target_slot
        del self._lookat.output_slot
        del self._lookat.pos_slot
        del self._lookat.target_slot
        del self.fstop_slot
        del self.focallength_slot

    # projection
    def projection(self, width, height, near, far):
        return mat4().perspective(self.fov, float(width) / height, near, far)

    # viewTransformation
    def viewTransformation(self):
        return self.worldtransform.inverse()

    ## protected:

    exec slots.slotPropertyCode("fstop")
    exec slots.slotPropertyCode("focallength")
    exec slots.slotPropertyCode("roll")
    exec slots.slotPropertyCode("up")

    # "fov" property...

    def _getFOV(self):
        """Return the current field of view.

        This method is used for retrieving the \a fov property.

        \return Field of view in angles (\c float)
        """
        return self.fov_slot.getValue()

    def _setFOV(self, fov):
        """Set the field of view.

        This method is used for setting the \a fov property.

        \param fov (\c float) Field of view in angles (0-180)
        """
        fov = float(fov)
        if fov < 0:
            fov = 0.0
        if fov > 180:
            fov = 180.0
        self.fov_slot.setValue(fov)

    fov = property(_getFOV, _setFOV, None, "Field of view (in angles)")

    # "target" property...

    def _getTarget(self):
        """Return the current target position.

        This method is used for retrieving the \a target property.

        \return Target position (\c vec3)
        """
        return self.target_slot.getValue()

    def _setTarget(self, pos):
        """Set a new target position.

        This method is used for setting the \a target property.

        \param pos (\c vec3) Target position
        """
        pos = vec3(pos)
        self.target_slot.setValue(pos)

    target = property(_getTarget, _setTarget, None, "Target position")
Esempio n. 9
0
class InfoboxProviderBase(object):
    javascript_libs = [
        'jquery',
        'jquery.hotkeys',
        'jquery.fullsize',
        'jquery.lightbox',
        'jquery.jgrow-singleline',
        'json',
        'dateformat',
        'utils',
    ]

    protocols.advise(
        instancesProvide=[gui_interfaces.ICacheableInfoboxHTMLProvider])

    def get_html(self, *a, **k):
        try:
            context = self.get_context()
            context.update(k.get('context', {}))
            self.load_files(context)
            a = time.clock()
            context.setdefault('ngettext', ngettext)
            stream = self.get_template(
                file=k.get('file'),
                loader=k.get('loader'),
                dir=k.get('dir'),
            ).generate(**context)
            ret = stream.render(method='xhtml',
                                strip_whitespace=context.get(
                                    'strip_whitespace', True))
            if hasattr(self, 'acct'):
                b = time.clock()
                self.acct.last_gen_time = b - a
#                setattr(self.acct, 'gens', getattr(self.acct, 'gens', []) + [self.acct.last_gen_time])
            return ret
        except Exception:
            print_exc()
            raise

    def load_files(self, context):
        self.platform = context.get('platform')
        self.lib = context.get('lib')
        self.app = context.get('app')

    if template_engine == 'mako':

        def get_template(self, file=None, loader=None, dir=None):
            return MakoTemplate(dir or self.get_dir(), file or 'infobox.mako')

    elif template_engine == 'tenjin':

        def get_template(self, file=None, loader=None, dir=None):
            dir = dir or self.get_dir()
            file = file or 'infobox.tenjin'
            return get_tenjin_template(dir, file)

    elif template_engine == 'genshi':

        def get_template(self, file=None, loader=None, dir=None):
            dir = dir or self.get_dir()
            loader = loader or self.get_loader(dir)
            return loader.load(file or 'infobox.xml')

    def get_dir(self, ):
        if self.platform is None:
            dir = path.path('.').abspath()
        else:
            dir = self.platform.get_res_dir('base')
        return dir

    def get_loader(self, dir=None):
        if dir is None:
            dir = self.get_dir()
        from genshi.template import TemplateLoader
        loader = TemplateLoader(dir)

        return loader

    def get_context(self):
        import util
        platform = FileContext(gui.skin.resourcedir() / 'html',
                               'infobox')  # digsby/infobox stuff
        lib = FileContext(gui.skin.resourcedir(), 'html')
        app = self.get_app_context(
            AppFileContext)  # stuff for the component using the infobox

        ctx = dict(app=app,
                   lib=lib,
                   platform=platform,
                   gui=gui,
                   util=util,
                   javascript_libs=self.javascript_libs)

        hooks.notify('infobox.content.context', ctx,
                     getattr(self, 'acct', None))

        return ctx
Esempio n. 10
0
class FreeCamera(camerabase.CameraBase):
    """A camera object that is free to move and rotate.
    """

    protocols.advise(instancesProvide=[ISceneItem, ICamera])

    def __init__(self,
                 name = "FreeCamera",
                 target = None,
                 fov = 45.0,
                 fstop = 0,
                 focallength = 0,
                 **params):
        
        camerabase.CameraBase.__init__(self, name=name, **params)

        # FOV
        self.fov_slot = slots.DoubleSlot(fov)
        self.addSlot("fov", self.fov_slot)

        # fstop
        self.fstop_slot = slots.DoubleSlot(fstop)
        self.addSlot("fstop", self.fstop_slot)
        
        # focal length
        self.focallength_slot = slots.DoubleSlot(focallength)
        self.addSlot("focallength", self.focallength_slot)

        # Initial targeting
        if target!=None:
            up = getScene().up
            self.transform = mat4().lookAt(self.pos, vec3(target), up)


    def protocols(self):
        return [ISceneItem, IComponent, IWorldObject, ICamera]

    def destroy(self):
#        self.fov_slot.setController(None)
#        self.target_slot.setController(None)
#        self._lookat.pos_slot.setController(None)
#        self._lookat.target_slot.setController(None)
#        self.transform_slot.setController(None)
#        self.pos_slot.setController(None)
#        self.rot_slot.setController(None)
#        self.scale_slot.setController(None)
        del self.fov_slot
        del self.fstop_slot
        del self.focallength_slot

    # projection
    def projection(self, width, height, near, far):
        return mat4().perspective(self.fov, float(width)/height, near, far)

    # viewTransformation
    def viewTransformation(self):
        return self.worldtransform.inverse()


    ## protected:

    exec slots.slotPropertyCode("fstop")
    exec slots.slotPropertyCode("focallength")

    # "fov" property...
    
    def _getFOV(self):
        """Return the current field of view.

        This method is used for retrieving the \a fov property.

        \return Field of view in angles (\c float)
        """
        return self.fov_slot.getValue()

    def _setFOV(self, fov):
        """Set the field of view.

        This method is used for setting the \a fov property.

        \param fov (\c float) Field of view in angles (0-180)
        """
        fov = float(fov)
        if fov<0:
            fov = 0.0
        if fov>180:
            fov = 180.0
        self.fov_slot.setValue(fov)

    fov = property(_getFOV, _setFOV, None, "Field of view (in angles)")
        
Esempio n. 11
0
class PolylineGeom(GeomObject):

    protocols.advise(instancesProvide=[IGeometry])
    
    def __init__(self,
                 pts = None,
                 color = (0,0,0)):

        GeomObject.__init__(self)
        self.pts = pts      # all points
        self.wpts = pts     # work set
        self.fpts = []      # frozen points (for fast OpenGL calls)
        self.color = color
        self.lastUpdate = time.time()

    # boundingBox
    def boundingBox(self):
        """Return the bounding box of the control polygon.
        """
        bb = BoundingBox()
        #for p in self.pts:
            #bb.addPoint(BezierPoint(p))
        return bb
    
    def addNewPoint(self, p):
        self.pts.append(p)
        self.wpts.append(p)
        self.lastUpdate = time.time()
        
        if len(self.wpts) > 20:
            #~ print "freezing"
            self.freeze(len(self.pts))

    def freeze(self, n):
        self.fpts = numpy.array(self.pts[:n], dtype=numpy.float32)
        self.wpts = self.pts[n-1:]
        #~ print len(self.wpts)
    # drawGL
    def drawGL(self):

        freezeAll = False
        dt = time.time() - self.lastUpdate
        if dt > 0.5 and len(self.wpts) > 1:
            #~ print "No update since 0.5 seconds; freezing"
            self.freeze(len(self.pts))
        
        
            
        

        t0 = time.time()
        glPushAttrib(GL_LIGHTING_BIT)
        glDisable(GL_LIGHTING)
        glLineWidth(2)
        glColor3fv(self.color)
        

        if len(self.fpts) > 1:
            glVertexPointerf(self.fpts)
            glEnableClientState( GL_VERTEX_ARRAY )
            glDrawArrays(GL_LINE_STRIP, 0, len(self.fpts))

        #~ glColor3f(1,0,0)
        if len(self.wpts) > 1:
            glVertexPointerf(self.wpts)
            glEnableClientState( GL_VERTEX_ARRAY )
            glDrawArrays(GL_LINE_STRIP, 0, len(self.wpts))

        #~ glBegin(GL_LINE_STRIP)
        #~ for p in self.pts:
            #~ glVertex3fv(p)
        #~ glEnd()

        glPopAttrib()

        t1 = time.time()
Esempio n. 12
0
class GLTargetSpotLight(_core.GLSpotLight):
    """This class represents an OpenGL spot light.

    The direction of the light is the local positive Z axis.
    """

    protocols.advise(instancesProvide=[ISceneItem])

    def __init__(self,
                 name="GLSpotLight",
                 parent=None,
                 enabled=True,
                 intensity=1.0,
                 ambient=None,
                 diffuse=None,
                 specular=None,
                 constant_attenuation=1.0,
                 linear_attenuation=0.0,
                 quadratic_attenuation=0.0,
                 exponent=0.0,
                 cutoff=45.0,
                 target=vec3(0, 0, 0),
                 cast_shadow=False,
                 auto_insert=True,
                 **params):

        _initWorldObject(self,
                         baseClass=_core.GLSpotLight,
                         name=name,
                         parent=parent,
                         auto_insert=auto_insert,
                         **params)

        target = vec3(target)

        # Target
        self.target_slot = Vec3Slot(target)
        self.addSlot("target", self.target_slot)

        self.enabled = enabled
        self.intensity = intensity
        if ambient != None:
            self.ambient = vec3(ambient)
        if diffuse != None:
            self.diffuse = vec3(diffuse)
        if specular != None:
            self.specular = vec3(specular)
        self.constant_attenuation = constant_attenuation
        self.linear_attenuation = linear_attenuation
        self.quadratic_attenuation = quadratic_attenuation
        self.exponent = exponent
        self.cutoff = cutoff

        self.cast_shadow = cast_shadow

        # Create the internal LookAt component
        self._lookat = lookat.LookAt()
        self._lookat.name = "GLTargetSpot_LookAt"
        self._lookat.output_slot.connect(self.rot_slot)
        self.pos_slot.connect(self._lookat.pos_slot)
        self.target_slot.connect(self._lookat.target_slot)

    # Create the "target" property
    exec slotPropertyCode("target")

    def protocols(self):
        return [ISceneItem]
Esempio n. 13
0
class EulerAdapter(Component):
    """Euler angle to mat3, mat4 or quat adapter.

    This class can be used to convert euler angles either to a mat3, a mat4
    or a quat. The input slots are \c anglex_slot, \c angley_slot and
    \c anglez_slot. The output slot is \c output_slot. The type of the output
    can be determined in the constructor.
    """

    protocols.advise(instancesProvide=[ISceneItem])

    def __init__(self,
                 anglex = 0,
                 angley = 0,
                 anglez = 0,
                 radians = False,
                 order = "xyz",
                 outtype = "mat3",
                 name="EulerAdapter",
                 auto_insert=True):
        """Constructor.

        \param anglex (\c float) Initial angle around x axis
        \param angley (\c float) Initial angle around y axis
        \param anglez (\c float) Initial angle around z axis
        \param radians (\c bool) True = Angles are specified in radians instead of degrees
        \param order (\c str) The rotation order ("xyz", "xzy", ...)
        \param outtpye (\c str) Output type ("mat3", "mat4", "quat")
        \param name (\c str) Component name
        \param auto_insert (\c bool) Auto insert flag
        """
        Component.__init__(self, name=name, auto_insert=auto_insert)

        if radians:
            self.factor = 1.0
        else:
            self.factor = pi/180.0

        self.anglex_slot = slots.DoubleSlot(anglex)
        self.angley_slot = slots.DoubleSlot(angley)
        self.anglez_slot = slots.DoubleSlot(anglez)
        self.addSlot("anglex", self.anglex_slot)
        self.addSlot("angley", self.angley_slot)
        self.addSlot("anglez", self.anglez_slot)

        if outtype=="mat3":
            self.output_slot = slots.ProceduralMat3Slot(self.computeMat3)
        elif outtype=="mat4":
            self.output_slot = slots.ProceduralMat4Slot(self.computeMat4)
        elif outtype=="quat":
            self.output_slot = slots.ProceduralQuatSlot(self.computeQuat)
        else:
            raise ValueError("Unknown output type: %s"%outtype)
        
        self.addSlot("output", self.output_slot)
            
        self.anglex_slot.addDependent(self.output_slot)
        self.angley_slot.addDependent(self.output_slot)
        self.anglez_slot.addDependent(self.output_slot)

        # self.fromEuler is the mat3() method that computes the matrix
        # from the euler angles. Which one exactly it is depends on the
        # order
        exec "self.fromEuler = mat3.fromEuler%s"%order.upper()

    def protocols(self):
        return [ISceneItem, IComponent]

    def computeMat3(self):
        """Slot procedure."""
        f = self.factor
        return self.fromEuler(f*self.anglex_slot.getValue(),
                              f*self.angley_slot.getValue(),
                              f*self.anglez_slot.getValue())

    def computeMat4(self):
        """Slot procedure."""
        f = self.factor
        m3 = self.fromEuler(f*self.anglex_slot.getValue(),
                            f*self.angley_slot.getValue(),
                            f*self.anglez_slot.getValue())
        res = mat4(1)
        res.setMat3(m3)
        return res

    def computeQuat(self):
        """Slot procedure."""
        f = self.factor
        m3 = self.fromEuler(f*self.anglex_slot.getValue(),
                            f*self.angley_slot.getValue(),
                            f*self.anglez_slot.getValue())
        res = quat().fromMat(m3)
        return res

    ## protected:
        
    # angle properties...
    exec slotPropertyCode("anglex")
    exec slotPropertyCode("angley")
    exec slotPropertyCode("anglez")

    # "output" property...
    exec slotPropertyCode("output")