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