Bprojection: now the keymap is not related to the line number anymore
[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.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=(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  = (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             # XXX, this isnt future proof, DON'T USE INDEX's - campbell                    
824             km = bpy.data.window_managers['WinMan'].keyconfigs['Blender'].keymaps['3D View']
825             l = ['view3d.rotate','view3d.move','view3d.zoom','view3d.viewnumpad','MOUSE','KEYBOARD','MIDDLEMOUSE','WHEELINMOUSE','WHEELOUTMOUSE','NUMPAD_1','NUMPAD_3','NUMPAD_7']
826             for kmi in km.keymap_items:
827                 if kmi.idname in l and kmi.map_type in l and kmi.type in l:
828                     try:
829                         p = kmi.properties.delta
830                         if p == -1 or p == 1:
831                             kmi.idname = 'view3d.zoom_view3d'
832                             kmi.properties.delta = p
833                     except:
834                         try:
835                             p = kmi.properties.type
836                             if kmi.shift == False :
837                                 kmi.idname = 'view3d.preset_view3d'
838                                 kmi.properties.view = p
839                         except:
840                             if kmi.idname == 'view3d.rotate':
841                                 kmi.idname = 'view3d.rotate_view3d'  
842                             if kmi.idname == 'view3d.move':
843                                 kmi.idname = 'view3d.pan_view3d' 
844                                                        
845             km = context.window_manager.keyconfigs.default.keymaps['Image Paint']
846             kmi = km.keymap_items.new("object.intuitivescale", 'LEFTMOUSE', 'PRESS', shift=True)
847                         
848             align_to_view(context)
849             
850             context.space_data.cursor_location = em.location
851             
852             bpy.ops.object.mode_set(mode = cm, toggle=False)
853             bpy.data.objects[BProjection_Empty].custom_active_object = context.object.name
854             
855         return {'FINISHED'}
856
857 # Oprerator Class to remove what is no more needed    
858 class RemoveBProjectionPlane(Operator):
859     bl_idname = "object.removebprojectionplane"
860     bl_label = "Configure"
861
862     def removematerial(self, context):
863         ob = context.object 
864         i = 0
865
866         for ms in ob.material_slots:
867             if ms.name == BProjection_Material:
868                 index = i
869             i+=1
870                 
871         ob.active_material_index = index
872         bpy.ops.object.material_slot_remove()
873     
874     def execute(self, context):
875         try:               
876             cm = bpy.context.object.mode
877             bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
878             
879             context.space_data.show_relationship_lines = True
880             
881             bpy.ops.object.modifier_remove(modifier="Hook-Empty for BProjection")
882             
883             self.removematerial(context)
884
885             ob = context.object
886     
887             bpy.ops.object.editmode_toggle()
888     
889             bpy.ops.mesh.reveal()
890                                    
891             bpy.ops.mesh.select_all(action='DESELECT')                    
892             
893             ob.vertex_groups.active_index = ob.vertex_groups['texture plane'].index
894             bpy.ops.object.vertex_group_select()
895             bpy.ops.mesh.delete()
896             bpy.ops.object.vertex_group_remove()
897     
898             bpy.ops.object.editmode_toggle()
899    
900             ob.select = False
901                 
902             em = bpy.data.objects[BProjection_Empty]
903             context.scene.objects.active = em
904             em.hide = False
905             em.select = True
906             bpy.ops.object.delete()
907     
908             context.scene.objects.active = ob
909             ob.select = True
910             
911             reinitkey()
912                         
913             '''tmp = context.object
914             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):
915                 context.scene.objects.active = ob
916                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False) 
917             
918             context.scene.objects.active = tmp'''
919             ob = context.object           
920             
921             
922             for i in ob.data.shape_keys.key_blocks:
923                 bpy.ops.object.shape_key_remove()
924             bpy.ops.object.shape_key_remove()
925                
926             bpy.ops.object.mode_set(mode = cm, toggle=False)
927             removecustomprops()
928                     
929         except:
930             nothing = 0
931         
932         return {'FINISHED'}
933
934 def reinitkey():
935     km = bpy.data.window_managers['WinMan'].keyconfigs['Blender'].keymaps['3D View']
936     l = ['view3d.zoom_view3d','view3d.preset_view3d','view3d.rotate_view3d','view3d.pan_view3d','MOUSE','KEYBOARD','MIDDLEMOUSE','WHEELINMOUSE','WHEELOUTMOUSE','NUMPAD_1','NUMPAD_3','NUMPAD_7']
937     for kmi in km.keymap_items:
938         if kmi.idname in l and kmi.map_type in l and kmi.type in l:
939             try:
940                 p = kmi.properties.delta
941                 if p == -1 or p == 1:
942                     kmi.idname = 'view3d.zoom'
943                     kmi.properties.delta = p
944             except:
945                 try:
946                     p = kmi.properties.view
947                     if kmi.shift == False :
948                         kmi.idname = 'view3d.viewnumpad'
949                         kmi.properties.type = p
950                 except:
951                     if kmi.idname == 'view3d.rotate_view3d':
952                         kmi.idname = 'view3d.rotate'  
953                     if kmi.idname == 'view3d.pan_view3d':
954                         kmi.idname = 'view3d.move'            
955             
956     km = bpy.context.window_manager.keyconfigs.default.keymaps['Image Paint']
957     #to do
958     for kmi in (kmi for kmi in km.keymap_items if kmi.idname in {"object.intuitivescale", }):
959             km.keymap_items.remove(kmi)
960
961 # Oprerator Class to remove what is no more needed    
962 class ChangeObject(Operator):
963     bl_idname = "object.change_object"
964     bl_label = "Change Object"
965
966     def removematerial(self, context):
967         ob = context.object 
968         i = 0
969
970         for ms in ob.material_slots:
971             if ms.name == BProjection_Material:
972                 index = i
973             i+=1
974                 
975         ob.active_material_index = index
976         bpy.ops.object.material_slot_remove()
977     
978     def execute(self, context):
979             new_ob = context.object
980             em = bpy.data.objects[BProjection_Empty]              
981             context.scene.objects.active = bpy.data.objects[em.custom_active_object]
982             ob = context.object
983             if ob != new_ob:
984                 cm = bpy.context.object.mode
985                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False)
986                 
987                 bpy.ops.object.modifier_remove(modifier="Hook-Empty for BProjection") 
988     
989                 ob = context.object
990         
991                 bpy.ops.object.editmode_toggle()
992         
993                 bpy.ops.mesh.reveal()
994                                        
995                 bpy.ops.mesh.select_all(action='DESELECT')                               
996                 ob.vertex_groups.active_index = ob.vertex_groups['texture plane'].index
997                 bpy.ops.object.vertex_group_select()
998                 lo_b = [ob for ob in bpy.data.objects if ob.type == 'MESH']
999                 bpy.ops.mesh.separate(type='SELECTED')
1000                 lo_a = [ob for ob in bpy.data.objects if ob.type == 'MESH']
1001                 bpy.ops.object.vertex_group_remove()
1002                 
1003                 for i in lo_b:
1004                     lo_a.remove(i)
1005                 bplane = lo_a[0]
1006                 
1007                 bpy.ops.object.editmode_toggle()
1008                 
1009                 self.removematerial(context)
1010                 
1011                 bpy.ops.object.mode_set(mode = cm, toggle=False)
1012                 
1013                 shape_index = ob.active_shape_key_index
1014                 
1015                 for i in ob.data.shape_keys.key_blocks:
1016                     bpy.ops.object.shape_key_remove()
1017                 bpy.ops.object.shape_key_remove()
1018                 
1019                 ob.select = False
1020                 
1021                 bplane.select = True            
1022                 context.scene.objects.active = bplane
1023                 for ms in (ms for ms in bplane.material_slots if ms.name != BProjection_Material):
1024                     bplane.active_material = ms.material
1025                     bpy.ops.object.material_slot_remove()
1026                 
1027                 for gs in (gs for gs in bplane.vertex_groups if gs.name != 'texture plane'):
1028                     bplane.vertex_groups.active_index = gs.index
1029                     bpy.ops.object.vertex_group_remove()
1030               
1031                 context.scene.objects.active = new_ob
1032                 cm = new_ob.mode
1033                 bpy.ops.object.mode_set(mode = 'OBJECT', toggle=False) 
1034                 bpy.ops.object.join()
1035     
1036                 em.hide = False
1037                 em.select = True
1038                 new_ob.select = False
1039                 bpy.ops.object.location_clear()
1040                 bpy.ops.object.rotation_clear()
1041                 bpy.ops.object.scale_clear()
1042                 context.scene.objects.active = new_ob
1043                 bpy.ops.object.editmode_toggle()            
1044                 bpy.ops.object.hook_add_selob()
1045                 bpy.ops.object.editmode_toggle()
1046                 em.hide = True
1047                 em.select = False
1048                 new_ob.select = True
1049                 em.custom_active_object = new_ob.name
1050                 tmp = em.custom_c3d
1051                 em.custom_c3d = False
1052                 bpy.ops.object.active_view(index = shape_index-1)
1053                 bpy.ops.object.mode_set(mode = cm, toggle=False)
1054                         
1055                 sd = context.space_data
1056                 r3d = sd.region_3d 
1057                 vr = r3d.view_rotation.copy()
1058                 vr.invert()
1059                 ob_loc = ob.location.copy()            
1060                 new_ob_loc = new_ob.location.copy() 
1061                 ob_loc.rotate(vr)
1062                 new_ob_loc.rotate(vr)
1063                 em.custom_location += Vector((ob_loc.x - new_ob_loc.x, ob_loc.y - new_ob_loc.y, 0.0))
1064                 em.custom_c3d = tmp
1065                     
1066             return {'FINISHED'}
1067
1068 # Oprerator Class to rotate the view3D
1069 class RotateView3D(Operator):
1070     bl_idname = "view3d.rotate_view3d"
1071     bl_label = "Rotate the View3D"
1072     
1073     first_mouse = Vector((0,0))
1074
1075     pan = Vector((0,0))
1076
1077     key = ['']
1078     block = 0
1079  
1080     first_time = True
1081     tmp_level = -1
1082
1083     def vect_sphere(self, context, mx, my):
1084         width = context.area.regions[4].width
1085         height = context.area.regions[4].height
1086            
1087         if width >= height:
1088             ratio = height/width
1089         
1090             x = 2*mx/width
1091             y = 2*ratio*my/height
1092             
1093             x = x - 1
1094             y = y - ratio
1095         else:
1096             ratio = width/height
1097         
1098             x = 2*ratio*mx/width
1099             y = 2*my/height
1100  
1101             x = x - ratio
1102             y = y - 1
1103         
1104         z2 = 1 - x * x - y * y
1105         if z2 > 0:
1106             z= sqrt(z2)
1107         else : z=0
1108             
1109         p = Vector((x, y, z))
1110         p.normalize()
1111         return p
1112     
1113     def tracball(self, context, mx, my, origine):
1114         sd = context.space_data
1115         ob = context.object
1116         em = bpy.data.objects[BProjection_Empty]
1117             
1118         vr_b = sd.region_3d.view_rotation.copy()
1119         vr_b.invert()
1120         pos_init = sd.region_3d.view_location - origine
1121         sd.region_3d.view_location = origine
1122         
1123         v1 = self.vect_sphere(context, self.first_mouse.x, self.first_mouse.y)
1124         v2 = self.vect_sphere(context, mx, my)
1125                         
1126         axis = Vector.cross(v1,v2);
1127         angle = Vector.angle(v1,v2);
1128             
1129         q =  Quaternion(axis,-2*angle)
1130                         
1131         sd.region_3d.view_rotation *=q
1132         sd.region_3d.update()
1133         
1134         vr_a = sd.region_3d.view_rotation.copy()                           
1135         pos_init.rotate(vr_a*vr_b)            
1136         sd.region_3d.view_location =  pos_init + origine
1137         
1138         self.first_mouse = Vector((mx, my))
1139                 
1140     def modal(self, context, event):                                
1141         ob = context.object
1142         em = bpy.data.objects['Empty for BProjection'] 
1143         reg = context.area.regions[4]        
1144             
1145                     
1146         if event.type not in {'MOUSEMOVE','INBETWEEN_MOUSEMOVE'}:
1147             self.pan = Vector((event.mouse_region_x, event.mouse_region_y))
1148             self.key = [event.type]
1149             self.block = 1
1150             
1151         if event.value == 'RELEASE':
1152             if self.tmp_level > -1:
1153                 for sub in context.object.modifiers:
1154                     if sub.type in ['SUBSURF','MULTIRES']:
1155                         sub.levels = self.tmp_level 
1156             return {'FINISHED'}
1157
1158         if event.type == 'MOUSEMOVE':                        
1159             if self.block == 0:
1160                 self.tracball(context, event.mouse_region_x, event.mouse_region_y,ob.location)
1161                 align_to_view(context)
1162                 #to unlock the camera
1163                 if self.first_time:                    
1164                     rot_ang = context.user_preferences.view.rotation_angle            
1165                     context.user_preferences.view.rotation_angle = 0
1166                     bpy.ops.view3d.view_orbit(type='ORBITLEFT')
1167                     context.user_preferences.view.rotation_angle = rot_ang   
1168                     bpy.ops.view3d.view_persportho()         
1169                     bpy.ops.view3d.view_persportho()
1170                     self.first_time = False
1171             else:          
1172                 deltax = event.mouse_region_x - round(self.pan.x)
1173                 deltay = event.mouse_region_y - round(self.pan.y)          
1174      
1175                 if 'G' in self.key:     
1176                     sd = context.space_data              
1177                     l =  sd.region_3d
1178                     vr = l.view_rotation.copy()
1179                     vr.invert()
1180                     
1181                     v_init = Vector((0.0,0.0,1.0))
1182                     
1183                     pos = [-deltax,-deltay]
1184                     v = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)
1185                     pos = [0,0]
1186                     vbl = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)        
1187                     loc = vbl - v 
1188               
1189                     loc.rotate(vr)
1190                     em.custom_location += loc              
1191                                        
1192                 if 'S' in self.key:                
1193                     s = em.custom_scale
1194                     if em.custom_linkscale:
1195                         em.custom_propscale += deltax/20
1196                     else:
1197                         em.custom_scale = [s[0] + deltax/20, s[1] + deltay/20]
1198                                               
1199                 if 'Z' in self.key:                
1200                     em.custom_location.z+=deltax/10
1201                           
1202                 if 'R' in self.key:
1203                     em.custom_rotation+=deltax
1204                         
1205                 if 'U' in self.key:
1206                     suv = em.custom_scaleuv
1207                     if em.custom_linkscaleuv:    
1208                         em.custom_propscaleuv += deltax/50
1209                     else:
1210                         em.custom_scaleuv= [suv[0] + deltax/50 , suv[1] + deltay/50]               
1211     
1212                 if 'Y' in self.key:       
1213                     ouv = em.custom_offsetuv
1214                     em.custom_offsetuv = [ouv[0] - deltax/50,ouv[1] - deltay/50] 
1215     
1216                 self.pan = Vector((event.mouse_region_x, event.mouse_region_y))
1217         
1218         if 'C' in self.key:
1219             clear_props(context)
1220         
1221         if 'O' in self.key:
1222             bpy.ops.object.change_object()           
1223         return {'RUNNING_MODAL'}
1224     
1225     def execute(self, context):        
1226         align_to_view(context)  
1227         
1228         return{'FINISHED'}
1229
1230     def invoke(self, context, event):
1231         bpy.data.objects['Empty for BProjection']
1232         context.window_manager.modal_handler_add(self)
1233         self.first_mouse = Vector((event.mouse_region_x,event.mouse_region_y))
1234         self.first_time = True
1235         for sub in context.object.modifiers:
1236             if sub.type in ['SUBSURF', 'MULTIRES']:
1237                 self.tmp_level = sub.levels
1238                 if sub.levels - self.tmp_level <0:
1239                     sub.levels = 0
1240                 else:
1241                     sub.levels += bpy.context.object.custom_fnlevel
1242         return {'RUNNING_MODAL'}
1243             
1244
1245 # Oprerator Class to pan the view3D
1246 class PanView3D(bpy.types.Operator):
1247     bl_idname = "view3d.pan_view3d"
1248     bl_label = "Pan View3D"
1249     
1250     first_mouse = Vector((0,0))
1251     tmp_level = -1
1252
1253     def modal(self, context, event):
1254         ob = context.object
1255         em = bpy.data.objects[BProjection_Empty]
1256         width = context.area.regions[4].width
1257         height = context.area.regions[4].height
1258
1259         deltax = event.mouse_region_x - self.first_mouse.x
1260         deltay = event.mouse_region_y - self.first_mouse.y                
1261         
1262         sd = context.space_data              
1263         r3d =  sd.region_3d
1264         vr = r3d.view_rotation.copy()
1265         vr.invert()
1266         
1267         v_init = Vector((0.0,0.0,1.0))
1268         
1269         pos = [deltax,deltay]
1270         v = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1271         pos = [0,0]
1272         vbl = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)        
1273         loc = vbl - v       
1274         sd.region_3d.view_location += loc         
1275         loc.rotate(vr)
1276         em.custom_location += loc
1277
1278         self.first_mouse.x = event.mouse_region_x
1279         self.first_mouse.y = event.mouse_region_y
1280
1281         if event.type == 'MIDDLEMOUSE'and event.value == 'RELEASE':
1282             if self.tmp_level > -1:
1283                 for sub in context.object.modifiers:
1284                     if sub.type in ['SUBSURF','MULTIRES']:
1285                         sub.levels = self.tmp_level
1286             return {'FINISHED'}
1287         
1288         return {'RUNNING_MODAL'}
1289                 
1290     def invoke(self, context, event):
1291         bpy.data.objects['Empty for BProjection']    
1292         context.window_manager.modal_handler_add(self)
1293         self.first_mouse.x = event.mouse_region_x
1294         self.first_mouse.y = event.mouse_region_y   
1295         for sub in context.object.modifiers:
1296             if sub.type in ['SUBSURF', 'MULTIRES']:
1297                 self.tmp_level = sub.levels
1298                 if sub.levels - self.tmp_level <0:
1299                     sub.levels = 0
1300                 else:
1301                     sub.levels += bpy.context.object.custom_fnlevel 
1302                       
1303         return {'RUNNING_MODAL'}
1304         
1305     def execute(self, context):        
1306         align_to_view(context)  
1307         
1308         return{'FINISHED'}
1309
1310 # Oprerator Class to zoom the view3D
1311 class ZoomView3D(Operator):
1312     bl_idname = "view3d.zoom_view3d"
1313     bl_label = "Zoom View3D"
1314
1315     delta = FloatProperty(
1316         name="delta",
1317         description="Delta",
1318         min=-1.0, max=1,
1319         default=1.0)
1320
1321     def invoke(self, context, event):                   
1322         ob = context.object
1323         em = bpy.data.objects[BProjection_Empty]
1324         sd = context.space_data
1325
1326         width = context.area.regions[4].width
1327         height = context.area.regions[4].height              
1328                     
1329         r3d =  sd.region_3d
1330         v_init = Vector((0.0,0.0,1.0))
1331
1332         pos = [width,height]
1333         vtr_b = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1334         pos = [0,0]
1335         vbl_b = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1336         len_b = vtr_b - vbl_b
1337        
1338         bpy.ops.view3d.zoom(delta = self.delta)
1339         r3d.update()
1340
1341         pos = [width,height]
1342         vtr_a = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
1343         pos = [0,0]
1344         vbl_a = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init) 
1345         len_a = vtr_a - vbl_a
1346         
1347         fac = len_a.length/len_b.length
1348         r3d.view_location -= ob.location
1349         r3d.view_location *= fac
1350         r3d.view_location += ob.location
1351         vres = Vector((em.custom_location.x*fac,em.custom_location.y*fac,em.custom_location.z))
1352         em.custom_location = vres
1353         
1354         
1355         align_to_view(context)
1356         
1357         return {'FINISHED'}
1358
1359     def execute(self, context):        
1360         align_to_view(context)
1361         
1362         return{'FINISHED'}
1363
1364 # Oprerator Class to use numpad shortcut
1365 class PresetView3D(Operator):
1366     bl_idname = "view3d.preset_view3d"
1367     bl_label = "Preset View3D"
1368
1369     view = StringProperty(name="View", description="Select the view", default='TOP')
1370     def invoke(self, context, event):                   
1371         ob = context.object
1372         em = bpy.data.objects[BProjection_Empty]
1373         origine = ob.location
1374         sd = context.space_data
1375
1376         vr_b = sd.region_3d.view_rotation.copy()
1377         vr_b.invert()
1378         pos_init = sd.region_3d.view_location - origine
1379         sd.region_3d.view_location = origine
1380
1381         tmp = context.user_preferences.view.smooth_view
1382         context.user_preferences.view.smooth_view = 0
1383         bpy.ops.view3d.viewnumpad(type=self.view)
1384         align_to_view(context)        
1385         context.user_preferences.view.smooth_view = tmp
1386
1387         vr_a = sd.region_3d.view_rotation.copy()                           
1388         pos_init.rotate(vr_a*vr_b)            
1389         sd.region_3d.view_location =  pos_init + origine              
1390                     
1391         return {'FINISHED'}
1392
1393 @persistent
1394 def load_handler(dummy):
1395     reinitkey()
1396
1397 def register():
1398     bpy.utils.register_module(__name__)
1399     createcustomprops(bpy.context)
1400     bpy.app.handlers.load_post.append(load_handler)
1401
1402 def unregister():
1403     bpy.utils.unregister_module(__name__)
1404
1405 if __name__ == "__main__":
1406     register()