Replaced names for Material, Empty and Texture by constants (WIP)
[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             box = layout.box()
534
535             row = box.row()
536             if not em.custom_expand:
537                 row.prop(em, "custom_expand", text  = "", icon="TRIA_RIGHT", emboss=False)
538                 row.label(text= 'Paint Object: '+ ob.name)
539             else:
540                 row.prop(em, "custom_expand", text = "" , icon="TRIA_DOWN", emboss=False)                
541                 row.label(text= 'Paint Object: '+ ob.name)
542                 
543                 if ob == bpy.data.objects[em.custom_active_object]:
544                     col = box.column(align =True)
545                     col.template_ID(tex, "image", open="image.open")
546                     row  = box.row(align=True)
547                     row.operator('object.applyimage', text="Apply image", icon = 'FILE_TICK')
548                     row.prop(em, "custom_c3d",text="", icon='CURSOR')
549                     row  = box.row(align =True)
550                     row.label(text="Location:")
551                     row  = box.row(align =True)
552                     row.prop(em,'custom_location', text='')
553                     row  = box.row(align =True)            
554                     row.prop(em,'custom_rotation')
555                     row.prop(em,'custom_rotc3d',text="",icon='MANIPUL')            
556                     row  = box.row(align =True)
557                     row.label(text="Scale:")
558                     row  = box.row(align =True) 
559                     if em.custom_linkscale :
560                         row.prop(em, "custom_propscale",text="")
561                         row.prop(em, "custom_linkscale",text="",icon='LINKED')
562                     else: 
563                         row.prop(em,'custom_scale',text='')
564                         row.prop(em, "custom_linkscale",text="",icon='UNLINKED')
565                     row.prop(em,'custom_scac3d',text="",icon='MANIPUL')                            
566                     row  = box.row(align =True)
567                     row.label(text="UV's Offset:")
568                     row  = box.row(align =True)
569                     row.prop(em,'custom_offsetuv',text='')
570                     row.prop(em, "custom_flipuvx",text="",icon='ARROW_LEFTRIGHT')   
571                     row.prop(em, "custom_flipuvy",text="",icon='FULLSCREEN_ENTER') 
572                     row  = box.row(align =True)
573                     row.label(text="UV's Scale:")
574                     row  = box.row(align =True)                            
575                     if em.custom_linkscaleuv:
576                         row.prop(em,'custom_propscaleuv',text='')
577                         row.prop(em, "custom_linkscaleuv",text="",icon='LINKED')
578                     else: 
579                         row.prop(em,'custom_scaleuv',text='')
580                         row.prop(em, "custom_linkscaleuv",text="",icon='UNLINKED')            
581                     row = box.column(align =True)
582                     row.prop(ob.material_slots['Material for BProjection'].material,'alpha', slider = True)
583                     row = box.column(align =True)
584     
585                 if ob == bpy.data.objects[em.custom_active_object]:    
586                     for item in em.custom_props:
587                         box = layout.box()
588                         row = box.row()
589                         if item.custom_active:
590                             row.operator("object.active_view",text = "", icon='RADIOBUT_ON', emboss = False).index = item.custom_index 
591                         else:
592                             row.operator("object.active_view",text = "", icon='RADIOBUT_OFF', emboss = False).index = item.custom_index 
593                         row.prop(item, "custom_active_view", text="")        
594                         row.operator('object.remove_view', text="", icon = 'PANEL_CLOSE', emboss = False).index = item.custom_index
595                     row = layout.row()
596                     row.operator('object.create_view', text="Create View", icon = 'RENDER_STILL') 
597                 else:
598                     col = box.column(align =True)
599                     col.operator("object.change_object", text="Change Object")       
600
601         else:
602             ob = context.object
603             col = layout.column(align = True)
604             col.operator("object.addbprojectionplane", text="Add BProjection plan")
605             col = layout.column(align = True)
606             col.prop(ob, "custom_sub",text="Subdivision level")
607                    
608
609 # Oprerator Class to apply the image to the plane             
610 class ApplyImage(Operator):
611     bl_idname = "object.applyimage"
612     bl_label = "Apply image"
613
614     def execute(self, context):        
615         applyimage(context)
616         
617         return {'FINISHED'}
618
619 # Oprerator Class to make the 4 or 6 point and scale the plan
620 class IntuitiveScale(Operator):
621     bl_idname = "object.intuitivescale"
622     bl_label = "Draw lines"
623
624     def invoke(self, context, event):
625         ob = context.object
626         em = bpy.data.objects[BProjection_Empty]
627         x = event.mouse_region_x
628         y = event.mouse_region_y                
629         if len(ob.grease_pencil.layers.active.frames) == 0: 
630             bpy.ops.gpencil.draw(mode='DRAW', stroke=[{"name":"", "pen_flip":False,
631                                                        "is_start":True, "location":(0, 0, 0),
632                                                        "mouse":(x,y), "pressure":1, "time":0}])
633         else:
634             if em.custom_linkscale:
635                 nb_point = 4
636             else:
637                 nb_point = 6
638                    
639             if len(ob.grease_pencil.layers.active.frames[0].strokes) < nb_point:
640                 bpy.ops.gpencil.draw(mode='DRAW', stroke=[{"name":"", "pen_flip":False,
641                                                            "is_start":True, "location":(0, 0, 0),
642                                                            "mouse":(x,y), "pressure":1, "time":0}])
643                                                            
644             if len(ob.grease_pencil.layers.active.frames[0].strokes) == nb_point:
645                 s = ob.grease_pencil.layers.active.frames[0]
646                 v1 = s.strokes[1].points[0].co - s.strokes[0].points[0].co
647                 if not em.custom_linkscale:
648                     v2 = s.strokes[4].points[0].co - s.strokes[3].points[0].co
649                 else:
650                     v2 = s.strokes[3].points[0].co - s.strokes[2].points[0].co
651                 propx = v1.x/v2.x                
652                 em.custom_scale[0] *= abs(propx)
653                 
654                 if not em.custom_linkscale:
655                     v1 = s.strokes[2].points[0].co - s.strokes[0].points[0].co
656                     v2 = s.strokes[5].points[0].co - s.strokes[3].points[0].co
657                     propy = v1.y/v2.y
658                     em.custom_scale[1] *= abs(propy)
659                 bpy.ops.gpencil.active_frame_delete()
660         
661         return {'FINISHED'}
662
663 # Oprerator Class to configure all wath is needed
664 class AddBProjectionPlane(Operator):
665     bl_idname = "object.addbprojectionplane"
666     bl_label = "Configure"
667     
668     def creatematerial(self, context):        
669         if 'Material for BProjection' not in [mat.name for mat in bpy.data.materials]:            
670             bpy.data.textures.new(name='Texture for BProjection',type='IMAGE')
671     
672             bpy.data.materials.new(name='Material for BProjection')
673             
674             matBProjection = bpy.data.materials['Material for BProjection']
675             matBProjection.texture_slots.add()
676             matBProjection.use_shadeless = True
677             matBProjection.use_transparency = True
678             matBProjection.active_texture = bpy.data.textures['Texture for BProjection']
679         
680             index = matBProjection.active_texture_index
681             matBProjection.texture_slots[index].texture_coords = 'UV'
682         
683         ob = context.object 
684         old_index = ob.active_material_index
685         bpy.ops.object.material_slot_add()
686         index = ob.active_material_index
687         ob.material_slots[index].material = bpy.data.materials['Material for BProjection']
688         bpy.ops.object.material_slot_assign()
689         ob.active_material_index = old_index
690         ob.data.update()
691             
692     def execute(self, context):    
693         if  BProjection_Empty not in [ob.name for ob in bpy.data.objects]:                
694             
695             cm = bpy.context.object.mode
696             '''tmp = context.object
697             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):
698                 context.scene.objects.active = ob
699                 bpy.ops.object.mode_set(mode = cm, toggle=False) 
700             
701             context.scene.objects.active = tmp'''
702             bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
703             
704             context.space_data.show_relationship_lines = False
705             
706             ob = context.object
707         
708             bpy.ops.object.add()
709             em = context.object
710             em.name = BProjection_Empty
711                         
712             context.scene.objects.active = ob
713             ob.select = True
714     
715             bpy.ops.object.editmode_toggle()
716     
717             bpy.ops.mesh.primitive_plane_add()
718             bpy.ops.object.vertex_group_assign(new = True)
719             ob.vertex_groups.active.name = 'texture plane'   
720             bpy.ops.uv.unwrap()
721             
722             bpy.ops.mesh.select_all(action='DESELECT')                                
723             bpy.ops.object.vertex_group_select()
724             
725             bpy.ops.object.editmode_toggle()
726             for i in range(4):
727                 ob.data.edges[len(ob.data.edges)-1-i].crease = 1
728             bpy.ops.object.editmode_toggle()
729             
730             em.custom_sub = ob.custom_sub
731             if em.custom_sub > 0:
732                 bpy.ops.mesh.subdivide(number_cuts = em.custom_sub)
733     
734             em.select = True
735             bpy.ops.object.hook_add_selob()
736             em.select = False
737             em.hide = True   
738                      
739             self.creatematerial(context)
740   
741           
742             bpy.ops.gpencil.data_add()
743             ob.grease_pencil.draw_mode = 'VIEW'
744             bpy.ops.gpencil.layer_add()
745             ob.grease_pencil.layers.active.color = [1.0,0,0]
746             
747             bpy.ops.object.editmode_toggle()
748             
749             bpy.ops.object.shape_key_add(from_mix = False)
750             
751             bpy.ops.object.create_view()
752             # ----------------------------------------------
753             # XXX, this isnt future proof, DON'T USE INDEX's - campbell                    
754             km = bpy.data.window_managers['WinMan'].keyconfigs['Blender'].keymaps['3D View']
755             km.keymap_items[3-1].idname = 'view3d.rotate_view3d'
756             km.keymap_items[19-1].idname = 'view3d.zoom_view3d'
757             km.keymap_items[19-1].properties.delta = 1.0
758             km.keymap_items[20-1].idname = 'view3d.zoom_view3d'
759             km.keymap_items[20-1].properties.delta = -1.0
760             km.keymap_items[4-1].idname = 'view3d.pan_view3d'
761             km.keymap_items[28-1].idname = 'view3d.preset_view3d'
762             km.keymap_items[28-1].properties.view = 'FRONT'
763             km.keymap_items[30-1].idname = 'view3d.preset_view3d'
764             km.keymap_items[30-1].properties.view = 'RIGHT'            
765             km.keymap_items[34-1].idname = 'view3d.preset_view3d'
766             km.keymap_items[34-1].properties.view = 'TOP'
767             km.keymap_items[36-1].idname = 'view3d.preset_view3d'
768             km.keymap_items[36-1].properties.view = 'BACK'
769             km.keymap_items[37-1].idname = 'view3d.preset_view3d'
770             km.keymap_items[37-1].properties.view = 'LEFT'            
771             km.keymap_items[38-1].idname = 'view3d.preset_view3d'
772             km.keymap_items[38-1].properties.view = 'BOTTOM'                                   
773             km = context.window_manager.keyconfigs.default.keymaps['Image Paint']
774             kmi = km.keymap_items.new("object.intuitivescale", 'LEFTMOUSE', 'PRESS', shift=True)
775                         
776             align_to_view(context)
777             
778             context.space_data.cursor_location = em.location
779             
780             bpy.ops.object.mode_set(mode = cm, toggle=False)
781             bpy.data.objects[BProjection_Empty].custom_active_object = context.object.name
782             
783         return {'FINISHED'}
784
785 # Oprerator Class to remove what is no more needed    
786 class RemoveBProjectionPlane(Operator):
787     bl_idname = "object.removebprojectionplane"
788     bl_label = "Configure"
789
790     def removematerial(self, context):
791         ob = context.object 
792         i = 0
793
794         for ms in ob.material_slots:
795             if ms.name == BProjection_Material:
796                 index = i
797             i+=1
798                 
799         ob.active_material_index = index
800         bpy.ops.object.material_slot_remove()
801     
802     def execute(self, context):
803         try:               
804             cm = bpy.context.object.mode
805             bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
806             
807             context.space_data.show_relationship_lines = True
808             
809             bpy.ops.object.modifier_remove(modifier="Hook-Empty for BProjection")
810             
811             self.removematerial(context)
812
813             ob = context.object
814     
815             bpy.ops.object.editmode_toggle()
816     
817             bpy.ops.mesh.reveal()
818                                    
819             bpy.ops.mesh.select_all(action='DESELECT')                    
820             
821             ob.vertex_groups.active_index = ob.vertex_groups['texture plane'].index
822             bpy.ops.object.vertex_group_select()
823             bpy.ops.mesh.delete()
824             bpy.ops.object.vertex_group_remove()
825     
826             bpy.ops.object.editmode_toggle()
827    
828             ob.select = False
829                 
830             em = bpy.data.objects[BProjection_Empty]
831             context.scene.objects.active = em
832             em.hide = False
833             em.select = True
834             bpy.ops.object.delete()
835     
836             context.scene.objects.active = ob
837             ob.select = True
838             
839             km = bpy.data.window_managers['WinMan'].keyconfigs['Blender'].keymaps['3D View']
840             # ----------------------------------------------
841             # XXX, this isnt future proof, DON'T USE INDEX's - campbell
842             km.keymap_items[3-1].idname = 'view3d.rotate'
843             km.keymap_items[19-1].idname = 'view3d.zoom'
844             km.keymap_items[19-1].properties.delta = 1.0
845             km.keymap_items[20-1].idname = 'view3d.zoom'
846             km.keymap_items[20-1].properties.delta = -1.0
847             km.keymap_items[4-1].idname = 'view3d.move'
848             km.keymap_items[28-1].idname = 'view3d.viewnumpad'
849             km.keymap_items[28-1].properties.type = 'FRONT'
850             km.keymap_items[30-1].idname = 'view3d.viewnumpad'
851             km.keymap_items[30-1].properties.type = 'RIGHT'            
852             km.keymap_items[34-1].idname = 'view3d.viewnumpad'
853             km.keymap_items[34-1].properties.type = 'TOP'
854             km.keymap_items[36-1].idname = 'view3d.viewnumpad'
855             km.keymap_items[36-1].properties.type = 'BACK'
856             km.keymap_items[37-1].idname = 'view3d.viewnumpad'
857             km.keymap_items[37-1].properties.type = 'LEFT'            
858             km.keymap_items[38-1].idname = 'view3d.viewnumpad'
859             km.keymap_items[38-1].properties.type = 'BOTTOM'            
860             
861             km = context.window_manager.keyconfigs.default.keymaps['Image Paint']
862             #to do
863             for kmi in (kmi for kmi in km.keymap_items if kmi.idname in {"object.intuitivescale", }):
864                     km.keymap_items.remove(kmi)
865             
866             '''tmp = context.object
867             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):
868                 context.scene.objects.active = ob
869                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False) 
870             
871             context.scene.objects.active = tmp'''
872             ob = context.object           
873             
874             
875             for i in ob.data.shape_keys.key_blocks:
876                 bpy.ops.object.shape_key_remove()
877             bpy.ops.object.shape_key_remove()
878                
879             bpy.ops.object.mode_set(mode = cm, toggle=False)
880             removecustomprops()
881                     
882         except:
883             nothing = 0
884         
885         return {'FINISHED'}
886
887 # Oprerator Class to remove what is no more needed    
888 class ChangeObject(Operator):
889     bl_idname = "object.change_object"
890     bl_label = "Change Object"
891
892     def removematerial(self, context):
893         ob = context.object 
894         i = 0
895
896         for ms in ob.material_slots:
897             if ms.name == BProjection_Material:
898                 index = i
899             i+=1
900                 
901         ob.active_material_index = index
902         bpy.ops.object.material_slot_remove()
903     
904     def execute(self, context):
905             new_ob = context.object
906             em = bpy.data.objects[BProjection_Empty]              
907             context.scene.objects.active = bpy.data.objects[em.custom_active_object]
908             ob = context.object
909             if ob != new_ob:
910                 cm = bpy.context.object.mode
911                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
912                 
913                 bpy.ops.object.modifier_remove(modifier="Hook-Empty for BProjection") 
914     
915                 ob = context.object
916         
917                 bpy.ops.object.editmode_toggle()
918         
919                 bpy.ops.mesh.reveal()
920                                        
921                 bpy.ops.mesh.select_all(action='DESELECT')                               
922                 ob.vertex_groups.active_index = ob.vertex_groups['texture plane'].index
923                 bpy.ops.object.vertex_group_select()
924                 lo_b = [ob for ob in bpy.data.objects if ob.type == 'MESH']
925                 bpy.ops.mesh.separate(type='SELECTED')
926                 lo_a = [ob for ob in bpy.data.objects if ob.type == 'MESH']
927                 bpy.ops.object.vertex_group_remove()
928                 
929                 for i in lo_b:
930                     lo_a.remove(i)
931                 bplane = lo_a[0]
932                 
933                 bpy.ops.object.editmode_toggle()
934                 
935                 self.removematerial(context)
936                 
937                 bpy.ops.object.mode_set(mode = cm, toggle=False)
938                 
939                 shape_index = ob.active_shape_key_index
940                 
941                 for i in ob.data.shape_keys.key_blocks:
942                     bpy.ops.object.shape_key_remove()
943                 bpy.ops.object.shape_key_remove()
944                 
945                 ob.select = False
946                 
947                 bplane.select = True            
948                 context.scene.objects.active = bplane
949                 for ms in (ms for ms in bplane.material_slots if ms.name != BProjection_Material):
950                     bplane.active_material = ms.material
951                     bpy.ops.object.material_slot_remove()
952                 
953                 for gs in (gs for gs in bplane.vertex_groups if gs.name != 'texture plane'):
954                     bplane.vertex_groups.active_index = gs.index
955                     bpy.ops.object.vertex_group_remove()
956               
957                 context.scene.objects.active = new_ob
958                 cm = new_ob.mode
959                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False) 
960                 bpy.ops.object.join()
961     
962                 em.hide = False
963                 em.select = True
964                 new_ob.select = False
965                 bpy.ops.object.location_clear()
966                 bpy.ops.object.rotation_clear()
967                 bpy.ops.object.scale_clear()
968                 context.scene.objects.active = new_ob
969                 bpy.ops.object.editmode_toggle()            
970                 bpy.ops.object.hook_add_selob()
971                 bpy.ops.object.editmode_toggle()
972                 em.hide = True
973                 em.select = False
974                 new_ob.select = True
975                 em.custom_active_object = new_ob.name
976                 tmp = em.custom_c3d
977                 em.custom_c3d = False
978                 bpy.ops.object.active_view(index = shape_index-1)
979                 bpy.ops.object.mode_set(mode = cm, toggle=False)
980                         
981                 sd = context.space_data
982                 r3d = sd.region_3d 
983                 vr = r3d.view_rotation.copy()
984                 vr.invert()
985                 ob_loc = ob.location.copy()            
986                 new_ob_loc = new_ob.location.copy() 
987                 ob_loc.rotate(vr)
988                 new_ob_loc.rotate(vr)
989                 em.custom_location += Vector((ob_loc.x - new_ob_loc.x, ob_loc.y - new_ob_loc.y, 0.0))
990                 em.custom_c3d = tmp
991                     
992             return {'FINISHED'}
993
994 # Oprerator Class to rotate the view3D
995 class RotateView3D(Operator):
996     bl_idname = "view3d.rotate_view3d"
997     bl_label = "Rotate the View3D"
998     
999     first_mouse = Vector((0,0))
1000
1001     pan = Vector((0,0))
1002
1003     key = ['']
1004  
1005     first_time = True
1006     tmp_level = -1
1007     
1008     def vect_sphere(self, context, mx, my):
1009         width = context.area.regions[4].width
1010         height = context.area.regions[4].height
1011            
1012         if width >= height:
1013             ratio = height/width
1014         
1015             x = 2*mx/width
1016             y = 2*ratio*my/height
1017             
1018             x = x - 1
1019             y = y - ratio
1020         else:
1021             ratio = width/height
1022         
1023             x = 2*ratio*mx/width
1024             y = 2*my/height
1025  
1026             x = x - ratio
1027             y = y - 1
1028         
1029         z2 = 1 - x * x - y * y
1030         if z2 > 0:
1031             z= sqrt(z2)
1032         else : z=0
1033             
1034         p = Vector((x, y, z))
1035         p.normalize()
1036         return p
1037     
1038     def tracball(self, context, mx, my, origine):
1039         sd = context.space_data
1040         ob = context.object
1041         em = bpy.data.objects[BProjection_Empty]
1042             
1043         vr_b = sd.region_3d.view_rotation.copy()
1044         vr_b.invert()
1045         pos_init = sd.region_3d.view_location - origine
1046         sd.region_3d.view_location = origine
1047         
1048         v1 = self.vect_sphere(context, self.first_mouse.x, self.first_mouse.y)
1049         v2 = self.vect_sphere(context, mx, my)
1050                         
1051         axis = Vector.cross(v1,v2);
1052         angle = Vector.angle(v1,v2);
1053             
1054         q =  Quaternion(axis,-2*angle)
1055                         
1056         sd.region_3d.view_rotation *=q
1057         sd.region_3d.update()
1058         
1059         vr_a = sd.region_3d.view_rotation.copy()                           
1060         pos_init.rotate(vr_a*vr_b)            
1061         sd.region_3d.view_location =  pos_init + origine
1062         
1063         self.first_mouse = Vector((mx, my))
1064                 
1065     def modal(self, context, event):                                
1066         ob = context.object
1067         em = bpy.data.objects['Empty for BProjection'] 
1068         reg = context.area.regions[4]        
1069         if event.value == 'PRESS':
1070             self.pan = Vector((event.mouse_region_x, event.mouse_region_y))
1071                     
1072             self.key = [event.type]
1073
1074         if event.value == 'RELEASE':
1075             self.key = [''] 
1076
1077         if event.type == 'MOUSEMOVE':                        
1078             
1079             if '' in self.key:
1080                 self.tracball(context, event.mouse_region_x, event.mouse_region_y,ob.location)
1081                 align_to_view(context)
1082                 if self.first_time:
1083                     rot_ang = context.user_preferences.view.rotation_angle            
1084                     context.user_preferences.view.rotation_angle = 0
1085                     bpy.ops.view3d.view_orbit(type='ORBITLEFT')
1086                     context.user_preferences.view.rotation_angle = rot_ang   
1087                     bpy.ops.view3d.view_persportho()         
1088                     bpy.ops.view3d.view_persportho()
1089                     self.first_time = False
1090           
1091             deltax = event.mouse_region_x - round(self.pan.x)
1092             deltay = event.mouse_region_y - round(self.pan.y)          
1093
1094             if 'G' in self.key:       
1095                 sd = context.space_data              
1096                 l =  sd.region_3d
1097                 vr = l.view_rotation.copy()
1098                 vr.invert()
1099                 
1100                 v_init = Vector((0.0,0.0,1.0))
1101                 
1102                 pos = [-deltax,-deltay]
1103                 v = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)
1104                 pos = [0,0]
1105                 vbl = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)        
1106                 loc = vbl - v            
1107                 loc.rotate(vr)
1108                 em.custom_location += loc              
1109                                    
1110             if 'S' in self.key:                
1111                 s = em.custom_scale
1112                 if em.custom_linkscale:
1113                     em.custom_propscale += deltax/20
1114                 else:
1115                     em.custom_scale = [s[0] + deltax/20, s[1] + deltay/20]
1116                                           
1117             if 'Z' in self.key:                
1118                 em.custom_location.z+=deltax/10
1119                       
1120             if 'R' in self.key:
1121                 em.custom_rotation+=deltax
1122                     
1123             if 'U' in self.key:
1124                 suv = em.custom_scaleuv
1125                 if em.custom_linkscaleuv:    
1126                     em.custom_propscaleuv += deltax/50
1127                 else:
1128                     em.custom_scaleuv= [suv[0] + deltax/50 , suv[1] + deltay/50]               
1129
1130             if 'Y' in self.key:       
1131                 ouv = em.custom_offsetuv
1132                 em.custom_offsetuv = [ouv[0] - deltax/50,ouv[1] - deltay/50] 
1133
1134             self.pan = Vector((event.mouse_region_x, event.mouse_region_y))
1135             self.first_mouse = Vector((event.mouse_region_x, self.first_mouse.y))
1136                         
1137         elif event.type == 'MIDDLEMOUSE'and event.value == 'RELEASE':
1138             if self.tmp_level > -1:
1139                 for sub in context.object.modifiers:
1140                     if sub.type in ['SUBSURF','MULTIRES']:
1141                         sub.levels = self.tmp_level   
1142             
1143             return {'FINISHED'}
1144         
1145         if 'C' in self.key:
1146             clear_props(context)
1147         
1148         if 'O' in self.key:
1149             bpy.ops.object.change_object()            
1150         return {'RUNNING_MODAL'}
1151     
1152     def execute(self, context):        
1153         align_to_view(context)  
1154         
1155         return{'FINISHED'}
1156
1157     def invoke(self, context, event):
1158         context.window_manager.modal_handler_add(self)
1159         self.first_mouse = Vector((event.mouse_region_x,event.mouse_region_y))
1160         self.first_time = True
1161         for sub in context.object.modifiers:
1162             if sub.type in ['SUBSURF', 'MULTIRES']:
1163                 self.tmp_level = sub.levels
1164                 sub.levels = 0
1165         return {'RUNNING_MODAL'}
1166
1167 # Oprerator Class to pan the view3D
1168 class PanView3D(bpy.types.Operator):
1169     bl_idname = "view3d.pan_view3d"
1170     bl_label = "Pan View3D"
1171     
1172     first_mouse = Vector((0,0))
1173     tmp_level = -1
1174
1175     def modal(self, context, event):
1176         ob = context.object
1177         em = bpy.data.objects[BProjection_Empty]
1178         width = context.area.regions[4].width
1179         height = context.area.regions[4].height
1180
1181         deltax = event.mouse_region_x - self.first_mouse.x
1182         deltay = event.mouse_region_y - self.first_mouse.y                
1183         
1184         sd = context.space_data              
1185         r3d =  sd.region_3d
1186         vr = r3d.view_rotation.copy()
1187         vr.invert()
1188         
1189         v_init = Vector((0.0,0.0,1.0))
1190         
1191         pos = [deltax,deltay]
1192         v = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1193         pos = [0,0]
1194         vbl = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)        
1195         loc = vbl - v       
1196         sd.region_3d.view_location += loc         
1197         loc.rotate(vr)
1198         em.custom_location += loc
1199
1200         self.first_mouse.x = event.mouse_region_x
1201         self.first_mouse.y = event.mouse_region_y
1202
1203         if event.type == 'MIDDLEMOUSE'and event.value == 'RELEASE':
1204             if self.tmp_level > -1:
1205                 for sub in context.object.modifiers:
1206                     if sub.type in ['SUBSURF','MULTIRES']:
1207                         sub.levels = self.tmp_level
1208             return {'FINISHED'}
1209         
1210         return {'RUNNING_MODAL'}
1211                 
1212     def invoke(self, context, event):
1213         context.window_manager.modal_handler_add(self)
1214         self.first_mouse.x = event.mouse_region_x
1215         self.first_mouse.y = event.mouse_region_y   
1216         for sub in context.object.modifiers:
1217             if sub.type in ['SUBSURF', 'MULTIRES']:
1218                 self.tmp_level = sub.levels
1219                 sub.levels = 0  
1220                       
1221         return {'RUNNING_MODAL'}
1222
1223     def execute(self, context):        
1224         align_to_view(context)  
1225         
1226         return{'FINISHED'}
1227
1228 # Oprerator Class to zoom the view3D
1229 class ZoomView3D(Operator):
1230     bl_idname = "view3d.zoom_view3d"
1231     bl_label = "Zoom View3D"
1232
1233     delta = FloatProperty(
1234         name="delta",
1235         description="Delta",
1236         min=-1.0, max=1,
1237         default=1.0)
1238
1239     def invoke(self, context, event):                   
1240         ob = context.object
1241         em = bpy.data.objects[BProjection_Empty]
1242         sd = context.space_data
1243
1244         width = context.area.regions[4].width
1245         height = context.area.regions[4].height              
1246                     
1247         r3d =  sd.region_3d
1248         v_init = Vector((0.0,0.0,1.0))
1249
1250         pos = [width,height]
1251         vtr_b = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1252         pos = [0,0]
1253         vbl_b = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1254         len_b = vtr_b - vbl_b
1255        
1256         bpy.ops.view3d.zoom(delta = self.delta)
1257         r3d.update()
1258
1259         pos = [width,height]
1260         vtr_a = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1261         pos = [0,0]
1262         vbl_a = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init) 
1263         len_a = vtr_a - vbl_a
1264         
1265         fac = len_a.length/len_b.length
1266         r3d.view_location -= ob.location
1267         r3d.view_location *= fac
1268         r3d.view_location += ob.location
1269         vres = Vector((em.custom_location.x*fac,em.custom_location.y*fac,em.custom_location.z))
1270         em.custom_location = vres
1271         
1272         
1273         align_to_view(context)
1274         
1275         return {'FINISHED'}
1276
1277     def execute(self, context):        
1278         align_to_view(context)
1279         
1280         return{'FINISHED'}
1281
1282 # Oprerator Class to use numpad shortcut
1283 class PresetView3D(Operator):
1284     bl_idname = "view3d.preset_view3d"
1285     bl_label = "Preset View3D"
1286
1287     view = StringProperty(name="View", description="Select the view", default='TOP')
1288     def invoke(self, context, event):                   
1289         ob = context.object
1290         em = bpy.data.objects[BProjection_Empty]
1291         origine = ob.location
1292         sd = context.space_data
1293
1294         vr_b = sd.region_3d.view_rotation.copy()
1295         vr_b.invert()
1296         pos_init = sd.region_3d.view_location - origine
1297         sd.region_3d.view_location = origine
1298
1299         tmp = context.user_preferences.view.smooth_view
1300         context.user_preferences.view.smooth_view = 0
1301         bpy.ops.view3d.viewnumpad(type=self.view)
1302         align_to_view(context)        
1303         context.user_preferences.view.smooth_view = tmp
1304
1305         vr_a = sd.region_3d.view_rotation.copy()                           
1306         pos_init.rotate(vr_a*vr_b)            
1307         sd.region_3d.view_location =  pos_init + origine              
1308                     
1309         return {'FINISHED'}
1310
1311 def register():
1312     bpy.utils.register_module(__name__)
1313     createcustomprops(bpy.context)
1314
1315 def unregister():
1316     bpy.utils.unregister_module(__name__)
1317
1318 if __name__ == "__main__":
1319     register()