Compare commits

..

3 Commits

Author SHA1 Message Date
kaosat.dev
6cbb144746 feat(Blenvy:Bevy):
* cleaned up hot reload code a bit
 * renamed a few things for clarity
 * experimented with hiding entity while spawning & showing it again after spawn to
try and remove "flashes" happening when spawning blueprints with lights
 * for testing example, fixed dynamic spawner test
2024-06-29 01:51:49 +02:00
kaosat.dev
fb54b0c913 feat(Blenvy:Blender): upgreadable components: disable ui for external items 2024-06-29 00:56:07 +02:00
kaosat.dev
547315aadc feat(Blenvy:Blender): fixed selection issues ! 2024-06-29 00:45:26 +02:00
8 changed files with 89 additions and 142 deletions

View File

@ -58,12 +58,12 @@ pub(crate) struct AssetLoadTracker {
/// helper component, for tracking loaded assets /// helper component, for tracking loaded assets
#[derive(Component, Debug)] #[derive(Component, Debug)]
pub(crate) struct BlenvyAssetsLoadState { pub(crate) struct BlueprintAssetsLoadState {
pub all_loaded: bool, pub all_loaded: bool,
pub asset_infos: Vec<AssetLoadTracker>, pub asset_infos: Vec<AssetLoadTracker>,
pub progress: f32, pub progress: f32,
} }
impl Default for BlenvyAssetsLoadState { impl Default for BlueprintAssetsLoadState {
fn default() -> Self { fn default() -> Self {
Self { Self {
all_loaded: Default::default(), all_loaded: Default::default(),

View File

@ -17,7 +17,7 @@ use bevy::{
render::mesh::Mesh, render::mesh::Mesh,
}; };
use crate::{AssetLoadTracker, BlenvyAssetsLoadState, BlenvyConfig, BlueprintInstanceReady}; use crate::{AssetLoadTracker, BlueprintAssetsLoadState, BlenvyConfig, BlueprintInstanceReady};
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)] #[reflect(Component)]
@ -72,7 +72,7 @@ pub(crate) fn materials_inject(
commands commands
.entity(entity) .entity(entity)
.insert(BlenvyAssetsLoadState { .insert(BlueprintAssetsLoadState {
all_loaded: false, all_loaded: false,
asset_infos, asset_infos,
..Default::default() ..Default::default()
@ -86,7 +86,7 @@ pub(crate) fn materials_inject(
// TODO, merge with blueprints_check_assets_loading, make generic ? // TODO, merge with blueprints_check_assets_loading, make generic ?
pub(crate) fn check_for_material_loaded( pub(crate) fn check_for_material_loaded(
mut blueprint_assets_to_load: Query< mut blueprint_assets_to_load: Query<
(Entity, &mut BlenvyAssetsLoadState), (Entity, &mut BlueprintAssetsLoadState),
With<BlueprintMaterialAssetsNotLoaded>, With<BlueprintMaterialAssetsNotLoaded>,
>, >,
asset_server: Res<AssetServer>, asset_server: Res<AssetServer>,

View File

@ -1,9 +1,9 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use bevy::{asset::LoadedUntypedAsset, gltf::Gltf, prelude::*, scene::SceneInstance, transform::commands, utils::hashbrown::HashMap}; use bevy::{asset::LoadedUntypedAsset, gltf::Gltf, prelude::*, render::view::visibility, scene::SceneInstance, transform::commands, utils::hashbrown::HashMap};
use serde_json::Value; use serde_json::Value;
use crate::{BlueprintAssets, BlenvyAssetsLoadState, AssetLoadTracker, BlenvyConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded}; use crate::{BlueprintAssets, BlueprintAssetsLoadState, AssetLoadTracker, BlenvyConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded};
/// this is a flag component for our levels/game world /// this is a flag component for our levels/game world
#[derive(Component)] #[derive(Component)]
@ -164,12 +164,13 @@ asset_server: Res<AssetServer>,
if !asset_infos.is_empty() { if !asset_infos.is_empty() {
commands commands
.entity(entity) .entity(entity)
.insert(BlenvyAssetsLoadState { .insert(BlueprintAssetsLoadState {
all_loaded: false, all_loaded: false,
asset_infos, asset_infos,
..Default::default() ..Default::default()
}) })
.insert(BlueprintAssetsNotLoaded); .insert(BlueprintAssetsNotLoaded)
;
} else { } else {
commands.entity(entity).insert(BlueprintAssetsLoaded); commands.entity(entity).insert(BlueprintAssetsLoaded);
} }
@ -178,7 +179,7 @@ asset_server: Res<AssetServer>,
pub(crate) fn blueprints_check_assets_loading( pub(crate) fn blueprints_check_assets_loading(
mut blueprint_assets_to_load: Query< mut blueprint_assets_to_load: Query<
(Entity, Option<&Name>, &BlueprintInfo, &mut BlenvyAssetsLoadState), (Entity, Option<&Name>, &BlueprintInfo, &mut BlueprintAssetsLoadState),
With<BlueprintAssetsNotLoaded>, With<BlueprintAssetsNotLoaded>,
>, >,
asset_server: Res<AssetServer>, asset_server: Res<AssetServer>,
@ -222,7 +223,7 @@ pub(crate) fn blueprints_check_assets_loading(
.entity(entity) .entity(entity)
.insert(BlueprintAssetsLoaded) .insert(BlueprintAssetsLoaded)
.remove::<BlueprintAssetsNotLoaded>() .remove::<BlueprintAssetsNotLoaded>()
//.remove::<BlenvyAssetsLoadState>() //REMOVE it in release mode/ when hot reload is off, keep it for dev/hot reload //.remove::<BlueprintAssetsLoadState>() //REMOVE it in release mode/ when hot reload is off, keep it for dev/hot reload
; ;
}else { }else {
println!("LOADING: done for ALL assets of {:?} (instance of {}): {} ",entity_name, blueprint_info.path, progress * 100.0); println!("LOADING: done for ALL assets of {:?} (instance of {}): {} ",entity_name, blueprint_info.path, progress * 100.0);
@ -233,7 +234,7 @@ pub(crate) fn blueprints_check_assets_loading(
/* /*
pub(crate) fn hot_reload_asset_check( pub(crate) fn hot_reload_asset_check(
mut blueprint_assets: Query< mut blueprint_assets: Query<
(Entity, Option<&Name>, &BlueprintInfo, &mut BlenvyAssetsLoadState)>, (Entity, Option<&Name>, &BlueprintInfo, &mut BlueprintAssetsLoadState)>,
asset_server: Res<AssetServer>, asset_server: Res<AssetServer>,
mut commands: Commands, mut commands: Commands,
){ ){
@ -260,109 +261,42 @@ use bevy::asset::AssetEvent;
pub(crate) fn react_to_asset_changes( pub(crate) fn react_to_asset_changes(
mut gltf_events: EventReader<AssetEvent<Gltf>>, mut gltf_events: EventReader<AssetEvent<Gltf>>,
mut untyped_events: EventReader<AssetEvent<LoadedUntypedAsset>>, mut untyped_events: EventReader<AssetEvent<LoadedUntypedAsset>>,
mut blueprint_assets: Query<(Entity, Option<&Name>, &BlueprintInfo, &mut BlenvyAssetsLoadState, Option<&Children>)>, mut blueprint_assets: Query<(Entity, Option<&Name>, &BlueprintInfo, &mut BlueprintAssetsLoadState, Option<&Children>)>,
asset_server: Res<AssetServer>, asset_server: Res<AssetServer>,
mut commands: Commands, mut commands: Commands,
) { ) {
for event in untyped_events.read() {
for (entity, entity_name, blueprint_info, mut assets_to_load, c) in blueprint_assets.iter_mut() {
for tracker in assets_to_load.asset_infos.iter_mut() {
let asset_id = tracker.id;
println!("changed {:?} (blueprint {}) {}", entity_name, blueprint_info.path, event.is_modified(asset_id));
}
}
match event {
AssetEvent::Added { id } => {
// React to the image being created
println!("Added untyped {:?}", asset_server.get_path(*id))
}
AssetEvent::LoadedWithDependencies { id } => {
// React to the image being loaded
// after all dependencies
println!("Loaded with deps untyped {:?}", asset_server.get_path(*id))
}
AssetEvent::Modified { id } => {
// React to the image being modified
println!("Modified untyped {:?}", asset_server.get_path(*id))
}
AssetEvent::Removed { id } => {
// React to the image being removed
println!("Removed untyped {:?}", asset_server.get_path(*id))
},
AssetEvent::Unused { id } => {
// React to the last strong handle for the asset being dropped
println!("unused untyped {:?}", asset_server.get_path(*id))
}
}
}
for event in gltf_events.read() { for event in gltf_events.read() {
// LoadedUntypedAsset // LoadedUntypedAsset
/*for (entity, entity_name, blueprint_info, mut assets_to_load) in blueprint_assets.iter_mut() {
for tracker in assets_to_load.asset_infos.iter_mut() {
let asset_id = tracker.id;
if blueprint_info.path.ends_with("glb") || blueprint_info.path.ends_with("gltf") {
// let typed_asset_id = asset_server.get_handle(blueprint_info.path);
let foo: Handle<Gltf> = asset_server.load(blueprint_info.path.clone());
//println!("changed {:?} (blueprint {}) {}", entity_name, blueprint_info.path, event.is_modified(foo.id()));
println!("changed {:?} (blueprint {}) {}", entity_name, blueprint_info.path, event.is_modified(foo.id()));
println!("added {:?} (blueprint {}) {}", entity_name, blueprint_info.path, event.is_added(foo.id()));
println!("removed {:?} (blueprint {}) {}", entity_name, blueprint_info.path, event.is_removed(foo.id()));
println!("loaded with deps {:?} (blueprint {}) {}", entity_name, blueprint_info.path, event.is_loaded_with_dependencies(foo.id()));
}
}
}*/
match event { match event {
AssetEvent::Added { id } => {
// React to the image being created
println!("Added gltf, path {:?}", asset_server.get_path(*id));
}
AssetEvent::LoadedWithDependencies { id } => {
// React to the image being loaded
// after all dependencies
println!("Loaded gltf with deps{:?}", asset_server.get_path(*id))
}
AssetEvent::Modified { id } => { AssetEvent::Modified { id } => {
// React to the image being modified // React to the image being modified
println!("Modified gltf {:?}", asset_server.get_path(*id)); // println!("Modified gltf {:?}", asset_server.get_path(*id));
for (entity, entity_name, blueprint_info, mut assets_to_load, children) in blueprint_assets.iter_mut() { for (entity, entity_name, blueprint_info, mut assets_to_load, children) in blueprint_assets.iter_mut() {
for tracker in assets_to_load.asset_infos.iter_mut() { for tracker in assets_to_load.asset_infos.iter_mut() {
if tracker.path == asset_server.get_path(*id).unwrap().to_string() { if asset_server.get_path(*id).is_some() {
println!("HOLY MOLY IT DETECTS !!, now respawn {:?}", entity_name); if tracker.path == asset_server.get_path(*id).unwrap().to_string() {
if children.is_some() { println!("HOLY MOLY IT DETECTS !!, now respawn {:?}", entity_name);
for child in children.unwrap().iter(){ if children.is_some() {
commands.entity(*child).despawn_recursive(); for child in children.unwrap().iter(){
commands.entity(*child).despawn_recursive();
}
} }
} commands.entity(entity)
commands.entity(entity) .remove::<BlueprintAssetsLoaded>()
.remove::<BlueprintAssetsLoaded>() .remove::<SceneInstance>()
.remove::<SceneInstance>() .remove::<BlueprintAssetsLoadState>()
.remove::<BlenvyAssetsLoadState>() .insert(SpawnHere);
.insert(SpawnHere);
break; break;
}
} }
} }
} }
} }
AssetEvent::Removed { id } => { _ => {}
// React to the image being removed
println!("Removed gltf {:?}", asset_server.get_path(*id))
},
AssetEvent::Unused { id } => {
// React to the last strong handle for the asset being dropped
println!("unused gltf {:?}", asset_server.get_path(*id))
}
} }
} }
} }
@ -447,6 +381,8 @@ pub(crate) fn blueprints_spawn(
SceneBundle { SceneBundle {
scene: scene.clone(), scene: scene.clone(),
transform: transforms, transform: transforms,
visibility: Visibility::Hidden,
..Default::default() ..Default::default()
}, },
Spawned, Spawned,

View File

@ -99,10 +99,11 @@ pub(crate) fn spawned_blueprint_post_process(
commands.entity(original).remove::<SpawnHere>(); commands.entity(original).remove::<SpawnHere>();
commands.entity(original).remove::<Spawned>(); commands.entity(original).remove::<Spawned>();
// commands.entity(original).remove::<Handle<Scene>>(); // FIXME: if we delete the handle to the scene, things get despawned ! not what we want // commands.entity(original).remove::<Handle<Scene>>(); // FIXME: if we delete the handle to the scene, things get despawned ! not what we want
//commands.entity(original).remove::<BlenvyAssetsLoadState>(); // also clear the sub assets tracker to free up handles, perhaps just freeing up the handles and leave the rest would be better ? //commands.entity(original).remove::<BlueprintAssetsLoadState>(); // also clear the sub assets tracker to free up handles, perhaps just freeing up the handles and leave the rest would be better ?
//commands.entity(original).remove::<BlueprintAssetsLoaded>(); //commands.entity(original).remove::<BlueprintAssetsLoaded>();
commands.entity(root_entity).despawn_recursive(); commands.entity(root_entity).despawn_recursive();
commands.entity(original).insert( Visibility::Visible
);
blueprint_events.send(BlueprintEvent::Spawned {blueprint_name: blueprint_info.name.clone(), blueprint_path: blueprint_info.path.clone() }); blueprint_events.send(BlueprintEvent::Spawned {blueprint_name: blueprint_info.name.clone(), blueprint_path: blueprint_info.path.clone() });
debug!("DONE WITH POST PROCESS"); debug!("DONE WITH POST PROCESS");

View File

@ -62,7 +62,7 @@ pub fn spawn_test(
let new_entity = commands let new_entity = commands
.spawn(( .spawn((
BluePrintBundle { BluePrintBundle {
blueprint: BlueprintInfo{name: "Health_Pickup".into() , path:"foo/bar.glb".into()}, // FIXME blueprint: BlueprintInfo{name: "Blueprint1".into() , path:"blueprints/Blueprint1.glb".into()}, // FIXME
..Default::default() ..Default::default()
}, },
bevy::prelude::Name::from(format!("test{}", name_index)), bevy::prelude::Name::from(format!("test{}", name_index)),

View File

@ -174,17 +174,17 @@ Blender side:
- [x] prevent attempting to add unexisting components to targets (ie when using the component search) - [x] prevent attempting to add unexisting components to targets (ie when using the component search)
- [x] also for the bulk fix actions - [x] also for the bulk fix actions
- [x] selection of nested objects in collections IS NOT WORKING !!! AHH - [x] selection of nested objects in collections IS NOT WORKING !!! AHH
- [ ] fix/ overhaul upgreadable components - [x] fix/ overhaul upgreadable components
- [x] add listing of upgradeable components for - [x] add listing of upgradeable components for
- [x] meshes - [x] meshes
- [x] materials - [x] materials
- [x] fix display of upgradeaeble components & co - [x] fix display of upgradeaeble components & co
- [x] add clear visual distinction between internal (selectable) & non selectable ones - [x] add clear visual distinction between internal (selectable) & non selectable ones
- [x] do not make selection button available for external blueprints/collections - [x] do not make selection button available for external blueprints/collections
- [ ] perhaps do not show the other buttons & inputs either ? we cannot change the values of an external library file anyway - [x] perhaps do not show the other buttons & inputs either ? we cannot change the values of an external library file anyway
- [ ] BLENVY_OT_item_select is missing handling for the other types (outside of object & collection) - [x] BLENVY_OT_item_select is missing handling for the other types (outside of object & collection)
- [ ] fix selection logic - [x] fix selection logic
- [ ] hidden objects/collections only semi respected at export - [ ] hidden objects/collections only semi respected at export
- this is because blueprints are external ? - this is because blueprints are external ?
@ -209,6 +209,9 @@ Blender side:
- [ ] scan for used materials per blueprint ! - [ ] scan for used materials per blueprint !
- [ ] for scenes, scan for used materials of all non instance objects (TODO: what about overrides ?) - [ ] for scenes, scan for used materials of all non instance objects (TODO: what about overrides ?)
- [ ] add a way of visualizing per blueprint instances ?
- [ ] display export path of blueprints (mostly external) ?
Bevy Side: Bevy Side:
- [x] deprecate BlueprintName & BlueprintPath & use BlueprintInfo instead - [x] deprecate BlueprintName & BlueprintPath & use BlueprintInfo instead
- [ ] make blueprint instances invisible until spawning is done to avoid "spawn flash"? - [ ] make blueprint instances invisible until spawning is done to avoid "spawn flash"?
@ -216,14 +219,22 @@ Bevy Side:
- [ ] simplify testing example: - [ ] simplify testing example:
- [x] remove use of rapier physics (or even the whole common boilerplate ?) - [x] remove use of rapier physics (or even the whole common boilerplate ?)
- [ ] remove/replace bevy editor pls with some native ui to display hierarchies - [ ] remove/replace bevy editor pls with some native ui to display hierarchies
- [x] try out hot reloading
- [ ] add a way of overriding assets for collection instances
- [ ] add a way of visualizing per blueprint instances
- [ ] cleanup all the spurious debug messages
- [ ] fix animation handling
- [ ] simplify examples:
- [ ] a full fledged demo (including physics & co) - [ ] a full fledged demo (including physics & co)
- [ ] other examples without interactions or physics - [ ] other examples without interactions or physics
- [ ] add hot reloading
- [x] basics
- [ ] make it enabled/disabled based on general flag
- [ ] cleanup internals
- [ ] review & change general component insertion & spawning ordering & logic
- GltfComponentsSet::Injection => GltfBlueprintsSet::Spawn => GltfBlueprintsSet::AfterSpawn
Injection => inject lights & co => spawn => afterSpawn
=> Injection => inject lights & co
- [ ] add a way of overriding assets for collection instances => doubt this is possible
- [ ] cleanup all the spurious debug messages
- [ ] fix animation handling
- [ ] how to deal with animation graphs ?
- [ ] update main docs - [ ] update main docs
- [ ] rename project to Blenvy - [ ] rename project to Blenvy
- [ ] replace all references to the old 2 add-ons with those to Blenvy - [ ] replace all references to the old 2 add-ons with those to Blenvy

View File

@ -339,17 +339,15 @@ class BLENVY_PT_component_tools_panel(bpy.types.Panel):
registry = bpy.context.window_manager.components_registry registry = bpy.context.window_manager.components_registry
registry_has_type_infos = registry.has_type_infos() registry_has_type_infos = registry.has_type_infos()
selected_component = target.components_meta.component_selector selected_component = target.components_meta.component_selector
internal = target.library is None
row = layout.row() row = layout.row()
col = row.column() col = row.column()
selector_text = f"{target.name}({item_type_short})" selector_text = f"{target.name}({item_type_short})"
if target.library is None: operator = col.operator("blenvy.select_item", text=selector_text, icon="FILE_BLEND")
operator = col.operator("blenvy.select_item", text=selector_text, icon="FILE_BLEND") operator.target_name = target.name
operator.target_name = target.name operator.item_type = item_type
operator.item_type = item_type col.enabled = internal
else:
col.label(text=selector_text, icon="LIBRARY_DATA_DIRECT")
col = row.column() col = row.column()
col.label(text=status) col.label(text=status)
@ -358,9 +356,12 @@ class BLENVY_PT_component_tools_panel(bpy.types.Panel):
col.label(text=component_name) col.label(text=component_name)
col = row.column() col = row.column()
# each components_meta has a component selector to pick components from if internal:
components_meta = target.components_meta # each components_meta has a component selector to pick components from
col.prop(components_meta, "component_selector", text="") components_meta = target.components_meta
col.prop(components_meta, "component_selector", text="")
else:
col.label(text="external, cannot edit")
col = row.column() col = row.column()
@ -369,7 +370,7 @@ class BLENVY_PT_component_tools_panel(bpy.types.Panel):
operator.original_name = component_name operator.original_name = component_name
operator.target_items = json.dumps([(target.name, item_type)]) # tupple operator.target_items = json.dumps([(target.name, item_type)]) # tupple
operator.target_name = target_component_name operator.target_name = target_component_name
col.enabled = registry_has_type_infos and component_name != "" and target_component_name != "" and component_name != target_component_name col.enabled = internal and registry_has_type_infos and component_name != "" and target_component_name != "" and component_name != target_component_name
col = row.column() col = row.column()
@ -377,6 +378,7 @@ class BLENVY_PT_component_tools_panel(bpy.types.Panel):
operator.item_name = target.name operator.item_name = target.name
operator.component_name = component_name operator.component_name = component_name
operator.item_type = get_selection_type(target) operator.item_type = get_selection_type(target)
col.enabled = internal
def draw_invalid_items(self, layout, upgreadable_entries): def draw_invalid_items(self, layout, upgreadable_entries):
for entry in upgreadable_entries: for entry in upgreadable_entries:

View File

@ -10,7 +10,7 @@ def select_area(context, area_name):
for area in context.screen.areas: for area in context.screen.areas:
#if area.type == 'PROPERTIES' and context.object is not None and context.object.type not in ('LIGHT_PROBE', 'CAMERA', 'LIGHT', 'SPEAKER'): #if area.type == 'PROPERTIES' and context.object is not None and context.object.type not in ('LIGHT_PROBE', 'CAMERA', 'LIGHT', 'SPEAKER'):
# Set it the active space # Set it the active space
print("SELECT AREA", area_name) #print("SELECT AREA", area_name)
try: try:
area.spaces.active.context = area_name #'MATERIAL' # 'VIEW_LAYER', 'SCENE' etc. area.spaces.active.context = area_name #'MATERIAL' # 'VIEW_LAYER', 'SCENE' etc.
except Exception as error: except Exception as error:
@ -103,7 +103,6 @@ class BLENVY_OT_item_select(Operator):
bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.select_all(action='DESELECT')
bpy.context.window.scene = scene_of_collection bpy.context.window.scene = scene_of_collection
#bpy.context.view_layer.objects.active = None #bpy.context.view_layer.objects.active = None
#
context.window_manager.blenvy_item_selected_ids = json.dumps({"name": collection.name, "type": self.item_type}) context.window_manager.blenvy_item_selected_ids = json.dumps({"name": collection.name, "type": self.item_type})
set_active_collection(bpy.context.window.scene, collection.name) set_active_collection(bpy.context.window.scene, collection.name)
@ -116,7 +115,6 @@ class BLENVY_OT_item_select(Operator):
if scene_of_item is not None: if scene_of_item is not None:
bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.select_all(action='DESELECT')
bpy.context.window.scene = scene_of_item bpy.context.window.scene = scene_of_item
mesh_object.select_set(True)
bpy.context.view_layer.objects.active = mesh_object bpy.context.view_layer.objects.active = mesh_object
context.window_manager.blenvy_item_selected_ids = json.dumps({"name": mesh.name, "type": self.item_type}) context.window_manager.blenvy_item_selected_ids = json.dumps({"name": mesh.name, "type": self.item_type})
@ -128,12 +126,9 @@ class BLENVY_OT_item_select(Operator):
material_object = get_material_object(material) material_object = get_material_object(material)
scene_of_item = get_object_scene(material_object) scene_of_item = get_object_scene(material_object)
select_area(context=context, area_name="MATERIAL") select_area(context=context, area_name="MATERIAL")
print("scene_of_item", scene_of_item)
if scene_of_item is not None: if scene_of_item is not None:
bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.select_all(action='DESELECT')
bpy.context.window.scene = scene_of_item bpy.context.window.scene = scene_of_item
#material_object.select_set(True)
bpy.context.view_layer.objects.active = material_object bpy.context.view_layer.objects.active = material_object
context.window_manager.blenvy_item_selected_ids = json.dumps({"name": material.name, "type": self.item_type}) context.window_manager.blenvy_item_selected_ids = json.dumps({"name": material.name, "type": self.item_type})
@ -154,20 +149,6 @@ def get_selected_item(context):
#print("original context", context) #print("original context", context)
try:
selection_overrides = json.loads(context.window_manager.blenvy_item_selected_ids)
#print("selection_overrides", selection_overrides)
if selection_overrides["type"] == "OBJECT":
selection = bpy.data.objects[selection_overrides["name"]]
elif selection_overrides["type"] == "COLLECTION":
selection = bpy.data.collections[selection_overrides["name"]]
if selection_overrides["type"] == "MESH":
selection = bpy.data.meshes[selection_overrides["name"]]
elif selection_overrides["type"] == "MATERIAL":
selection = bpy.data.materials[selection_overrides["name"]]
#print("SELECTION", selection)
#context.window_manager.blenvy_item_selected_ids = "{}"
except: pass
if selection is None: if selection is None:
area = get_outliner_area() area = get_outliner_area()
@ -175,8 +156,8 @@ def get_selected_item(context):
region = next(region for region in area.regions if region.type == "WINDOW") region = next(region for region in area.regions if region.type == "WINDOW")
with bpy.context.temp_override(area=area, region=region): with bpy.context.temp_override(area=area, region=region):
#print("overriden context", bpy.context) #print("overriden context", bpy.context)
for obj in bpy.context.selected_ids: """for obj in bpy.context.selected_ids:
print(f"Selected: {obj.name} - {type(obj)}") print(f"Selected: {obj.name} - {type(obj)}")"""
number_of_selections = len(bpy.context.selected_ids) number_of_selections = len(bpy.context.selected_ids)
selection = bpy.context.selected_ids[number_of_selections - 1] if number_of_selections > 0 else None #next(iter(bpy.context.selected_ids), None) selection = bpy.context.selected_ids[number_of_selections - 1] if number_of_selections > 0 else None #next(iter(bpy.context.selected_ids), None)
@ -185,6 +166,22 @@ def get_selected_item(context):
if selection is None: if selection is None:
number_of_selections = len(context.selected_objects) number_of_selections = len(context.selected_objects)
selection = context.selected_objects[number_of_selections - 1] if number_of_selections > 0 else None selection = context.selected_objects[number_of_selections - 1] if number_of_selections > 0 else None
if selection is None:
try:
selection_overrides = json.loads(context.window_manager.blenvy_item_selected_ids)
#print("selection_overrides", selection_overrides)
if selection_overrides["type"] == "OBJECT":
selection = bpy.data.objects[selection_overrides["name"]]
elif selection_overrides["type"] == "COLLECTION":
selection = bpy.data.collections[selection_overrides["name"]]
if selection_overrides["type"] == "MESH":
selection = bpy.data.meshes[selection_overrides["name"]]
elif selection_overrides["type"] == "MATERIAL":
selection = bpy.data.materials[selection_overrides["name"]]
#print("SELECTION", selection)
#context.window_manager.blenvy_item_selected_ids = "{}"
except: pass
return selection return selection