[Bf-extensions-cvs] [5be927b2] master: BlenderKit: split finally drag-drop from asset bar

Vilem Duha noreply at git.blender.org
Mon Jul 12 21:20:18 CEST 2021


Commit: 5be927b2f67d7ca3f453fe598f5c37a506be91ef
Author: Vilem Duha
Date:   Mon Jul 12 20:45:35 2021 +0200
Branches: master
https://developer.blender.org/rBA5be927b2f67d7ca3f453fe598f5c37a506be91ef

BlenderKit: split finally drag-drop from asset bar

the new operator is now used.
-proper support for alll object types
click and drag - drop for all assets
optimize drawing of asset  bar, should be faster.
fix a bug when rating requests didn't return proper results
asset popup now has drag-drop button and can be closed with X button
big cleanup of assetbar code

===================================================================

M	blenderkit/__init__.py
M	blenderkit/download.py
M	blenderkit/paths.py
M	blenderkit/ratings_utils.py
M	blenderkit/ui.py
M	blenderkit/ui_bgl.py
M	blenderkit/ui_panels.py

===================================================================

diff --git a/blenderkit/__init__.py b/blenderkit/__init__.py
index 37fa907f..7fc744a0 100644
--- a/blenderkit/__init__.py
+++ b/blenderkit/__init__.py
@@ -304,7 +304,19 @@ def asset_type_callback(self, context):
     return items
 
 
+def run_drag_drop_update(self, context):
+    if self.drag_init_button:
+        ui_props = bpy.context.scene.blenderkitUI
+        # ctx = utils.get_fake_context(bpy.context)
+
+        bpy.ops.view3d.close_popup_button('INVOKE_DEFAULT')
+        bpy.ops.view3d.asset_drag_drop('INVOKE_DEFAULT', asset_search_index=ui_props.active_index + ui_props.scrolloffset)
+
+        self.drag_init_button = False
+
+
 class BlenderKitUIProps(PropertyGroup):
