Newer
Older
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from blenderkit import paths, ratings, utils, search, upload, ui_bgl, download, bg_blender, colors, tasks_queue, \
ui_panels, icons, ratings_utils
import bpy
import math, random
from bpy.props import (
BoolProperty,
StringProperty,
IntProperty,
FloatVectorProperty
)
from bpy_extras import view3d_utils
import mathutils
from mathutils import Vector
import time
bk_logger = logging.getLogger('blenderkit')
handler_2d = None
handler_3d = None
active_area_pointer = None
active_window_pointer = None
active_region_pointer = None
mappingdict = {
'MODEL': 'model',
'SCENE': 'scene',
'MATERIAL': 'material',
'TEXTURE': 'texture',
'BRUSH': 'brush'
}
verification_icons = {
'ready': 'vs_ready.png',
'deleted': 'vs_deleted.png',
'uploaded': 'vs_uploaded.png',
'uploading': 'vs_uploading.png',
'validated': None,
}
# class UI_region():
# def _init__(self, parent = None, x = 10,y = 10 , width = 10, height = 10, img = None, col = None):
def get_approximate_text_width(st):
size = 10
for s in st:
if s in 'i|':
size += 2
elif s in ' ':
size += 4
elif s in 'sfrt':
size += 5
elif s in 'ceghkou':
size += 6
elif s in 'PadnBCST3E':
size += 7
elif s in 'GMODVXYZ':
size += 8
elif s in 'w':
size += 9
elif s in 'm':
size += 10
else:
size += 7
return size # Convert to picas
def add_report(text='', timeout=5, color=colors.GREEN):
global reports
# check for same reports and just make them longer by the timeout.
for old_report in reports:
if old_report.text == text:
old_report.timeout = old_report.age + timeout
return
report = Report(text=text, timeout=timeout, color=color)
reports.append(report)
class Report():
def __init__(self, text='', timeout=5, color=(.5, 1, .5, 1)):
self.text = text
self.timeout = timeout
self.start_time = time.time()
self.color = color
self.draw_color = color
self.age = 0
def fade(self):
fade_time = 1
self.age = time.time() - self.start_time
if self.age + fade_time > self.timeout:
alpha_multiplier = (self.timeout - self.age) / fade_time
self.draw_color = (self.color[0], self.color[1], self.color[2], self.color[3] * alpha_multiplier)
if self.age > self.timeout:
global reports
try:
reports.remove(self)
except Exception as e:
pass;
def draw(self, x, y):
if bpy.context.area.as_pointer() == active_area_pointer:
ui_bgl.draw_text(self.text, x, y + 8, 16, self.draw_color)
def get_asset_under_mouse(mousex, mousey):
s = bpy.context.scene
ui_props = bpy.context.scene.blenderkitUI
r = bpy.context.region
search_results = wm.get('search results')
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
if search_results is not None:
h_draw = min(ui_props.hcount, math.ceil(len(search_results) / ui_props.wcount))
for b in range(0, h_draw):
w_draw = min(ui_props.wcount, len(search_results) - b * ui_props.wcount - ui_props.scrolloffset)
for a in range(0, w_draw):
x = ui_props.bar_x + a * (ui_props.margin + ui_props.thumb_size) + ui_props.margin + ui_props.drawoffset
y = ui_props.bar_y - ui_props.margin - (ui_props.thumb_size + ui_props.margin) * (b + 1)
w = ui_props.thumb_size
h = ui_props.thumb_size
if x < mousex < x + w and y < mousey < y + h:
return a + ui_props.wcount * b + ui_props.scrolloffset
# return search_results[a]
return -3
def draw_bbox(location, rotation, bbox_min, bbox_max, progress=None, color=(0, 1, 0, 1)):
ui_props = bpy.context.scene.blenderkitUI
rotation = mathutils.Euler(rotation)
smin = Vector(bbox_min)
smax = Vector(bbox_max)
v0 = Vector(smin)
v1 = Vector((smax.x, smin.y, smin.z))
v2 = Vector((smax.x, smax.y, smin.z))
v3 = Vector((smin.x, smax.y, smin.z))
v4 = Vector((smin.x, smin.y, smax.z))
v5 = Vector((smax.x, smin.y, smax.z))
v6 = Vector((smax.x, smax.y, smax.z))
v7 = Vector((smin.x, smax.y, smax.z))
arrowx = smin.x + (smax.x - smin.x) / 2
arrowy = smin.y - (smax.x - smin.x) / 2
v8 = Vector((arrowx, arrowy, smin.z))
vertices = [v0, v1, v2, v3, v4, v5, v6, v7, v8]
for v in vertices:
v.rotate(rotation)
v += Vector(location)
lines = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5],
[2, 6], [3, 7], [0, 8], [1, 8]]
ui_bgl.draw_lines(vertices, lines, color)
if progress != None:
color = (color[0], color[1], color[2], .2)
progress = progress * .01
vz0 = (v4 - v0) * progress + v0
vz1 = (v5 - v1) * progress + v1
vz2 = (v6 - v2) * progress + v2
vz3 = (v7 - v3) * progress + v3
rects = (
(v0, v1, vz1, vz0),
(v1, v2, vz2, vz1),
(v2, v3, vz3, vz2),
(v3, v0, vz0, vz3))
for r in rects:
ui_bgl.draw_rect_3d(r, color)
def get_rating_scalevalues(asset_type):
xs = []
if asset_type == 'model':
scalevalues = (0.5, 1, 2, 5, 10, 25, 50, 100, 250)
for v in scalevalues:
a = math.log2(v)
x = (a + 1) * (1. / 9.)
xs.append(x)
else:
scalevalues = (0.2, 1, 2, 3, 4, 5)
for v in scalevalues:
a = v
x = v / 5.
xs.append(x)
return scalevalues, xs
def draw_ratings_bgl():
# return;
ui = bpy.context.scene.blenderkitUI
rating_possible, rated, asset, asset_data = is_rating_possible()
if rating_possible: # (not rated or ui_props.rating_menu_on):
bkit_ratings = asset.bkit_ratings
if ui.rating_button_on:
img = utils.get_thumbnail('star_white.png')
ui_bgl.draw_image(ui.rating_x,
ui.rating_y - ui.rating_button_width,
ui.rating_button_width,
ui.rating_button_width,
img, 1)
# if ui_props.asset_type != 'BRUSH':
# thumbnail_image = props.thumbnail
# else:
# b = utils.get_active_brush()
# thumbnail_image = b.icon_filepath
directory = paths.get_temp_dir('%s_search' % asset_data['assetType'])
tpath = os.path.join(directory, asset_data['thumbnail_small'])
img = utils.get_hidden_image(tpath, 'rating_preview')
ui_bgl.draw_image(ui.rating_x + ui.rating_button_width,
ui.rating_y - ui.rating_button_width,
ui.rating_button_width,
ui.rating_button_width,
img, 1)
return
def draw_text_block(x=0, y=0, width=40, font_size=10, line_height=15, text='', color=colors.TEXT):
lines = text.split('\n')
nlines = []
for l in lines:
nlines.extend(search.split_subs(l, ))
column_lines = 0
for l in nlines:
ytext = y - column_lines * line_height
column_lines += 1
ui_bgl.draw_text(l, x, ytext, font_size, color)
def draw_tooltip(x, y, name='', author='', quality='-', img=None, gravatar=None):
region = bpy.context.region
scale = bpy.context.preferences.view.ui_scale
t = time.time()
if not img or max(img.size[0], img.size[1]) == 0:
isizex = int(512 * scale * img.size[0] / min(img.size[0], img.size[1]))
isizey = int(512 * scale * img.size[1] / min(img.size[0], img.size[1]))
# then do recurrent re-scaling, to know where to fit the tooltip
estimated_height = 2 * ttipmargin + isizey
if estimated_height > y:
scaledown = y / (estimated_height)
scale *= scaledown
isizex = int(512 * scale * img.size[0] / min(img.size[0], img.size[1]))
isizey = int(512 * scale * img.size[1] / min(img.size[0], img.size[1]))
ttipmargin = 5 * scale
textmargin = 12 * scale
if gravatar is not None:
overlay_height_base = 90
else:
overlay_height = overlay_height_base * scale
name_height = int(20 * scale)
width = isizex + 2 * ttipmargin
properties_width = 0
for r in bpy.context.area.regions:
if r.type == 'UI':
properties_width = r.width
x = min(x + width, region.width - properties_width) - width
# define_colors
background_color = bpy.context.preferences.themes[0].user_interface.wcol_tooltip.inner
background_overlay = (background_color[0], background_color[1], background_color[2], .8)
textcol = bpy.context.preferences.themes[0].user_interface.wcol_tooltip.text
textcol = (textcol[0], textcol[1], textcol[2], 1)
ui_bgl.draw_rect(x - ttipmargin,
y - 2 * ttipmargin - isizey,
isizex + ttipmargin * 2,
2 * ttipmargin + isizey,
ui_bgl.draw_image(x, y - isizey - ttipmargin, isizex, isizey, img, 1)
# text overlay background
ui_bgl.draw_rect(x - ttipmargin,
y - 2 * ttipmargin - isizey,
isizex + ttipmargin * 2,
name_x = x + textmargin
name_y = y - isizey + overlay_height - textmargin - name_height
ui_bgl.draw_text(name, name_x, name_y, name_height, textcol)
author_x_text = x + isizex - textmargin
gravatar_size = overlay_height - 2 * textmargin
gravatar_y = y - isizey - ttipmargin + textmargin
author_x_text -= gravatar_size + textmargin
ui_bgl.draw_image(x + isizex - gravatar_size - textmargin,
gravatar_y, # + textmargin,
gravatar_size, gravatar_size, gravatar, 1)
author_text_size = int(name_height * .7)
ui_bgl.draw_text(author, author_x_text, gravatar_y, author_text_size, textcol, ralign=True)
# draw quality
quality_text_size = int(name_height * 1)
img = utils.get_thumbnail('star_grey.png')
ui_bgl.draw_image(name_x, gravatar_y, quality_text_size, quality_text_size, img, .6)
ui_bgl.draw_text(str(quality), name_x + quality_text_size + 5, gravatar_y, quality_text_size, textcol)
def draw_tooltip_with_author(asset_data, x, y):
# TODO move this lazy loading into a function and don't duplicate through the code
img = get_large_thumbnail_image(asset_data)
gimg = None
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']}"
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,
if not utils.guard_from_crash():
Vilém Duha
committed
w = context.window
try:
# self.area might throw error just by itself.
a1 = self.area
Vilém Duha
committed
w1 = self.window
if len(a.spaces[0].region_quadviews) > 0:
# print(dir(bpy.context.region_data))
# print('quad', a.spaces[0].region_3d, a.spaces[0].region_quadviews[0])
if a.spaces[0].region_3d != context.region_data:
go = False
except:
# bpy.types.SpaceView3D.draw_handler_remove(self._handle_2d, 'WINDOW')
# bpy.types.SpaceView3D.draw_handler_remove(self._handle_3d, 'WINDOW')
go = False
Vilém Duha
committed
if go and a == a1 and w == w1:
props = context.scene.blenderkitUI
if props.down_up == 'SEARCH':
draw_ratings_bgl()
elif props.down_up == 'UPLOAD':
draw_callback_2d_upload_preview(self, context)
def draw_downloader(x, y, percent=0, img=None, text=''):
if img is not None:
ui_bgl.draw_image(x, y, 50, 50, img, .5)
ui_bgl.draw_rect(x, y, 50, int(0.5 * percent), (.2, 1, .2, .3))
ui_bgl.draw_rect(x - 3, y - 3, 6, 6, (1, 0, 0, .3))
# if asset_data is not None:
# ui_bgl.draw_text(asset_data['name'], x, y, colors.TEXT)
# ui_bgl.draw_text(asset_data['filesSize'])
if text:
ui_bgl.draw_text(text, x, y - 15, 12, colors.TEXT)
def draw_progress(x, y, text='', percent=None, color=colors.GREEN):
ui_bgl.draw_text(text, x, y + 8, 16, color)
def draw_callback_3d_progress(self, context):
# 'star trek' mode gets here, blocked by now ;)
for threaddata in download.download_threads:
asset_data = threaddata[1]
tcom = threaddata[2]
if tcom.passargs.get('downloaders'):
for d in tcom.passargs['downloaders']:
if asset_data['assetType'] == 'model':
draw_bbox(d['location'], d['rotation'], asset_data['bbox_min'], asset_data['bbox_max'],
progress=tcom.progress)
def draw_callback_2d_progress(self, context):
green = (.2, 1, .2, .3)
offset = 0
row_height = 35
ui = bpy.context.scene.blenderkitUI
x = ui.reports_x
y = ui.reports_y
index = 0
for threaddata in download.download_threads:
asset_data = threaddata[1]
tcom = threaddata[2]
directory = paths.get_temp_dir('%s_search' % asset_data['assetType'])
tpath = os.path.join(directory, asset_data['thumbnail_small'])
img = utils.get_hidden_image(tpath, asset_data['id'])
if tcom.passargs.get('downloaders'):
for d in tcom.passargs['downloaders']:
loc = view3d_utils.location_3d_to_region_2d(bpy.context.region, bpy.context.space_data.region_3d,
d['location'])
if loc is not None:
if asset_data['assetType'] == 'model':
# models now draw with star trek mode, no need to draw percent for the image.
draw_downloader(loc[0], loc[1], percent=tcom.progress, img=img, text=tcom.report)
draw_downloader(loc[0], loc[1], percent=tcom.progress, img=img, text=tcom.report)
# utils.p('end drawing downlaoders downloader')
else:
draw_progress(x, y - index * 30, text='downloading %s' % asset_data['name'],
percent=tcom.progress)
index += 1
for process in bg_blender.bg_processes:
tcom = process[1]
n = tcom.name + ': '
draw_progress(x, y - index * 30, '%s' % n + tcom.lasttext,
global reports
for report in reports:
report.draw(x, y - index * 30)
index += 1
report.fade()
def draw_callback_2d_upload_preview(self, context):
ui_props = context.scene.blenderkitUI
props = utils.get_upload_props()
# assets which don't need asset preview
if ui_props.asset_type == 'HDR':
if ui_props.asset_type != 'BRUSH':
ui_props.thumbnail_image = props.thumbnail
else:
b = utils.get_active_brush()
ui_props.thumbnail_image = b.icon_filepath
img = utils.get_hidden_image(ui_props.thumbnail_image, 'upload_preview')
draw_tooltip(ui_props.bar_x, ui_props.bar_y, name=ui_props.tooltip, img=img)
def is_upload_old(asset_data):
'''
estimates if the asset is far too long in the 'uploaded' state
This returns the number of days the validation is over the limit.
'''
date_time_str = asset_data["created"][:10]
# date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d')
today = date_time_obj.today()
age = today - date_time_obj
old = datetime.timedelta(days=7)
if age > old:
return (age.days - old.days)
return 0
def get_large_thumbnail_image(asset_data):
'''Get thumbnail image from asset data'''
scene = bpy.context.scene
ui_props = scene.blenderkitUI
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 not asset_data['thumbnail']:
tpath = paths.get_addon_thumbnail_path('thumbnail_not_available.jpg')
if asset_data['assetType'] == 'hdr':
colorspace = 'Non-Color'
else:
colorspace = 'sRGB'
img = utils.get_hidden_image(tpath, iname, colorspace=colorspace)
return img
s = bpy.context.scene
ui_props = context.scene.blenderkitUI
user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
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
# hc = (hc[0], hc[1], hc[2], .2)
hc = (1, 1, 1, .07)
# grey1 = (hc.r * .55, hc.g * .55, hc.b * .55, 1)
grey2 = (hc[0] * .8, hc[1] * .8, hc[2] * .8, .5)
# grey1 = (hc.r, hc.g, hc.b, 1)
white = (1, 1, 1, 0.2)
green = (.2, 1, .2, .7)
highlight = bpy.context.preferences.themes[0].user_interface.wcol_menu_item.inner_sel
highlight = (1, 1, 1, .2)
# highlight = (1, 1, 1, 0.8)
# background of asset bar
# if ui_props.hcount>0:
# #this fixes a draw issue introduced in blender 2.91. draws a very small version of the image to avoid problems
# # with alpha. Not sure why this works.
# img = utils.get_thumbnail('arrow_left.png')
# ui_bgl.draw_image(0, 0, 1,
# 1,
# img,
# 1)
if not ui_props.dragging and ui_props.hcount > 0 and ui_props.wcount > 0:
search_results = bpy.context.window_manager.get('search results')
search_results_orig = bpy.context.window_manager.get('search results orig')
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
if search_results == None:
return
h_draw = min(ui_props.hcount, math.ceil(len(search_results) / ui_props.wcount))
if ui_props.wcount > len(search_results):
bar_width = len(search_results) * (ui_props.thumb_size + ui_props.margin) + ui_props.margin
else:
bar_width = ui_props.bar_width
row_height = ui_props.thumb_size + ui_props.margin
ui_bgl.draw_rect(ui_props.bar_x, ui_props.bar_y - ui_props.bar_height, bar_width,
ui_props.bar_height, hc)
if search_results is not None:
if ui_props.scrolloffset > 0 or ui_props.wcount * ui_props.hcount < len(search_results):
ui_props.drawoffset = 35
else:
ui_props.drawoffset = 0
if ui_props.wcount * ui_props.hcount < len(search_results):
# arrows
arrow_y = ui_props.bar_y - int((ui_props.bar_height + ui_props.thumb_size) / 2) + ui_props.margin
if ui_props.scrolloffset > 0:
if ui_props.active_index == -2:
ui_bgl.draw_rect(ui_props.bar_x, ui_props.bar_y - ui_props.bar_height, 25,
ui_props.bar_height, highlight)
img = utils.get_thumbnail('arrow_left.png')
ui_bgl.draw_image(ui_props.bar_x, arrow_y, 25,
ui_props.thumb_size,
img,
1)
if search_results_orig['count'] - ui_props.scrolloffset > (ui_props.wcount * ui_props.hcount) + 1:
if ui_props.active_index == -1:
ui_bgl.draw_rect(ui_props.bar_x + ui_props.bar_width - 25,
ui_props.bar_y - ui_props.bar_height, 25,
ui_props.bar_height,
highlight)
img1 = utils.get_thumbnail('arrow_right.png')
ui_bgl.draw_image(ui_props.bar_x + ui_props.bar_width - 25,
arrow_y, 25,
ui_props.thumb_size, img1, 1)
for b in range(0, h_draw):
w_draw = min(ui_props.wcount, len(search_results) - b * ui_props.wcount - ui_props.scrolloffset)
y = ui_props.bar_y - (b + 1) * (row_height)
for a in range(0, w_draw):
x = ui_props.bar_x + a * (
ui_props.margin + ui_props.thumb_size) + ui_props.margin + ui_props.drawoffset
#
index = a + ui_props.scrolloffset + b * ui_props.wcount
iname = utils.previmg_name(index)
img = bpy.data.images.get(iname)
if img is not None and img.size[0] > 0 and img.size[1] > 0:
w = int(ui_props.thumb_size * img.size[0] / max(img.size[0], img.size[1]))
h = int(ui_props.thumb_size * img.size[1] / max(img.size[0], img.size[1]))
crop = (0, 0, 1, 1)
if img.size[0] > img.size[1]:
offset = (1 - img.size[1] / img.size[0]) / 2
crop = (offset, 0, 1 - offset, 1)
ui_bgl.draw_image(x, y, w, w, img, 1,
crop=crop)
if index == ui_props.active_index:
ui_bgl.draw_rect(x - ui_props.highlight_margin, y - ui_props.highlight_margin,
w + 2 * ui_props.highlight_margin, w + 2 * ui_props.highlight_margin,
highlight)
# if index == ui_props.active_index:
# ui_bgl.draw_rect(x - highlight_margin, y - highlight_margin,
# w + 2*highlight_margin, h + 2*highlight_margin , highlight)
else:
ui_bgl.draw_rect(x, y, ui_props.thumb_size, ui_props.thumb_size, white)
# code to inform validators that the validation is waiting too long and should be done asap
if result['verificationStatus'] == 'uploaded':
if utils.profile_is_validator():
over_limit = is_upload_old(result)
if over_limit:
red = (1, 0, 0, redness)
ui_bgl.draw_rect(x, y, ui_props.thumb_size, ui_props.thumb_size, red)
ui_bgl.draw_rect(x, y, int(ui_props.thumb_size * result['downloaded'] / 100.0), 2, green)
# object type icons - just a test..., adds clutter/ not so userfull:
# icons = ('type_finished.png', 'type_template.png', 'type_particle_system.png')
if (result.get('canDownload', True)) == 0:
img = utils.get_thumbnail('locked.png')
ui_bgl.draw_image(x + 2, y + 2, 24, 24, img, 1)
# pcoll = icons.icon_collections["main"]
# v_icon = pcoll['rejected']
v_icon = verification_icons[result.get('verificationStatus', 'validated')]
if v_icon is None and utils.profile_is_validator():
if ratings_utils.get_rating_local(result['id']) in (None, {}):
v_icon = 'star_grey.png'
if v_icon is not None:
img = utils.get_thumbnail(v_icon)
ui_bgl.draw_image(x + ui_props.thumb_size - 26, y + 2, 24, 24, img, 1)
# if user_preferences.api_key == '':
# report = 'Register on BlenderKit website to upload your own assets.'
# ui_bgl.draw_text(report, ui_props.bar_x + ui_props.margin,
# ui_props.bar_y - 25 - ui_props.margin - ui_props.bar_height, 15)
# elif len(search_results) == 0:
# report = 'BlenderKit - No matching results found.'
# ui_bgl.draw_text(report, ui_props.bar_x + ui_props.margin,
# ui_props.bar_y - 25 - ui_props.margin, 15)
if ui_props.draw_tooltip:
r = search_results[ui_props.active_index]
draw_tooltip_with_author(r, ui_props.mouse_x, ui_props.mouse_y)
s = bpy.context.scene
props = utils.get_search_props()
# if props.report != '' and props.is_searching or props.search_error:
# ui_bgl.draw_text(props.report, ui_props.bar_x,
# ui_props.bar_y - 15 - ui_props.margin - ui_props.bar_height, 15)
if ui_props.dragging and (
ui_props.draw_drag_image or ui_props.draw_snapped_bounds) and ui_props.active_index > -1:
iname = utils.previmg_name(ui_props.active_index)
img = bpy.data.images.get(iname)
linelength = 35
ui_bgl.draw_image(ui_props.mouse_x + linelength, ui_props.mouse_y - linelength - ui_props.thumb_size,
ui_props.thumb_size, ui_props.thumb_size, img, 1)
ui_bgl.draw_line2d(ui_props.mouse_x, ui_props.mouse_y, ui_props.mouse_x + linelength,
ui_props.mouse_y - linelength, 2, white)
def draw_callback_3d(self, context):
''' Draw snapped bbox while dragging and in the future other blenderkit related stuff. '''
if not utils.guard_from_crash():
ui = context.scene.blenderkitUI
if ui.dragging and ui.asset_type == 'MODEL':
if ui.draw_snapped_bounds:
draw_bbox(ui.snapped_location, ui.snapped_rotation, ui.snapped_bbox_min, ui.snapped_bbox_max)
def object_in_particle_collection(o):
'''checks if an object is in a particle system as instance, to not snap to it and not to try to attach material.'''
for p in bpy.data.particles:
if p.instance_collection:
for o1 in p.instance_collection.objects:
if o1 == o:
return True
if p.instance_object == o:
return True
return False
def deep_ray_cast(depsgraph, ray_origin, vec):
# this allows to ignore some objects, like objects with bounding box draw style or particle objects
object = None
# while object is None or object.draw
has_hit, snapped_location, snapped_normal, face_index, object, matrix = bpy.context.scene.ray_cast(
depsgraph, ray_origin, vec)
empty_set = False, Vector((0, 0, 0)), Vector((0, 0, 1)), None, None, None
while try_object and (try_object.display_type == 'BOUNDS' or object_in_particle_collection(try_object)):
ray_origin = snapped_location + vec.normalized() * 0.0003
try_has_hit, try_snapped_location, try_snapped_normal, try_face_index, try_object, try_matrix = bpy.context.scene.ray_cast(
depsgraph, ray_origin, vec)
if try_has_hit:
# this way only good hits are returned, otherwise
has_hit, snapped_location, snapped_normal, face_index, object, matrix = try_has_hit, try_snapped_location, try_snapped_normal, try_face_index, try_object, try_matrix
if not (object.display_type == 'BOUNDS' or object_in_particle_collection(
try_object)): # or not object.visible_get()):
return has_hit, snapped_location, snapped_normal, face_index, object, matrix
return empty_set
def mouse_raycast(context, mx, my):
r = context.region
rv3d = context.region_data
coord = mx, my
# get the ray from the viewport and mouse
view_vector = view3d_utils.region_2d_to_vector_3d(r, rv3d, coord)
if rv3d.view_perspective == 'CAMERA' and rv3d.is_perspective == False:
# ortographic cameras don'w work with region_2d_to_origin_3d
view_position = rv3d.view_matrix.inverted().translation
ray_origin = view3d_utils.region_2d_to_location_3d(r, rv3d, coord, depth_location=view_position)
else:
ray_origin = view3d_utils.region_2d_to_origin_3d(r, rv3d, coord, clamp=1.0)
ray_target = ray_origin + (view_vector * 1000000000)
vec = ray_target - ray_origin
has_hit, snapped_location, snapped_normal, face_index, object, matrix = deep_ray_cast(
bpy.context.view_layer.depsgraph, ray_origin, vec)
# backface snapping inversion
if view_vector.angle(snapped_normal) < math.pi / 2:
# print(has_hit, snapped_location, snapped_normal, face_index, object, matrix)
# rote = mathutils.Euler((0, 0, math.pi))
randoffset = math.pi
if has_hit:
props = bpy.context.scene.blenderkit_models
up = Vector((0, 0, 1))
if props.perpendicular_snap:
if snapped_normal.z > 1 - props.perpendicular_snap_threshold:
snapped_normal = Vector((0, 0, 1))
elif snapped_normal.z < -1 + props.perpendicular_snap_threshold:
snapped_normal = Vector((0, 0, -1))
elif abs(snapped_normal.z) < props.perpendicular_snap_threshold:
snapped_normal.z = 0
snapped_normal.normalize()
snapped_rotation = snapped_normal.to_track_quat('Z', 'Y').to_euler()
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
if props.randomize_rotation and snapped_normal.angle(up) < math.radians(10.0):
randoffset = props.offset_rotation_amount + math.pi + (
random.random() - 0.5) * props.randomize_rotation_amount
else:
randoffset = props.offset_rotation_amount # we don't rotate this way on walls and ceilings. + math.pi
# snapped_rotation.z += math.pi + (random.random() - 0.5) * .2
else:
snapped_rotation = mathutils.Quaternion((0, 0, 0, 0)).to_euler()
snapped_rotation.rotate_axis('Z', randoffset)
return has_hit, snapped_location, snapped_normal, snapped_rotation, face_index, object, matrix
def floor_raycast(context, mx, my):
r = context.region
rv3d = context.region_data
coord = mx, my
# get the ray from the viewport and mouse
view_vector = view3d_utils.region_2d_to_vector_3d(r, rv3d, coord)
ray_origin = view3d_utils.region_2d_to_origin_3d(r, rv3d, coord)
ray_target = ray_origin + (view_vector * 1000)
# various intersection plane normals are needed for corner cases that might actually happen quite often - in front and side view.
# default plane normal is scene floor.
plane_normal = (0, 0, 1)
if math.isclose(view_vector.x, 0, abs_tol=1e-4) and math.isclose(view_vector.z, 0, abs_tol=1e-4):
plane_normal = (0, 1, 0)
elif math.isclose(view_vector.z, 0, abs_tol=1e-4):
plane_normal = (1, 0, 0)
snapped_location = mathutils.geometry.intersect_line_plane(ray_origin, ray_target, (0, 0, 0), plane_normal,
False)
if snapped_location != None:
has_hit = True
snapped_normal = Vector((0, 0, 1))
face_index = None
object = None
matrix = None
snapped_rotation = snapped_normal.to_track_quat('Z', 'Y').to_euler()
props = bpy.context.scene.blenderkit_models
if props.randomize_rotation:
randoffset = props.offset_rotation_amount + math.pi + (
random.random() - 0.5) * props.randomize_rotation_amount
else:
randoffset = props.offset_rotation_amount + math.pi
snapped_rotation.rotate_axis('Z', randoffset)
return has_hit, snapped_location, snapped_normal, snapped_rotation, face_index, object, matrix
def is_rating_possible():
ao = bpy.context.active_object
ui = bpy.context.scene.blenderkitUI
preferences = bpy.context.preferences.addons['blenderkit'].preferences
if preferences.api_key == '':
return False, False, None, None
if bpy.context.scene.get('assets rated') is not None and ui.down_up == 'SEARCH':
if bpy.context.mode in ('SCULPT', 'PAINT_TEXTURE'):
b = utils.get_active_brush()
ad = b.get('asset_data')
if ad is not None:
rated = bpy.context.scene['assets rated'].get(ad['assetBaseId'])
return True, rated, b, ad
if ao is not None:
# crawl parents to reach active asset. there could have been parenting so we need to find the first onw
ao_check = ao
while ad is None or (ad is None and ao_check.parent is not None):
ad = ao_check.get('asset_data')
if ad is not None and ad.get('assetBaseId') is not None:
rated = s['assets rated'].get(ad['assetBaseId'])
# originally hidden for already rated assets
return True, rated, ao_check, ad
elif ao_check.parent is not None:
ao_check = ao_check.parent
else:
# check also materials
m = ao.active_material
if m is not None:
ad = m.get('asset_data')
rated = bpy.context.scene['assets rated'].get(ad['assetBaseId'])
# if t>2 and t<2.5:
# ui_props.rating_on = False
return False, False, None, None
def interact_rating(r, mx, my, event):
ui = bpy.context.scene.blenderkitUI
rating_possible, rated, asset, asset_data = is_rating_possible()
if rating_possible:
bkit_ratings = asset.bkit_ratings
t = time.time() - ui.last_rating_time
if bpy.context.mode in ('SCULPT', 'PAINT_TEXTURE'):
accept_value = 'PRESS'
else:
accept_value = 'RELEASE'
if ui.rating_button_on and event.type == 'LEFTMOUSE' and event.value == accept_value:
if mouse_in_area(mx, my,
ui.rating_x,
ui.rating_y - ui.rating_button_width,
ui.rating_button_width * 2,
ui.rating_button_width):
# ui.rating_menu_on = True
ctx = utils.get_fake_context(bpy.context, area_type='VIEW_3D')
bpy.ops.wm.blenderkit_menu_rating_upload(ctx, 'INVOKE_DEFAULT', asset_name=asset_data['name'],
asset_id=asset_data['id'],
return True
return False
def mouse_in_area(mx, my, x, y, w, h):
if x < mx < x + w and y < my < y + h:
return True
else:
return False
def mouse_in_asset_bar(mx, my):
ui_props = bpy.context.scene.blenderkitUI
# search_results = bpy.context.window_manager.get('search results')
# if search_results == None:
# return False
#
# w_draw1 = min(ui_props.wcount + 1, len(search_results) - b * ui_props.wcount - ui_props.scrolloffset)
# end = ui_props.bar_x + (w_draw1) * (
# ui_props.margin + ui_props.thumb_size) + ui_props.margin + ui_props.drawoffset + 25
if ui_props.bar_y - ui_props.bar_height < my < ui_props.bar_y \
and mx > ui_props.bar_x and mx < ui_props.bar_x + ui_props.bar_width:
return True
else:
return False
def mouse_in_region(r, mx, my):
if 0 < my < r.height and 0 < mx < r.width:
return True
else:
return False
def update_ui_size(area, region):
if bpy.app.background or not area:
ui = bpy.context.scene.blenderkitUI
user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
ui_scale = bpy.context.preferences.view.ui_scale
ui.margin = ui.bl_rna.properties['margin'].default * ui_scale
ui.thumb_size = user_preferences.thumb_size * ui_scale
reg_multiplier = 1
if not bpy.context.preferences.system.use_region_overlap:
reg_multiplier = 0
for r in area.regions:
if r.type == 'TOOLS':