Set BPlane transparency only if BProjection material exists. Avoids breaking the...
[blender-addons-contrib.git] / space_view3d_paint_bprojection.py
1 bl_info = {
2     "name": "BProjection",
3     "description": "Help Clone tool",
4     "author": "kgeogeo",
5     "version": (1, 0),
6     "blender": (2, 6, 3),
7     "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/3D_interaction/bprojection",
8     "tracker_url":"http://projects.blender.org/tracker/index.php?func=detail&aid=30521&group_id=153&atid=468",
9     "category": "Paint"}
10
11 import bpy
12 from bpy.types import Panel, Operator
13 from bpy.props import IntProperty, FloatProperty, BoolProperty, IntVectorProperty, StringProperty, FloatVectorProperty, CollectionProperty
14 from bpy_extras import view3d_utils
15 import math
16 from math import *
17 import mathutils
18 from mathutils import *
19
20 BProjection_Empty    = 'Empty for BProjection'
21 BProjection_Material = 'Material for BProjection'
22 BProjection_Texture  = 'Texture for BProjection'
23
24 # Main function for align the plan to view
25 def align_to_view(context):
26     ob = context.object
27     em = bpy.data.objects[BProjection_Empty]       
28     rotation = em.custom_rotation
29     scale = em.custom_scale
30     z = em.custom_location.z
31     pos = [em.custom_location.x, em.custom_location.y]
32     
33     reg = context.area.regions[4]        
34     width = reg.width
35     height = reg.height 
36     
37     sd = context.space_data    
38     r3d = sd.region_3d     
39     r3d.update()
40     vr = r3d.view_rotation
41     quat = mathutils.Quaternion((0.0, 0.0, 1.0), math.radians(float(rotation)))
42     v = Vector((pos[0],pos[1],z))
43     v.rotate(vr)
44
45     em = bpy.data.objects[BProjection_Empty]
46     img = bpy.data.textures[BProjection_Texture].image
47     if img and img.size[1] != 0:
48         prop = img.size[0]/img.size[1]
49     else: prop = 1    
50     
51     if em.custom_linkscale:    
52         em.scale = Vector((prop*scale[0], scale[0], 1))
53     else:
54         em.scale = Vector((prop*scale[0], scale[1], 1))
55     pos_cur = em.location - sd.cursor_location
56     rot_cur1 = em.rotation_euler.to_quaternion()
57     em.location = v + ob.location            
58     em.rotation_euler = Quaternion.to_euler(vr*quat)   
59     if em.custom_c3d:
60         if em.custom_old_scale != em.custom_scale:
61             pos_cur = em.location - sd.cursor_location       
62         rot_cur2 = em.rotation_euler.to_quaternion()
63         rot_cur1.invert()
64         pos_cur.rotate(rot_cur1)
65         pos_cur.rotate(rot_cur2)
66         v = em.location - pos_cur
67         sd.cursor_location =  v
68
69 def applyimage(context):        
70         img = bpy.data.textures[BProjection_Texture].image
71         em = bpy.data.objects[BProjection_Empty]
72         ob = context.object
73                
74         face = ob.data.polygons
75         uvdata = ob.data.uv_textures.active.data 
76             
77         for f,d in zip(face,uvdata):
78             if f.select:
79                 d.image = img
80                
81         align_to_view(context)
82         ob.data.update()
83
84 # Function to update the properties
85 def update_Location(self, context):          
86     align_to_view(context)
87
88 def find_uv(context):
89     obj = context.object
90     me = obj.data.vertices
91     vg = obj.vertex_groups
92     l=[]
93     index_uv = 0      
94     for face in obj.data.polygons:
95         x=len(face.vertices)
96         for vertex in face.vertices:
97             if len(me[vertex].groups)>0:
98                 for g in me[vertex].groups:
99                     if vg[g.group].name == 'texture plane':
100                         x-=1
101         
102                         
103         if x == 0:
104             l.append([index_uv,len(face.vertices)])
105         index_uv += len(face.vertices)
106     return l
107
108 # Function to update the scaleUV
109 def update_UVScale(self, context):
110     ob = context.object
111     em = bpy.data.objects[BProjection_Empty]
112     v = Vector((em.custom_offsetuv[0]/10 + 0.5, em.custom_offsetuv[1]/10 + 0.5))
113     l = Vector((0.0,0.0))
114     s = em.custom_scaleuv
115     os = em.custom_old_scaleuv 
116     scale = s - os
117     l = find_uv(context)
118     for i,j in l:
119         for t in range(j):
120             d = context.object.data.uv_layers.active.data[i+t]
121             vres =  v - d.uv  
122             d.uv.x = v.x - vres.x/os[0]*s[0]
123             d.uv.y = v.y - vres.y/os[1]*s[1]
124
125     em.custom_old_scaleuv = s  
126     
127     applyimage(context)
128
129 def update_PropUVScale(self, context):
130     em = bpy.data.objects[BProjection_Empty]
131     if em.custom_linkscaleuv:
132         em.custom_scaleuv = [em.custom_propscaleuv,em.custom_propscaleuv]
133
134 def update_LinkUVScale(self, context):
135     em = bpy.data.objects[BProjection_Empty]
136     if em.custom_linkscaleuv:
137         em.custom_propscaleuv = em.custom_scaleuv.x
138         update_PropUVScale(self, context)
139     else:
140         update_UVScale(self, context) 
141         
142 # Function to update the offsetUV
143 def update_UVOffset(self, context):
144     ob = context.object
145     em = bpy.data.objects[BProjection_Empty]
146     o = em.custom_offsetuv
147     oo = em.custom_old_offsetuv 
148     l = find_uv(context)
149     for i,j in l:
150         for t in range(j):
151             d = context.object.data.uv_layers.active.data[i+t]
152             d.uv = [d.uv[0] - oo[0]/10 + o[0]/10, d.uv[1] - oo[1]/10 + o[1]/10]   
153     em.custom_old_offsetuv = o
154     
155     applyimage(context)
156
157 # Function to update the flip horizontal
158 def update_FlipUVX(self, context):
159     l = find_uv(context)
160     for i,j in l:
161         for t in range(j):
162             d = context.object.data.uv_layers.active.data[i+t]
163             x = d.uv.x
164             d.uv.x = 1 - x
165     
166     applyimage(context)
167
168 # Function to update the flip vertical
169 def update_FlipUVY(self, context):
170     l = find_uv(context)
171     for i,j in l:
172         for t in range(j):
173             d = context.object.data.uv_layers.active.data[i+t]
174             y = d.uv[1]
175             d.uv[1] = 1 - y
176     
177     applyimage(context)
178
179 # Function to update
180 def update_Rotation(self, context):              
181     ob = context.object
182     em = bpy.data.objects[BProjection_Empty]
183     if em.custom_rotc3d:
184         angle = em.custom_rotation - em.custom_old_rotation
185         sd = context.space_data
186         vr = sd.region_3d.view_rotation.copy()        
187         c = sd.cursor_location - ob.location
188         e = bpy.data.objects[BProjection_Empty].location - ob.location
189         vo = Vector((0.0, 0.0, 1.0))
190         vo.rotate(vr)
191         quat = mathutils.Quaternion(vo, math.radians(angle))
192         v = e-c
193         v.rotate(quat)
194         vr.invert()
195         v.rotate(vr)
196         c.rotate(vr)
197         em.custom_location = c + v
198     else:        
199         align_to_view(context)
200    
201     em.custom_old_rotation = em.custom_rotation
202
203 # Function to update scale
204 def update_Scale(self, context):              
205     ob = context.object
206     em = bpy.data.objects[BProjection_Empty]
207     
208     if em.custom_scac3d:
209         sd = context.space_data
210         r3d =  sd.region_3d
211         vr = r3d.view_rotation.copy()
212         vr.invert()
213         e = em.location - ob.location
214         c = sd.cursor_location - ob.location
215         ce = e - c
216         
217         s = em.custom_scale
218         os = em.custom_old_scale
219         c.rotate(vr)
220         ce.rotate(vr)
221         
222         img = bpy.data.textures[BProjection_Texture].image
223         if img and img.size[1] != 0:
224             prop = img.size[0]/img.size[1]
225         else: prop = 1
226         
227         v = Vector((s.x*ce.x/os.x, s.y*ce.y/os.y,0.0))
228         em.custom_location = c + v
229         
230
231     else:          
232         align_to_view(context)
233             
234     
235     em.custom_old_scale = em.custom_scale
236
237 def update_PropScale(self, context):
238     em = bpy.data.objects[BProjection_Empty]
239     if em.custom_linkscale:
240         em.custom_scale = [em.custom_propscale,em.custom_propscale]
241     
242 def update_LinkScale(self, context):
243     em = bpy.data.objects[BProjection_Empty]
244     if em.custom_linkscale:
245         em.custom_propscale = em.custom_scale.x
246         update_PropScale(self, context)
247     else:
248         update_Scale(self, context) 
249
250 def update_activeviewname(self, context):
251     em = bpy.data.objects[BProjection_Empty]
252     if self.custom_active:
253         em.custom_active_view = self.custom_active_view
254
255 class custom_props(bpy.types.PropertyGroup):
256     custom_location = FloatVectorProperty(name="Location", description="Location of the plan",
257                                            default=(0,0,-1.0),
258                                            subtype = 'XYZ', size=3)
259                                            
260     custom_rotation = FloatProperty(name="Rotation", description="Rotate the plane",
261                                      min=-180, max=180, default=0)
262                                          
263     custom_scale = FloatVectorProperty(name="Scales", description="Scale the planes",
264                                        subtype = 'XYZ', default=(1.0, 1.0),min = 0.1, size=2)
265     custom_propscale = FloatProperty(name="PropScale", description="Scale the Plan",
266                                            default=1.0,min = 0.1)
267                                                                                     
268     custom_linkscale = BoolProperty(name="linkscale", default=True)
269    
270     # UV properties
271     custom_scaleuv = FloatVectorProperty(name="ScaleUV", description="Scale the texture's UV",
272                                             default=(1.0,1.0),min = 0.01, subtype = 'XYZ', size=2)
273     custom_propscaleuv = FloatProperty(name="PropScaleUV", description="Scale the texture's UV",
274                                            default=1.0,min = 0.01) 
275     custom_offsetuv = FloatVectorProperty(name="OffsetUV", description="Decal the texture's UV",
276                                             default=(0.0,0.0), subtype = 'XYZ', size=2)       
277     custom_linkscaleuv = BoolProperty(name="linkscaleUV", default=True)
278     custom_flipuvx = BoolProperty(name="flipuvx", default=False)
279     custom_flipuvy = BoolProperty(name="flipuvy", default=False)
280     
281     # other properties
282     custom_active= BoolProperty(name="custom_active", default=True)   
283     custom_expand = BoolProperty(name="expand", default=False)
284     
285     custom_active_view = StringProperty(name = "custom_active_view",default = "View",update = update_activeviewname)
286     
287     custom_image = StringProperty(name = "custom_image",default = "")
288     
289     custom_index = IntProperty()
290
291 # Function to create custom properties
292 def createcustomprops(context):
293     Ob = bpy.types.Object    
294     
295     # plane properties 
296     Ob.custom_location = FloatVectorProperty(name="Location", description="Location of the plan",
297                                            default=(5.0,0.0,-1.0),
298                                            subtype = 'XYZ', size=3, update = update_Location)
299                                            
300     Ob.custom_rotation = FloatProperty(name="Rotation", description="Rotate the plane",
301                                      min=-180, max=180, default=0,update = update_Rotation)
302                                      
303     Ob.custom_old_rotation = FloatProperty(name="old_Rotation", description="Old Rotate the plane",
304                                          min=-180, max=180, default=0)
305                                          
306     Ob.custom_scale = FloatVectorProperty(name="Scales", description="Scale the planes",
307                                           subtype = 'XYZ', default=(1.0, 1.0),min = 0.1, size=2,update = update_Scale)
308     Ob.custom_propscale = FloatProperty(name="PropScale", description="Scale the Plan",
309                                            default=1.0,min = 0.1,update = update_PropScale)
310     Ob.custom_old_scale = FloatVectorProperty(name="old_Scales", description="Old Scale the planes",
311                                           subtype = 'XYZ', default=(1.0, 1.0),min = 0.1, size=2)
312                                           
313     Ob.custom_linkscale = BoolProperty(name="linkscale", default=True, update = update_LinkScale)
314     
315                                 
316     Ob.custom_sub = IntProperty(name="Subdivide", description="Number of subdivision of the plan",
317                                      min=0, max=20, default=0)                                
318     
319     # UV properties
320     Ob.custom_scaleuv = FloatVectorProperty(name="ScaleUV", description="Scale the texture's UV",
321                                             default=(1.0,1.0),min = 0.01, subtype = 'XYZ', size=2,update = update_UVScale)
322     Ob.custom_propscaleuv = FloatProperty(name="PropScaleUV", description="Scale the texture's UV",
323                                            default=1.0,min = 0.01,update = update_PropUVScale)    
324     Ob.custom_old_scaleuv = FloatVectorProperty(name="old_ScaleUV", description="Scale the texture's UV",
325                                                 default=(1.0,1.0),min = 0.01, subtype = 'XYZ', size=2)
326     Ob.custom_offsetuv = FloatVectorProperty(name="OffsetUV", description="Decal the texture's UV",
327                                             default=(0.0,0.0), subtype = 'XYZ', size=2,update = update_UVOffset)    
328     Ob.custom_old_offsetuv = FloatVectorProperty(name="old_OffsetUV", description="Decal the texture's UV",
329                                                  default=(0.0,0.0), subtype = 'XYZ', size=2)    
330     Ob.custom_linkscaleuv = BoolProperty(name="linkscaleUV", default=True, update = update_LinkUVScale)
331     Ob.custom_flipuvx = BoolProperty(name="flipuvx", default=False, update = update_FlipUVX)
332     Ob.custom_flipuvy = BoolProperty(name="flipuvy", default=False, update = update_FlipUVY)
333     
334     # other properties    
335     Ob.custom_c3d = BoolProperty(name="c3d", default=True)
336     Ob.custom_rotc3d = BoolProperty(name="rotc3d", default=False)
337     Ob.custom_scac3d = BoolProperty(name="scac3d", default=False)
338     Ob.custom_expand = BoolProperty(name="expand", default=True)
339     Ob.custom_active_view = StringProperty(name = "custom_active_view",default = "View")
340     try:
341         Ob.custom_active_object = StringProperty(name = "custom_active_object",default = context.object.name)
342     except:
343         Ob.custom_active_object = StringProperty(name = "custom_active_object",default = 'debut')    
344     Ob.custom_props = CollectionProperty(type = custom_props)
345
346 # Function to remove custom properties
347 def removecustomprops():    
348     list_prop = ['custom_location', 'custom_rotation', 'custom_old_rotation', 'custom_scale', 'custom_old_scale', 'custom_c3d',
349                  'custom_rotc3d', 'custom_scaleuv', 'custom_flipuvx', 'custom_flipuvy', 'custom_linkscale',
350                  'custom_linkscaleuv', 'custom_old_scaleuv', 'custom_offsetuv', 'custom_old_offsetuv', 'custom_scac3d', 'custom_sub',
351                  'custom_expand', 'custom_active_view', 'custom_propscaleuv', 'custom_props', 'custom_propscale']
352     for prop in list_prop:
353         try:
354             del bpy.data.objects[BProjection_Empty][prop]
355         except:
356             pass
357         
358 def clear_props(context):
359     em = bpy.data.objects[BProjection_Empty] 
360     em.custom_scale = [1,1]
361     em.custom_rotation = 0
362     em.custom_scaleuv =[1.0,1.0]
363     em.custom_offsetuv =[0.0,0.0]
364     em.custom_propscaleuv = 1.0
365     em.custom_propscale = 1.0
366     if em.custom_flipuvx == True:
367         em.custom_flipuvx = False
368     if em.custom_flipuvy == True:
369         em.custom_flipuvy = False
370
371 # Oprerator Class to create view            
372 class CreateView(Operator):
373     bl_idname = "object.create_view"
374     bl_label = "Create a new view"
375
376     def execute(self, context):              
377         ob = context.object
378         em = bpy.data.objects[BProjection_Empty]
379         new_props = em.custom_props.add()        
380         em.custom_active_view = new_props.custom_active_view               
381         ob.data.shape_keys.key_blocks[ob.active_shape_key_index].mute = True
382         bpy.ops.object.shape_key_add(from_mix = False)
383         ob.data.shape_keys.key_blocks[ob.active_shape_key_index].value = 1.0
384         new_props.custom_index = len(em.custom_props)-1
385         bpy.ops.object.active_view(index = new_props.custom_index)
386         return {'FINISHED'}
387
388 # Oprerator Class to copy view 
389 class SaveView(Operator):
390     bl_idname = "object.save_view"
391     bl_label = "copy the view"
392     
393     index = IntProperty(default = 0)
394     
395     def execute(self, context):              
396         em = bpy.data.objects[BProjection_Empty]
397         prop = em.custom_props[self.index]                            
398         prop.custom_rotation =  em.custom_rotation                    
399         prop.custom_scale =  em.custom_scale                  
400         prop.custom_linkscale =  em.custom_linkscale                                      
401         prop.custom_scaleuv = em.custom_scaleuv
402         prop.custom_propscale = em.custom_propscale
403         prop.custom_offsetuv =  em.custom_offsetuv  
404         prop.custom_linkscaleuv = em.custom_linkscaleuv
405         prop.custom_propscaleuv = em.custom_propscaleuv
406         prop.custom_flipuvx = em.custom_flipuvx
407         prop.custom_flipuvy = em.custom_flipuvy
408         try:
409             prop.custom_image = bpy.data.textures[BProjection_Texture].image.name
410         except:
411             pass
412         
413         return {'FINISHED'}
414
415 # Oprerator Class to copy view 
416 class PasteView(Operator):
417     bl_idname = "object.paste_view"
418     bl_label = "paste the view"
419     
420     index = IntProperty(default = 0)
421     
422     def execute(self, context):              
423         em = bpy.data.objects[BProjection_Empty]
424         tmp_scac3d = em.custom_scac3d
425         tmp_rotc3d = em.custom_rotc3d
426         em.custom_scac3d = False
427         em.custom_rotc3d = False
428         prop = em.custom_props[self.index]
429         em.custom_linkscale =  prop.custom_linkscale
430         em.custom_offsetuv =  prop.custom_offsetuv 
431         em.custom_linkscaleuv = prop.custom_linkscaleuv
432         em.custom_scaleuv = prop.custom_scaleuv
433         em.custom_propscaleuv = prop.custom_propscaleuv       
434         em.custom_rotation =  prop.custom_rotation                    
435         em.custom_scale =  prop.custom_scale
436         em.custom_propscale = prop.custom_propscale                     
437         if prop.custom_image != '':
438             if bpy.data.textures[BProjection_Texture].image.name != prop.custom_image:
439                 bpy.data.textures[BProjection_Texture].image = bpy.data.images[prop.custom_image]
440                 applyimage(context)
441         if em.custom_flipuvx != prop.custom_flipuvx:
442             em.custom_flipuvx = prop.custom_flipuvx
443         if em.custom_flipuvy != prop.custom_flipuvy:
444             em.custom_flipuvy = prop.custom_flipuvy
445         em.custom_scac3d = tmp_scac3d
446         em.custom_rotc3d = tmp_rotc3d        
447         return {'FINISHED'}
448
449 # Oprerator Class to remove view 
450 class RemoveView(Operator):
451     bl_idname = "object.remove_view"
452     bl_label = "Rmeove the view"
453     
454     index = IntProperty(default = 0)
455     
456     def execute(self, context):              
457         ob = context.object
458         em = bpy.data.objects[BProjection_Empty]
459         
460         ob.active_shape_key_index =  self.index + 1
461         bpy.ops.object.shape_key_remove()
462         
463         if  em.custom_props[self.index].custom_active: 
464             if len(em.custom_props) > 0:
465                 bpy.ops.object.active_view(index = self.index-1)
466             if self.index == 0 and len(em.custom_props) > 1:
467                 bpy.ops.object.active_view(index = 1)            
468                 
469         em.custom_props.remove(self.index)
470                 
471         if len(em.custom_props) == 0:
472             clear_props(context)
473             
474             bpy.ops.object.create_view()            
475                  
476         i=0
477         for item in em.custom_props:
478             item.custom_index = i           
479             i+=1 
480
481         for item in (item for item in em.custom_props if item.custom_active):
482                 ob.active_shape_key_index = item.custom_index+1
483            
484         return {'FINISHED'}
485
486 # Oprerator Class to copy view 
487 class ActiveView(Operator):
488     bl_idname = "object.active_view"
489     bl_label = "Active the view"
490     
491     index = IntProperty(default = 0)
492     
493     def execute(self, context):
494         ob = context.object
495         em = bpy.data.objects[BProjection_Empty]
496         for item in (item for item in em.custom_props if item.custom_active == True):
497             bpy.ops.object.save_view(index = item.custom_index)
498             item.custom_active = False
499         em.custom_props[self.index].custom_active  = True
500         em.custom_active_view = em.custom_props[self.index].custom_active_view 
501         ob.active_shape_key_index =  self.index + 1
502         
503         for i in ob.data.shape_keys.key_blocks:
504             i.mute = True
505         
506         ob.data.shape_keys.key_blocks[ob.active_shape_key_index].mute = False
507         
508         bpy.ops.object.paste_view(index = self.index)         
509         
510         return {'FINISHED'}
511
512 # Draw Class to show the panel
513 class BProjection(Panel):
514     bl_space_type = 'VIEW_3D'
515     bl_region_type = 'UI'
516     bl_label = "BProjection"
517
518     @classmethod
519     def poll(cls, context):
520         return (context.image_paint_object or context.sculpt_object)
521
522     def draw(self, context):
523         layout = self.layout        
524         if  BProjection_Empty in [ob.name for ob in bpy.data.objects]:
525             tex = bpy.data.textures[BProjection_Texture]
526
527             ob = context.object
528             em = bpy.data.objects[BProjection_Empty]
529             if ob == bpy.data.objects[em.custom_active_object]:            
530                 col = layout.column(align =True)
531                 col.operator("object.removebprojectionplane", text="Remove BProjection plane")           
532
533             try:
534                 matBProjection = bpy.data.materials[BProjection_Material]
535             except:
536                 matBProjection = None
537             
538             box = layout.box()
539
540             row = box.row()
541             if not em.custom_expand:
542                 row.prop(em, "custom_expand", text  = "", icon="TRIA_RIGHT", emboss=False)
543                 row.label(text= 'Paint Object: '+ ob.name)
544             else:
545                 row.prop(em, "custom_expand", text = "" , icon="TRIA_DOWN", emboss=False)                
546                 row.label(text= 'Paint Object: '+ ob.name)
547                 
548                 if ob == bpy.data.objects[em.custom_active_object]:
549                     col = box.column(align =True)
550                     col.template_ID(tex, "image", open="image.open")
551                     row  = box.row(align=True)
552                     row.operator('object.applyimage', text="Apply image", icon = 'FILE_TICK')
553                     row.prop(em, "custom_c3d",text="", icon='CURSOR')
554                     row  = box.row(align =True)
555                     row.label(text="Location:")
556                     row  = box.row(align =True)
557                     row.prop(em,'custom_location', text='')
558                     row  = box.row(align =True)            
559                     row.prop(em,'custom_rotation')
560                     row.prop(em,'custom_rotc3d',text="",icon='MANIPUL')            
561                     row  = box.row(align =True)
562                     row.label(text="Scale:")
563                     row  = box.row(align =True) 
564                     if em.custom_linkscale :
565                         row.prop(em, "custom_propscale",text="")
566                         row.prop(em, "custom_linkscale",text="",icon='LINKED')
567                     else: 
568                         row.prop(em,'custom_scale',text='')
569                         row.prop(em, "custom_linkscale",text="",icon='UNLINKED')
570                     row.prop(em,'custom_scac3d',text="",icon='MANIPUL')                            
571                     row  = box.row(align =True)
572                     row.label(text="UV's Offset:")
573                     row  = box.row(align =True)
574                     row.prop(em,'custom_offsetuv',text='')
575                     row.prop(em, "custom_flipuvx",text="",icon='ARROW_LEFTRIGHT')   
576                     row.prop(em, "custom_flipuvy",text="",icon='FULLSCREEN_ENTER') 
577                     row  = box.row(align =True)
578                     row.label(text="UV's Scale:")
579                     row  = box.row(align =True)                            
580                     if em.custom_linkscaleuv:
581                         row.prop(em,'custom_propscaleuv',text='')
582                         row.prop(em, "custom_linkscaleuv",text="",icon='LINKED')
583                     else: 
584                         row.prop(em,'custom_scaleuv',text='')
585                         row.prop(em, "custom_linkscaleuv",text="",icon='UNLINKED')            
586                     
587                     if matBProjection:
588                         row = box.column(align =True)
589                         row.prop(matBProjection,'alpha', slider = True)
590                         row = box.column(align =True)
591     
592                 if ob == bpy.data.objects[em.custom_active_object]:    
593                     for item in em.custom_props:
594                         box = layout.box()
595                         row = box.row()
596                         if item.custom_active:
597                             row.operator("object.active_view",text = "", icon='RADIOBUT_ON', emboss = False).index = item.custom_index 
598                         else:
599                             row.operator("object.active_view",text = "", icon='RADIOBUT_OFF', emboss = False).index = item.custom_index 
600                         row.prop(item, "custom_active_view", text="")        
601                         row.operator('object.remove_view', text="", icon = 'PANEL_CLOSE', emboss = False).index = item.custom_index
602                     row = layout.row()
603                     row.operator('object.create_view', text="Create View", icon = 'RENDER_STILL') 
604                 else:
605                     col = box.column(align =True)
606                     col.operator("object.change_object", text="Change Object")       
607
608         else:
609             ob = context.object
610             col = layout.column(align = True)
611             col.operator("object.addbprojectionplane", text="Add BProjection plane")
612             col = layout.column(align = True)
613             col.prop(ob, "custom_sub",text="Subdivision level")
614                    
615
616 # Oprerator Class to apply the image to the plane             
617 class ApplyImage(Operator):
618     bl_idname = "object.applyimage"
619     bl_label = "Apply image"
620
621     def execute(self, context):        
622         applyimage(context)
623         
624         return {'FINISHED'}
625
626 # Oprerator Class to make the 4 or 6 point and scale the plan
627 class IntuitiveScale(Operator):
628     bl_idname = "object.intuitivescale"
629     bl_label = "Draw lines"
630
631     def invoke(self, context, event):
632         ob = context.object
633         em = bpy.data.objects[BProjection_Empty]
634         x = event.mouse_region_x
635         y = event.mouse_region_y                
636         if len(ob.grease_pencil.layers.active.frames) == 0: 
637             bpy.ops.gpencil.draw(mode='DRAW', stroke=[{"name":"", "pen_flip":False,
638                                                        "is_start":True, "location":(0, 0, 0),
639                                                        "mouse":(x,y), "pressure":1, "time":0}])
640         else:
641             if em.custom_linkscale:
642                 nb_point = 4
643             else:
644                 nb_point = 6
645                    
646             if len(ob.grease_pencil.layers.active.frames[0].strokes) < nb_point:
647                 bpy.ops.gpencil.draw(mode='DRAW', stroke=[{"name":"", "pen_flip":False,
648                                                            "is_start":True, "location":(0, 0, 0),
649                                                            "mouse":(x,y), "pressure":1, "time":0}])
650                                                            
651             if len(ob.grease_pencil.layers.active.frames[0].strokes) == nb_point:
652                 s = ob.grease_pencil.layers.active.frames[0]
653                 v1 = s.strokes[1].points[0].co - s.strokes[0].points[0].co
654                 if not em.custom_linkscale:
655                     v2 = s.strokes[4].points[0].co - s.strokes[3].points[0].co
656                 else:
657                     v2 = s.strokes[3].points[0].co - s.strokes[2].points[0].co
658                 propx = v1.x/v2.x                
659                 em.custom_scale[0] *= abs(propx)
660                 
661                 if not em.custom_linkscale:
662                     v1 = s.strokes[2].points[0].co - s.strokes[0].points[0].co
663                     v2 = s.strokes[5].points[0].co - s.strokes[3].points[0].co
664                     propy = v1.y/v2.y
665                     em.custom_scale[1] *= abs(propy)
666                 bpy.ops.gpencil.active_frame_delete()
667         
668         return {'FINISHED'}
669
670 # Oprerator Class to configure all wath is needed
671 class AddBProjectionPlane(Operator):
672     bl_idname = "object.addbprojectionplane"
673     bl_label = "Configure"
674     
675     def creatematerial(self, context):        
676         if 'Material for BProjection' not in [mat.name for mat in bpy.data.materials]:            
677             bpy.data.textures.new(name='Texture for BProjection',type='IMAGE')
678     
679             bpy.data.materials.new(name='Material for BProjection')
680             
681             matBProjection = bpy.data.materials['Material for BProjection']
682             matBProjection.texture_slots.add()
683             matBProjection.use_shadeless = True
684             matBProjection.use_transparency = True
685             matBProjection.active_texture = bpy.data.textures['Texture for BProjection']
686         
687             index = matBProjection.active_texture_index
688             matBProjection.texture_slots[index].texture_coords = 'UV'
689         
690         ob = context.object 
691         old_index = ob.active_material_index
692         bpy.ops.object.material_slot_add()
693         index = ob.active_material_index
694         ob.material_slots[index].material = bpy.data.materials['Material for BProjection']
695         bpy.ops.object.material_slot_assign()
696         ob.active_material_index = old_index
697         ob.data.update()
698             
699     def execute(self, context):    
700         if  BProjection_Empty not in [ob.name for ob in bpy.data.objects]:                
701             
702             cm = bpy.context.object.mode
703             '''tmp = context.object
704             for ob in (ob for ob in bpy.data.objects if ob.type == 'MESH' and ob.hide == False and context.scene in ob.users_scene):
705                 context.scene.objects.active = ob
706                 bpy.ops.object.mode_set(mode = cm, toggle=False) 
707             
708             context.scene.objects.active = tmp'''
709             bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
710             
711             context.space_data.show_relationship_lines = False
712             
713             ob = context.object
714         
715             bpy.ops.object.add()
716             em = context.object
717             em.name = BProjection_Empty
718                         
719             context.scene.objects.active = ob
720             ob.select = True
721     
722             bpy.ops.object.editmode_toggle()
723     
724             bpy.ops.mesh.primitive_plane_add()
725             bpy.ops.object.vertex_group_assign(new = True)
726             ob.vertex_groups.active.name = 'texture plane'   
727             bpy.ops.uv.unwrap()
728             
729             bpy.ops.mesh.select_all(action='DESELECT')                                
730             bpy.ops.object.vertex_group_select()
731             
732             bpy.ops.object.editmode_toggle()
733             for i in range(4):
734                 ob.data.edges[len(ob.data.edges)-1-i].crease = 1
735             bpy.ops.object.editmode_toggle()
736             
737             em.custom_sub = ob.custom_sub
738             if em.custom_sub > 0:
739                 bpy.ops.mesh.subdivide(number_cuts = em.custom_sub)
740     
741             em.select = True
742             bpy.ops.object.hook_add_selob()
743             em.select = False
744             em.hide = True   
745                      
746             self.creatematerial(context)
747   
748           
749             bpy.ops.gpencil.data_add()
750             ob.grease_pencil.draw_mode = 'VIEW'
751             bpy.ops.gpencil.layer_add()
752             ob.grease_pencil.layers.active.color = [1.0,0,0]
753             
754             bpy.ops.object.editmode_toggle()
755             
756             bpy.ops.object.shape_key_add(from_mix = False)
757             
758             bpy.ops.object.create_view()
759             # ----------------------------------------------
760             # XXX, this isnt future proof, DON'T USE INDEX's - campbell                    
761             km = bpy.data.window_managers['WinMan'].keyconfigs['Blender'].keymaps['3D View']
762             km.keymap_items[3-1].idname = 'view3d.rotate_view3d'
763             km.keymap_items[19-1].idname = 'view3d.zoom_view3d'
764             km.keymap_items[19-1].properties.delta = 1.0
765             km.keymap_items[20-1].idname = 'view3d.zoom_view3d'
766             km.keymap_items[20-1].properties.delta = -1.0
767             km.keymap_items[4-1].idname = 'view3d.pan_view3d'
768             km.keymap_items[28-1].idname = 'view3d.preset_view3d'
769             km.keymap_items[28-1].properties.view = 'FRONT'
770             km.keymap_items[30-1].idname = 'view3d.preset_view3d'
771             km.keymap_items[30-1].properties.view = 'RIGHT'            
772             km.keymap_items[34-1].idname = 'view3d.preset_view3d'
773             km.keymap_items[34-1].properties.view = 'TOP'
774             km.keymap_items[36-1].idname = 'view3d.preset_view3d'
775             km.keymap_items[36-1].properties.view = 'BACK'
776             km.keymap_items[37-1].idname = 'view3d.preset_view3d'
777             km.keymap_items[37-1].properties.view = 'LEFT'            
778             km.keymap_items[38-1].idname = 'view3d.preset_view3d'
779             km.keymap_items[38-1].properties.view = 'BOTTOM'                                   
780             km = context.window_manager.keyconfigs.default.keymaps['Image Paint']
781             kmi = km.keymap_items.new("object.intuitivescale", 'LEFTMOUSE', 'PRESS', shift=True)
782                         
783             align_to_view(context)
784             
785             context.space_data.cursor_location = em.location
786             
787             bpy.ops.object.mode_set(mode = cm, toggle=False)
788             bpy.data.objects[BProjection_Empty].custom_active_object = context.object.name
789             
790         return {'FINISHED'}
791
792 # Oprerator Class to remove what is no more needed    
793 class RemoveBProjectionPlane(Operator):
794     bl_idname = "object.removebprojectionplane"
795     bl_label = "Configure"
796
797     def removematerial(self, context):
798         ob = context.object 
799         i = 0
800
801         for ms in ob.material_slots:
802             if ms.name == BProjection_Material:
803                 index = i
804             i+=1
805                 
806         ob.active_material_index = index
807         bpy.ops.object.material_slot_remove()
808     
809     def execute(self, context):
810         try:               
811             cm = bpy.context.object.mode
812             bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
813             
814             context.space_data.show_relationship_lines = True
815             
816             bpy.ops.object.modifier_remove(modifier="Hook-Empty for BProjection")
817             
818             self.removematerial(context)
819
820             ob = context.object
821     
822             bpy.ops.object.editmode_toggle()
823     
824             bpy.ops.mesh.reveal()
825                                    
826             bpy.ops.mesh.select_all(action='DESELECT')                    
827             
828             ob.vertex_groups.active_index = ob.vertex_groups['texture plane'].index
829             bpy.ops.object.vertex_group_select()
830             bpy.ops.mesh.delete()
831             bpy.ops.object.vertex_group_remove()
832     
833             bpy.ops.object.editmode_toggle()
834    
835             ob.select = False
836                 
837             em = bpy.data.objects[BProjection_Empty]
838             context.scene.objects.active = em
839             em.hide = False
840             em.select = True
841             bpy.ops.object.delete()
842     
843             context.scene.objects.active = ob
844             ob.select = True
845             
846             km = bpy.data.window_managers['WinMan'].keyconfigs['Blender'].keymaps['3D View']
847             # ----------------------------------------------
848             # XXX, this isnt future proof, DON'T USE INDEX's - campbell
849             km.keymap_items[3-1].idname = 'view3d.rotate'
850             km.keymap_items[19-1].idname = 'view3d.zoom'
851             km.keymap_items[19-1].properties.delta = 1.0
852             km.keymap_items[20-1].idname = 'view3d.zoom'
853             km.keymap_items[20-1].properties.delta = -1.0
854             km.keymap_items[4-1].idname = 'view3d.move'
855             km.keymap_items[28-1].idname = 'view3d.viewnumpad'
856             km.keymap_items[28-1].properties.type = 'FRONT'
857             km.keymap_items[30-1].idname = 'view3d.viewnumpad'
858             km.keymap_items[30-1].properties.type = 'RIGHT'            
859             km.keymap_items[34-1].idname = 'view3d.viewnumpad'
860             km.keymap_items[34-1].properties.type = 'TOP'
861             km.keymap_items[36-1].idname = 'view3d.viewnumpad'
862             km.keymap_items[36-1].properties.type = 'BACK'
863             km.keymap_items[37-1].idname = 'view3d.viewnumpad'
864             km.keymap_items[37-1].properties.type = 'LEFT'            
865             km.keymap_items[38-1].idname = 'view3d.viewnumpad'
866             km.keymap_items[38-1].properties.type = 'BOTTOM'            
867             
868             km = context.window_manager.keyconfigs.default.keymaps['Image Paint']
869             #to do
870             for kmi in (kmi for kmi in km.keymap_items if kmi.idname in {"object.intuitivescale", }):
871                     km.keymap_items.remove(kmi)
872             
873             '''tmp = context.object
874             for ob in (ob for ob in bpy.data.objects if ob.type == 'MESH' and ob.hide == False and context.scene in ob.users_scene):
875                 context.scene.objects.active = ob
876                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False) 
877             
878             context.scene.objects.active = tmp'''
879             ob = context.object           
880             
881             
882             for i in ob.data.shape_keys.key_blocks:
883                 bpy.ops.object.shape_key_remove()
884             bpy.ops.object.shape_key_remove()
885                
886             bpy.ops.object.mode_set(mode = cm, toggle=False)
887             removecustomprops()
888                     
889         except:
890             nothing = 0
891         
892         return {'FINISHED'}
893
894 # Oprerator Class to remove what is no more needed    
895 class ChangeObject(Operator):
896     bl_idname = "object.change_object"
897     bl_label = "Change Object"
898
899     def removematerial(self, context):
900         ob = context.object 
901         i = 0
902
903         for ms in ob.material_slots:
904             if ms.name == BProjection_Material:
905                 index = i
906             i+=1
907                 
908         ob.active_material_index = index
909         bpy.ops.object.material_slot_remove()
910     
911     def execute(self, context):
912             new_ob = context.object
913             em = bpy.data.objects[BProjection_Empty]              
914             context.scene.objects.active = bpy.data.objects[em.custom_active_object]
915             ob = context.object
916             if ob != new_ob:
917                 cm = bpy.context.object.mode
918                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
919                 
920                 bpy.ops.object.modifier_remove(modifier="Hook-Empty for BProjection") 
921     
922                 ob = context.object
923         
924                 bpy.ops.object.editmode_toggle()
925         
926                 bpy.ops.mesh.reveal()
927                                        
928                 bpy.ops.mesh.select_all(action='DESELECT')                               
929                 ob.vertex_groups.active_index = ob.vertex_groups['texture plane'].index
930                 bpy.ops.object.vertex_group_select()
931                 lo_b = [ob for ob in bpy.data.objects if ob.type == 'MESH']
932                 bpy.ops.mesh.separate(type='SELECTED')
933                 lo_a = [ob for ob in bpy.data.objects if ob.type == 'MESH']
934                 bpy.ops.object.vertex_group_remove()
935                 
936                 for i in lo_b:
937                     lo_a.remove(i)
938                 bplane = lo_a[0]
939                 
940                 bpy.ops.object.editmode_toggle()
941                 
942                 self.removematerial(context)
943                 
944                 bpy.ops.object.mode_set(mode = cm, toggle=False)
945                 
946                 shape_index = ob.active_shape_key_index
947                 
948                 for i in ob.data.shape_keys.key_blocks:
949                     bpy.ops.object.shape_key_remove()
950                 bpy.ops.object.shape_key_remove()
951                 
952                 ob.select = False
953                 
954                 bplane.select = True            
955                 context.scene.objects.active = bplane
956                 for ms in (ms for ms in bplane.material_slots if ms.name != BProjection_Material):
957                     bplane.active_material = ms.material
958                     bpy.ops.object.material_slot_remove()
959                 
960                 for gs in (gs for gs in bplane.vertex_groups if gs.name != 'texture plane'):
961                     bplane.vertex_groups.active_index = gs.index
962                     bpy.ops.object.vertex_group_remove()
963               
964                 context.scene.objects.active = new_ob
965                 cm = new_ob.mode
966                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False) 
967                 bpy.ops.object.join()
968     
969                 em.hide = False
970                 em.select = True
971                 new_ob.select = False
972                 bpy.ops.object.location_clear()
973                 bpy.ops.object.rotation_clear()
974                 bpy.ops.object.scale_clear()
975                 context.scene.objects.active = new_ob
976                 bpy.ops.object.editmode_toggle()            
977                 bpy.ops.object.hook_add_selob()
978                 bpy.ops.object.editmode_toggle()
979                 em.hide = True
980                 em.select = False
981                 new_ob.select = True
982                 em.custom_active_object = new_ob.name
983                 tmp = em.custom_c3d
984                 em.custom_c3d = False
985                 bpy.ops.object.active_view(index = shape_index-1)
986                 bpy.ops.object.mode_set(mode = cm, toggle=False)
987                         
988                 sd = context.space_data
989                 r3d = sd.region_3d 
990                 vr = r3d.view_rotation.copy()
991                 vr.invert()
992                 ob_loc = ob.location.copy()            
993                 new_ob_loc = new_ob.location.copy() 
994                 ob_loc.rotate(vr)
995                 new_ob_loc.rotate(vr)
996                 em.custom_location += Vector((ob_loc.x - new_ob_loc.x, ob_loc.y - new_ob_loc.y, 0.0))
997                 em.custom_c3d = tmp
998                     
999             return {'FINISHED'}
1000
1001 # Oprerator Class to rotate the view3D
1002 class RotateView3D(Operator):
1003     bl_idname = "view3d.rotate_view3d"
1004     bl_label = "Rotate the View3D"
1005     
1006     first_mouse = Vector((0,0))
1007
1008     pan = Vector((0,0))
1009
1010     key = ['']
1011  
1012     first_time = True
1013     tmp_level = -1
1014     
1015     def vect_sphere(self, context, mx, my):
1016         width = context.area.regions[4].width
1017         height = context.area.regions[4].height
1018            
1019         if width >= height:
1020             ratio = height/width
1021         
1022             x = 2*mx/width
1023             y = 2*ratio*my/height
1024             
1025             x = x - 1
1026             y = y - ratio
1027         else:
1028             ratio = width/height
1029         
1030             x = 2*ratio*mx/width
1031             y = 2*my/height
1032  
1033             x = x - ratio
1034             y = y - 1
1035         
1036         z2 = 1 - x * x - y * y
1037         if z2 > 0:
1038             z= sqrt(z2)
1039         else : z=0
1040             
1041         p = Vector((x, y, z))
1042         p.normalize()
1043         return p
1044     
1045     def tracball(self, context, mx, my, origine):
1046         sd = context.space_data
1047         ob = context.object
1048         em = bpy.data.objects[BProjection_Empty]
1049             
1050         vr_b = sd.region_3d.view_rotation.copy()
1051         vr_b.invert()
1052         pos_init = sd.region_3d.view_location - origine
1053         sd.region_3d.view_location = origine
1054         
1055         v1 = self.vect_sphere(context, self.first_mouse.x, self.first_mouse.y)
1056         v2 = self.vect_sphere(context, mx, my)
1057                         
1058         axis = Vector.cross(v1,v2);
1059         angle = Vector.angle(v1,v2);
1060             
1061         q =  Quaternion(axis,-2*angle)
1062                         
1063         sd.region_3d.view_rotation *=q
1064         sd.region_3d.update()
1065         
1066         vr_a = sd.region_3d.view_rotation.copy()                           
1067         pos_init.rotate(vr_a*vr_b)            
1068         sd.region_3d.view_location =  pos_init + origine
1069         
1070         self.first_mouse = Vector((mx, my))
1071                 
1072     def modal(self, context, event):                                
1073         ob = context.object
1074         em = bpy.data.objects['Empty for BProjection'] 
1075         reg = context.area.regions[4]        
1076         if event.value == 'PRESS':
1077             self.pan = Vector((event.mouse_region_x, event.mouse_region_y))
1078                     
1079             self.key = [event.type]
1080
1081         if event.value == 'RELEASE':
1082             self.key = [''] 
1083
1084         if event.type == 'MOUSEMOVE':                        
1085             
1086             if '' in self.key:
1087                 self.tracball(context, event.mouse_region_x, event.mouse_region_y,ob.location)
1088                 align_to_view(context)
1089                 if self.first_time:
1090                     rot_ang = context.user_preferences.view.rotation_angle            
1091                     context.user_preferences.view.rotation_angle = 0
1092                     bpy.ops.view3d.view_orbit(type='ORBITLEFT')
1093                     context.user_preferences.view.rotation_angle = rot_ang   
1094                     bpy.ops.view3d.view_persportho()         
1095                     bpy.ops.view3d.view_persportho()
1096                     self.first_time = False
1097           
1098             deltax = event.mouse_region_x - round(self.pan.x)
1099             deltay = event.mouse_region_y - round(self.pan.y)          
1100
1101             if 'G' in self.key:       
1102                 sd = context.space_data              
1103                 l =  sd.region_3d
1104                 vr = l.view_rotation.copy()
1105                 vr.invert()
1106                 
1107                 v_init = Vector((0.0,0.0,1.0))
1108                 
1109                 pos = [-deltax,-deltay]
1110                 v = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)
1111                 pos = [0,0]
1112                 vbl = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)        
1113                 loc = vbl - v            
1114                 loc.rotate(vr)
1115                 em.custom_location += loc              
1116                                    
1117             if 'S' in self.key:                
1118                 s = em.custom_scale
1119                 if em.custom_linkscale:
1120                     em.custom_propscale += deltax/20
1121                 else:
1122                     em.custom_scale = [s[0] + deltax/20, s[1] + deltay/20]
1123                                           
1124             if 'Z' in self.key:                
1125                 em.custom_location.z+=deltax/10
1126                       
1127             if 'R' in self.key:
1128                 em.custom_rotation+=deltax
1129                     
1130             if 'U' in self.key:
1131                 suv = em.custom_scaleuv
1132                 if em.custom_linkscaleuv:    
1133                     em.custom_propscaleuv += deltax/50
1134                 else:
1135                     em.custom_scaleuv= [suv[0] + deltax/50 , suv[1] + deltay/50]               
1136
1137             if 'Y' in self.key:       
1138                 ouv = em.custom_offsetuv
1139                 em.custom_offsetuv = [ouv[0] - deltax/50,ouv[1] - deltay/50] 
1140
1141             self.pan = Vector((event.mouse_region_x, event.mouse_region_y))
1142             self.first_mouse = Vector((event.mouse_region_x, self.first_mouse.y))
1143                         
1144         elif event.type == 'MIDDLEMOUSE'and event.value == 'RELEASE':
1145             if self.tmp_level > -1:
1146                 for sub in context.object.modifiers:
1147                     if sub.type in ['SUBSURF','MULTIRES']:
1148                         sub.levels = self.tmp_level   
1149             
1150             return {'FINISHED'}
1151         
1152         if 'C' in self.key:
1153             clear_props(context)
1154         
1155         if 'O' in self.key:
1156             bpy.ops.object.change_object()            
1157         return {'RUNNING_MODAL'}
1158     
1159     def execute(self, context):        
1160         align_to_view(context)  
1161         
1162         return{'FINISHED'}
1163
1164     def invoke(self, context, event):
1165         context.window_manager.modal_handler_add(self)
1166         self.first_mouse = Vector((event.mouse_region_x,event.mouse_region_y))
1167         self.first_time = True
1168         for sub in context.object.modifiers:
1169             if sub.type in ['SUBSURF', 'MULTIRES']:
1170                 self.tmp_level = sub.levels
1171                 sub.levels = 0
1172         return {'RUNNING_MODAL'}
1173
1174 # Oprerator Class to pan the view3D
1175 class PanView3D(bpy.types.Operator):
1176     bl_idname = "view3d.pan_view3d"
1177     bl_label = "Pan View3D"
1178     
1179     first_mouse = Vector((0,0))
1180     tmp_level = -1
1181
1182     def modal(self, context, event):
1183         ob = context.object
1184         em = bpy.data.objects[BProjection_Empty]
1185         width = context.area.regions[4].width
1186         height = context.area.regions[4].height
1187
1188         deltax = event.mouse_region_x - self.first_mouse.x
1189         deltay = event.mouse_region_y - self.first_mouse.y                
1190         
1191         sd = context.space_data              
1192         r3d =  sd.region_3d
1193         vr = r3d.view_rotation.copy()
1194         vr.invert()
1195         
1196         v_init = Vector((0.0,0.0,1.0))
1197         
1198         pos = [deltax,deltay]
1199         v = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1200         pos = [0,0]
1201         vbl = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)        
1202         loc = vbl - v       
1203         sd.region_3d.view_location += loc         
1204         loc.rotate(vr)
1205         em.custom_location += loc
1206
1207         self.first_mouse.x = event.mouse_region_x
1208         self.first_mouse.y = event.mouse_region_y
1209
1210         if event.type == 'MIDDLEMOUSE'and event.value == 'RELEASE':
1211             if self.tmp_level > -1:
1212                 for sub in context.object.modifiers:
1213                     if sub.type in ['SUBSURF','MULTIRES']:
1214                         sub.levels = self.tmp_level
1215             return {'FINISHED'}
1216         
1217         return {'RUNNING_MODAL'}
1218                 
1219     def invoke(self, context, event):
1220         context.window_manager.modal_handler_add(self)
1221         self.first_mouse.x = event.mouse_region_x
1222         self.first_mouse.y = event.mouse_region_y   
1223         for sub in context.object.modifiers:
1224             if sub.type in ['SUBSURF', 'MULTIRES']:
1225                 self.tmp_level = sub.levels
1226                 sub.levels = 0  
1227                       
1228         return {'RUNNING_MODAL'}
1229
1230     def execute(self, context):        
1231         align_to_view(context)  
1232         
1233         return{'FINISHED'}
1234
1235 # Oprerator Class to zoom the view3D
1236 class ZoomView3D(Operator):
1237     bl_idname = "view3d.zoom_view3d"
1238     bl_label = "Zoom View3D"
1239
1240     delta = FloatProperty(
1241         name="delta",
1242         description="Delta",
1243         min=-1.0, max=1,
1244         default=1.0)
1245
1246     def invoke(self, context, event):                   
1247         ob = context.object
1248         em = bpy.data.objects[BProjection_Empty]
1249         sd = context.space_data
1250
1251         width = context.area.regions[4].width
1252         height = context.area.regions[4].height              
1253                     
1254         r3d =  sd.region_3d
1255         v_init = Vector((0.0,0.0,1.0))
1256
1257         pos = [width,height]
1258         vtr_b = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1259         pos = [0,0]
1260         vbl_b = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1261         len_b = vtr_b - vbl_b
1262        
1263         bpy.ops.view3d.zoom(delta = self.delta)
1264         r3d.update()
1265
1266         pos = [width,height]
1267         vtr_a = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1268         pos = [0,0]
1269         vbl_a = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init) 
1270         len_a = vtr_a - vbl_a
1271         
1272         fac = len_a.length/len_b.length
1273         r3d.view_location -= ob.location
1274         r3d.view_location *= fac
1275         r3d.view_location += ob.location
1276         vres = Vector((em.custom_location.x*fac,em.custom_location.y*fac,em.custom_location.z))
1277         em.custom_location = vres
1278         
1279         
1280         align_to_view(context)
1281         
1282         return {'FINISHED'}
1283
1284     def execute(self, context):        
1285         align_to_view(context)
1286         
1287         return{'FINISHED'}
1288
1289 # Oprerator Class to use numpad shortcut
1290 class PresetView3D(Operator):
1291     bl_idname = "view3d.preset_view3d"
1292     bl_label = "Preset View3D"
1293
1294     view = StringProperty(name="View", description="Select the view", default='TOP')
1295     def invoke(self, context, event):                   
1296         ob = context.object
1297         em = bpy.data.objects[BProjection_Empty]
1298         origine = ob.location
1299         sd = context.space_data
1300
1301         vr_b = sd.region_3d.view_rotation.copy()
1302         vr_b.invert()
1303         pos_init = sd.region_3d.view_location - origine
1304         sd.region_3d.view_location = origine
1305
1306         tmp = context.user_preferences.view.smooth_view
1307         context.user_preferences.view.smooth_view = 0
1308         bpy.ops.view3d.viewnumpad(type=self.view)
1309         align_to_view(context)        
1310         context.user_preferences.view.smooth_view = tmp
1311
1312         vr_a = sd.region_3d.view_rotation.copy()                           
1313         pos_init.rotate(vr_a*vr_b)            
1314         sd.region_3d.view_location =  pos_init + origine              
1315                     
1316         return {'FINISHED'}
1317
1318 def register():
1319     bpy.utils.register_module(__name__)
1320     createcustomprops(bpy.context)
1321
1322 def unregister():
1323     bpy.utils.unregister_module(__name__)
1324
1325 if __name__ == "__main__":
1326     register()