+
     down_up: EnumProperty(
         name="Download vs Upload",
         items=(
@@ -370,6 +382,10 @@ class BlenderKitUIProps(PropertyGroup):
 
     dragging: BoolProperty(name="Dragging", default=False)
     drag_init: BoolProperty(name="Drag Initialisation", default=False)
+    drag_init_button: BoolProperty(name="Drag Initialisation from button",
+                                   default=False,
+                                   description="Click or drag into scene for download.",
+                                   update = run_drag_drop_update)
     drag_length: IntProperty(name="Drag length", default=0)
     draw_drag_image: BoolProperty(name="Draw Drag Image", default=False)
     draw_snapped_bounds: BoolProperty(name="Draw Snapped Bounds", default=False)
diff --git a/blenderkit/download.py b/blenderkit/download.py
index a217cc83..4d7cfa52 100644
--- a/blenderkit/download.py
+++ b/blenderkit/download.py
@@ -1271,7 +1271,7 @@ class BlenderkitDownloadOperator(bpy.types.Operator):
 
     resolution: EnumProperty(
         items=available_resolutions_callback,
-        default=0,
+        default=512,
         description='Replace resolution'
     )
 
diff --git a/blenderkit/paths.py b/blenderkit/paths.py
index 12b815e5..b9847be2 100644
--- a/blenderkit/paths.py
+++ b/blenderkit/paths.py
@@ -96,9 +96,19 @@ def get_categories_filepath():
     tempdir = get_temp_dir()
     return os.path.join(tempdir, 'categories.json')
 
-
+dirs_exist_dict = {}#cache these results since this is used very often
 def get_temp_dir(subdir=None):
+
     user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
+    #first try cached results
+    if subdir is not None:
+        d = dirs_exist_dict.get(subdir)
+        if d is not None:
+            return d
+    else:
+        d = dirs_exist_dict.get('top')
+        if d is not None:
+            return d
 
     # tempdir = user_preferences.temp_dir
     tempdir = os.path.join(tempfile.gettempdir(), 'bkit_temp')
@@ -107,10 +117,14 @@ def get_temp_dir(subdir=None):
     try:
         if not os.path.exists(tempdir):
             os.makedirs(tempdir)
+        dirs_exist_dict['top'] = tempdir
+
         if subdir is not None:
             tempdir = os.path.join(tempdir, subdir)
             if not os.path.exists(tempdir):
                 os.makedirs(tempdir)
+            dirs_exist_dict[subdir] = tempdir
+
         cleanup_old_folders()
     except:
         tasks_queue.add_task((ui.add_report, ('Cache directory not found. Resetting Cache folder path.',)))
@@ -379,9 +393,10 @@ def get_addon_file(subpath=''):
     # fpath = os.path.join(p, subpath)
     return os.path.join(script_path, subpath)
 
+script_path = os.path.dirname(os.path.realpath(__file__))
 
 def get_addon_thumbnail_path(name):
-    script_path = os.path.dirname(os.path.realpath(__file__))
+    global script_path
     # fpath = os.path.join(p, subpath)
     ext = name.split('.')[-1]
     next = ''
diff --git a/blenderkit/ratings_utils.py b/blenderkit/ratings_utils.py
index fe2643e1..9a282944 100644
--- a/blenderkit/ratings_utils.py
+++ b/blenderkit/ratings_utils.py
@@ -96,19 +96,19 @@ def get_rating(asset_id, headers):
     url = paths.get_api_url() + 'assets/' + asset_id + '/rating/'
     params = {}
     r = rerequests.get(url, params=params, verify=True, headers=headers)
-    print(r.text)
-    rj = r.json()
-    ratings = {}
-    # store ratings - send them to task queue
-    for r in rj['results']:
-        ratings[r['ratingType']] = r['score']
-        tasks_queue.add_task((store_rating_local,(asset_id, r['ratingType'], r['score'])))
-        # store_rating_local(asset_id, type = r['ratingType'], value = r['score'])
-
-    if len(rj['results'])==0:
-        # store empty ratings too, so that server isn't checked repeatedly
-        tasks_queue.add_task((store_rating_local_empty,(asset_id,)))
-    return ratings
+    if r.status_code == 200:
+        rj = r.json()
+        ratings = {}
+        # store ratings - send them to task queue
+        for r in rj['results']:
+            ratings[r['ratingType']] = r['score']
+            tasks_queue.add_task((store_rating_local,(asset_id, r['ratingType'], r['score'])))
+            # store_rating_local(asset_id, type = r['ratingType'], value = r['score'])
+
+        if len(rj['results'])==0:
+            # store empty ratings too, so that server isn't checked repeatedly
+            tasks_queue.add_task((store_rating_local_empty,(asset_id,)))
+        # return ratings
 
 
 def get_rating_local(asset_id):
diff --git a/blenderkit/ui.py b/blenderkit/ui.py
index da1e6f29..c9d17d64 100644
--- a/blenderkit/ui.py
+++ b/blenderkit/ui.py
@@ -40,6 +40,14 @@ import os
 
 import logging
 
+PROFILING = False
+if PROFILING:
+    import cProfile
+    profiler = cProfile.Profile()
+
+draw_time = 0
+eval_time = 0
+
 bk_logger = logging.getLogger('blenderkit')
 
 handler_2d = None
@@ -371,34 +379,62 @@ def draw_tooltip_with_author(asset_data, x, y):
 
     img = get_large_thumbnail_image(asset_data)
     gimg = None
-    author_text = ''
-
-    if bpy.context.window_manager.get('bkit authors') is not None:
-        a = bpy.context.window_manager['bkit authors'].get(asset_data['author']['id'])
-        if a is not None and a != '':
-            if a.get('gravatarImg') is not None:
-                gimg = utils.get_hidden_image(a['gravatarImg'], a['gravatarHash'])
-
-            if len(a['firstName'])>0 or len(a['lastName'])>0:
-                author_text = f"by {a['firstName']} {a['lastName']}"
-
-    aname = asset_data['displayName']
-    aname = aname[0].upper() + aname[1:]
-    if len(aname) > 36:
-        aname = f"{aname[:33]}..."
-
-    rc = asset_data.get('ratingsCount')
-    show_rating_threshold = 0
-    rcount = 0
-    quality = '-'
-    if rc:
-        rcount = min(rc.get('quality',0), rc.get('workingHours',0))
-    if rcount > show_rating_threshold:
-        quality = round(asset_data['ratingsAverage'].get('quality'))
-
-    draw_tooltip(x, y, name=aname, author=author_text, quality=quality, img=img,
+    tooltip_data = asset_data.get('tooltip_data')
+    if tooltip_data is None:
+        author_text = ''
+
+        if bpy.context.window_manager.get('bkit authors') is not None:
+            a = bpy.context.window_manager['bkit authors'].get(asset_data['author']['id'])
+            if a is not None and a != '':
+                if a.get('gravatarImg') is not None:
+                    gimg = utils.get_hidden_image(a['gravatarImg'], a['gravatarHash']).name
+
+                if len(a['firstName'])>0 or len(a['lastName'])>0:
+                    author_text = f"by {a['firstName']} {a['lastName']}"
+
+        aname = asset_data['displayName']
+        aname = aname[0].upper() + aname[1:]
+        if len(aname) > 36:
+            aname = f"{aname[:33]}..."
+
+        rc = asset_data.get('ratingsCount')
+        show_rating_threshold = 0
+        rcount = 0
+        quality = '-'
+        if rc:
+            rcount = min(rc.get('quality',0), rc.get('workingHours',0))
+        if rcount > show_rating_threshold:
+            quality = round(asset_data['ratingsAverage'].get('quality'))
+        tooltip_data={
+            'aname': aname,
+            'author_text': author_text,
+            'quality':quality,
+            'gimg': gimg
+        }
+        asset_data['tooltip_data'] = tooltip_data
+    gimg = tooltip_data['gimg']
+    if gimg is not None:
+        gimg = bpy.data.images[gimg]
+
+    draw_tooltip(x, y, name=tooltip_data['aname'],
+                 author=tooltip_data['author_text'],
+                 quality=tooltip_data['quality'],
+                 img=img,
                  gravatar=gimg)
 
+profiler_step = 0
+def draw_callback_2d_profiled(self,context):
+    global profiler,profiler_step
+    result = profiler.runcall(draw_callback_2d,self,context)
+    if profiler_step >= 1000:
+
+        profiler.print_stats(sort = 'cumulative')
+        profiler = cProfile.Profile()
+        profiler_step = 0
+    profiler_step+=1
+    if profiler_step%10 ==0:
+        print(profiler_step)
+    return
 
 def draw_callback_2d(self, context):
     if not utils.guard_from_crash():
@@ -556,8 +592,8 @@ def get_large_thumbnail_image(asset_data):
     iname = utils.previmg_name(ui_props.active_index, fullsize=True)
     directory = paths.get_temp_dir('%s_search' % mappingdict[ui_props.asset_type])
     tpath = os.path.join(directory, asset_data['thumbnail'])
-    if asset_data['assetType'] == 'hdr':
-        tpath = os.path.join(directory, asset_data['thumbnail'])
+    # if asset_data['assetType'] == 'hdr':
+    #     tpath = os.path.join(directory, asset_data['thumbnail'])
     if not asset_data['thumbnail']:
         tpath = paths.get_addon_thumbnail_path('thumbnail_not_available.jpg')
 
@@ -573,7 +609,7 @@ def draw_asset_bar(self, context):
     s = bpy.context.scene
     ui_props = context.scene.blenderkitUI
     user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
-
+    is_validator = utils.profile_is_validator()
     r = self.region
     # hc = bpy.context.preferences.themes[0].view_3d.space.header
     # hc = bpy.context.preferences.themes[0].user_interface.wcol_menu_back.inner
@@ -641,7 +677,7 @@ def draw_asset_bar(self, context):
                     ui_bgl.draw_image(ui_props.bar_x + ui_props.bar_width - 25,
                                       arrow_y, 25,
                                       ui_props.thumb_size, img1, 1)
-
+            ar = context.window_manager.get('asset ratings')
      

@@ Diff output truncated at 10240 characters. @@



More information about the Bf-extensions-cvs mailing list