Compare commits

...

3 Commits

Author SHA1 Message Date
kaosat.dev
4b1268f0a3 feat(Blenvy):
* fixed handling of scene gltf_extras
 * fixed handling of colors for BlenderBackgroundShader
 * added scene tonemapping & scene colorgrading and handling on the Bevy side.
 * experimented with exporting ron asset files, updated & overhauled asset file generation, adapted
for blueprints
 * various cleanups
2024-06-23 19:14:00 +02:00
kaosat.dev
ed5dfeb3cd feat(Blenvy): removed local assets, as they are useless, renamed AllAssets to BlenvyAssets 2024-06-22 13:58:43 +02:00
kaosat.dev
c162c33575 feat(Blenvy): added support for Bevy components to meshes & materials
* added a much improved "get current selection in outliner" helper function
 * added MESH and MATERIAL variants to the type enums
 * added metadata to both Mesh & Material types
 * various related tweaks & improvements
2024-06-21 12:21:32 +02:00
28 changed files with 329 additions and 214 deletions

View File

@ -20,7 +20,7 @@ pub struct LocalAssets(pub Vec<MyAsset>);
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints /// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)] #[reflect(Component)]
pub struct AllAssets(pub Vec<MyAsset>); pub struct BlenvyAssets(pub Vec<MyAsset>);

View File

@ -123,7 +123,7 @@ impl Plugin for BlueprintsPlugin {
.register_type::<Vec<MyAsset>>() .register_type::<Vec<MyAsset>>()
.register_type::<Vec<String>>() .register_type::<Vec<String>>()
.register_type::<LocalAssets>() .register_type::<LocalAssets>()
.register_type::<AllAssets>() .register_type::<BlenvyAssets>()
.register_type::<HashMap<String, Vec<String>>>() .register_type::<HashMap<String, Vec<String>>>()

View File

@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap}; use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap};
use crate::{AllAssets, AssetsToLoad, AssetLoadTracker, BluePrintsConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded}; use crate::{BlenvyAssets, AssetsToLoad, AssetLoadTracker, BluePrintsConfig, 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)]
@ -76,9 +76,9 @@ pub(crate) fn test_thingy(
&BlueprintPath, &BlueprintPath,
Option<&Parent>,*/ Option<&Parent>,*/
Option<&Name>, Option<&Name>,
Option<&AllAssets>, Option<&BlenvyAssets>,
), ),
(Added<AllAssets>), // Added<AllAssets> (Added<BlenvyAssets>), // Added<BlenvyAssets>
>, >,

View File

@ -18,6 +18,19 @@ bevy = { version = "0.14.0-rc.3", default-features = false, features = ["bevy_as
serde = "1.0.188" serde = "1.0.188"
ron = "0.8.1" ron = "0.8.1"
serde_json = "1.0.108" serde_json = "1.0.108"
gltf = { version = "1.4.0", default-features = false, features = [
"KHR_lights_punctual",
"KHR_materials_transmission",
"KHR_materials_ior",
"KHR_materials_volume",
"KHR_materials_unlit",
"KHR_materials_emissive_strength",
"KHR_texture_transform",
"extras",
"extensions",
"names",
"utils",
] }
[dev-dependencies] [dev-dependencies]

View File

@ -15,12 +15,7 @@ pub struct MyAsset{
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints /// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)] #[reflect(Component)]
pub struct LocalAssets(pub Vec<MyAsset>); pub struct BlenvyAssets(pub Vec<MyAsset>);
/// helper component, is used to store the list of sub blueprints to enable automatic loading of dependend blueprints
#[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)]
pub struct AllAssets(pub Vec<MyAsset>);

View File

@ -50,26 +50,6 @@ impl Default for BluePrintBundle {
} }
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
pub enum GltfFormat {
#[default]
GLB,
GLTF,
}
impl fmt::Display for GltfFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GltfFormat::GLB => {
write!(f, "glb",)
}
GltfFormat::GLTF => {
write!(f, "gltf")
}
}
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
/// Plugin for gltf blueprints /// Plugin for gltf blueprints
pub struct BlueprintsPlugin { pub struct BlueprintsPlugin {
@ -112,8 +92,7 @@ impl Plugin for BlueprintsPlugin {
.register_type::<MyAsset>() .register_type::<MyAsset>()
.register_type::<Vec<MyAsset>>() .register_type::<Vec<MyAsset>>()
.register_type::<Vec<String>>() .register_type::<Vec<String>>()
.register_type::<LocalAssets>() .register_type::<BlenvyAssets>()
.register_type::<AllAssets>()
.add_event::<BlueprintEvent>() .add_event::<BlueprintEvent>()

View File

@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap}; use bevy::{gltf::Gltf, prelude::*, utils::hashbrown::HashMap};
use crate::{AllAssets, AssetsToLoad, AssetLoadTracker, BlenvyConfig, BlueprintAnimations, BlueprintAssetsLoaded, BlueprintAssetsNotLoaded}; use crate::{BlenvyAssets, AssetsToLoad, 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)]
@ -99,9 +99,9 @@ pub(crate) fn blueprints_prepare_spawn(
&BlueprintPath, &BlueprintPath,
Option<&Parent>,*/ Option<&Parent>,*/
Option<&Name>, Option<&Name>,
Option<&AllAssets>, Option<&BlenvyAssets>,
), ),
(Added<AllAssets>), // Added<AllAssets> (Added<BlenvyAssets>), // Added<BlenvyAssets>
>, >,
@ -111,7 +111,7 @@ pub(crate) fn blueprints_prepare_spawn(
&BlueprintName, &BlueprintName,
&BlueprintPath, &BlueprintPath,
Option<&Parent>, Option<&Parent>,
Option<&AllAssets>, Option<&BlenvyAssets>,
),(Added<BlueprintPath>) ),(Added<BlueprintPath>)
>, >,
mut commands: Commands, mut commands: Commands,

View File

@ -1,5 +1,7 @@
use bevy::core_pipeline::tonemapping::Tonemapping;
use bevy::pbr::DirectionalLightShadowMap; use bevy::pbr::DirectionalLightShadowMap;
use bevy::prelude::*; use bevy::prelude::*;
use bevy::render::view::{ColorGrading, ColorGradingGlobal, ColorGradingSection};
use crate::GltfComponentsSet; use crate::GltfComponentsSet;
@ -7,9 +9,12 @@ pub(crate) fn plugin(app: &mut App) {
app.register_type::<BlenderBackgroundShader>() app.register_type::<BlenderBackgroundShader>()
.register_type::<BlenderShadowSettings>() .register_type::<BlenderShadowSettings>()
.register_type::<BlenderLightShadows>() .register_type::<BlenderLightShadows>()
.register_type::<BlenderToneMapping>()
.register_type::<BlenderColorGrading>()
.add_systems( .add_systems(
Update, Update,
(process_lights, process_shadowmap, process_background_shader) (process_lights, process_shadowmap, process_background_shader, process_tonemapping, process_colorgrading)
.after(GltfComponentsSet::Injection), .after(GltfComponentsSet::Injection),
); );
} }
@ -40,6 +45,26 @@ pub struct BlenderShadowSettings {
pub cascade_size: usize, pub cascade_size: usize,
} }
/// Not all possible Blender ToneMappings are available in Bevy & vice versa
#[derive(Component, Reflect, Default, Debug, PartialEq, Clone)]
#[reflect(Component)]
#[non_exhaustive]
pub enum BlenderToneMapping {
#[default]
None,
AgX,
Filmic
}
#[derive(Component, Reflect, Default, Debug, PartialEq, Clone)]
#[reflect(Component)]
#[non_exhaustive]
pub struct BlenderColorGrading {
exposure: f32,
gamma: f32,
}
fn process_lights( fn process_lights(
mut directional_lights: Query< mut directional_lights: Query<
(&mut DirectionalLight, Option<&BlenderLightShadows>), (&mut DirectionalLight, Option<&BlenderLightShadows>),
@ -51,23 +76,17 @@ fn process_lights(
for (mut light, blender_light_shadows) in directional_lights.iter_mut() { for (mut light, blender_light_shadows) in directional_lights.iter_mut() {
if let Some(blender_light_shadows) = blender_light_shadows { if let Some(blender_light_shadows) = blender_light_shadows {
light.shadows_enabled = blender_light_shadows.enabled; light.shadows_enabled = blender_light_shadows.enabled;
} else { }
light.shadows_enabled = true;
}
} }
for (mut light, blender_light_shadows) in spot_lights.iter_mut() { for (mut light, blender_light_shadows) in spot_lights.iter_mut() {
if let Some(blender_light_shadows) = blender_light_shadows { if let Some(blender_light_shadows) = blender_light_shadows {
light.shadows_enabled = blender_light_shadows.enabled; light.shadows_enabled = blender_light_shadows.enabled;
} else { }
light.shadows_enabled = true;
}
} }
for (mut light, blender_light_shadows) in point_lights.iter_mut() { for (mut light, blender_light_shadows) in point_lights.iter_mut() {
if let Some(blender_light_shadows) = blender_light_shadows { if let Some(blender_light_shadows) = blender_light_shadows {
light.shadows_enabled = blender_light_shadows.enabled; light.shadows_enabled = blender_light_shadows.enabled;
} else {
light.shadows_enabled = true;
} }
} }
} }
@ -88,10 +107,76 @@ fn process_background_shader(
mut commands: Commands, mut commands: Commands,
) { ) {
for background_shader in background_shaders.iter() { for background_shader in background_shaders.iter() {
println!("HEYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY {:?}", background_shader.color);
commands.insert_resource(AmbientLight { commands.insert_resource(AmbientLight {
color: background_shader.color, color: background_shader.color,
// Just a guess, see <https://github.com/bevyengine/bevy/issues/12280> // Just a guess, see <https://github.com/bevyengine/bevy/issues/12280>
brightness: background_shader.strength * 400.0, brightness: background_shader.strength * 400.0,
}); });
commands.insert_resource(ClearColor(background_shader.color));
} }
} }
// FIXME: this logic should not depend on if toneMapping or Cameras where added first
fn process_tonemapping(
tonemappings: Query<&BlenderToneMapping , Added<BlenderToneMapping>>,
cameras: Query<Entity, With<Camera>>,
mut commands: Commands,
){
for entity in cameras.iter(){
for tone_mapping in tonemappings.iter(){
match tone_mapping {
BlenderToneMapping::None => {
println!("TONEMAPPING NONE");
commands.entity(entity).remove::<Tonemapping>();
}
BlenderToneMapping::AgX => {
println!("TONEMAPPING Agx");
commands.entity(entity).insert(Tonemapping::AgX);
}
BlenderToneMapping::Filmic => {
println!("TONEMAPPING Filmic");
commands.entity(entity).insert(Tonemapping::BlenderFilmic);
}
}
}
}
}
// FIXME: this logic should not depend on if toneMapping or Cameras where added first
fn process_colorgrading(
blender_colorgradings: Query<&BlenderColorGrading , Added<BlenderColorGrading>>,
cameras: Query<Entity, With<Camera>>,
mut commands: Commands,
){
for entity in cameras.iter(){
for blender_colorgrading in blender_colorgradings.iter(){
println!("COLOR GRADING");
commands.entity(entity).insert(
ColorGrading{
global: ColorGradingGlobal{
exposure: blender_colorgrading.exposure,
..Default::default()
},
shadows: ColorGradingSection{
gamma: blender_colorgrading.gamma,
..Default::default()
},
midtones: ColorGradingSection{
gamma: blender_colorgrading.gamma,
..Default::default()
},
highlights: ColorGradingSection{
gamma: blender_colorgrading.gamma,
..Default::default()
},
..Default::default()
}
);
}
}
}

View File

@ -16,14 +16,14 @@ use bevy::{
use crate::{ronstring_to_reflect_component, GltfProcessed}; use crate::{ronstring_to_reflect_component, GltfProcessed};
// , mut entity_components: HashMap<Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>> // , mut entity_components: HashMap<Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>>
fn find_entity_components(entity: Entity, name: &Name, parent: &Parent, reflect_components: Vec<(Box<dyn Reflect>, TypeRegistration)>, entity_components: &HashMap<Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>>) -> (Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>){ fn find_entity_components(entity: Entity, name: &Name, parent: Option<&Parent>, reflect_components: Vec<(Box<dyn Reflect>, TypeRegistration)>, entity_components: &HashMap<Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>>) -> (Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>){
// we assign the components specified /xxx_components objects to their parent node // we assign the components specified /xxx_components objects to their parent node
let mut target_entity = entity; let mut target_entity = entity;
// if the node contains "components" or ends with "_pa" (ie add to parent), the components will not be added to the entity itself but to its parent // if the node contains "components" or ends with "_pa" (ie add to parent), the components will not be added to the entity itself but to its parent
// this is mostly used for Blender collections // this is mostly used for Blender collections
if name.as_str().contains("components") || name.as_str().ends_with("_pa") { if parent.is_some() && (name.as_str().contains("components") || name.as_str().ends_with("_pa")) {
debug!("adding components to parent"); debug!("adding components to parent");
target_entity = parent.get(); target_entity = parent.expect("the target entity had a parent ").get();
} }
debug!("adding to {:?}", target_entity); debug!("adding to {:?}", target_entity);
@ -50,12 +50,10 @@ fn find_entity_components(entity: Entity, name: &Name, parent: &Parent, reflect_
/// main function: injects components into each entity in gltf files that have `gltf_extras`, using reflection /// main function: injects components into each entity in gltf files that have `gltf_extras`, using reflection
pub fn add_components_from_gltf_extras(world: &mut World) { pub fn add_components_from_gltf_extras(world: &mut World) {
let mut extras = let mut extras = world.query_filtered::<(Entity, &Name, &GltfExtras, Option<&Parent>), (Added<GltfExtras>, Without<GltfProcessed>)>();
world.query_filtered::<(Entity, &Name, &GltfExtras, &Parent), (Added<GltfExtras>, Without<GltfProcessed>)>(); let mut scene_extras = world.query_filtered::<(Entity, &Name, &GltfSceneExtras, Option<&Parent>), (Added<GltfSceneExtras>, Without<GltfProcessed>)>();
let mut mesh_extras = world.query_filtered::<(Entity, &Name, &GltfMeshExtras, Option<&Parent>), (Added<GltfMeshExtras>, Without<GltfProcessed>)>();
let mut scene_extras = world.query_filtered::<(Entity, &Name, &GltfSceneExtras, &Parent), (Added<GltfSceneExtras>, Without<GltfProcessed>)>(); let mut material_extras = world.query_filtered::<(Entity, &Name, &GltfMaterialExtras, Option<&Parent>), (Added<GltfMaterialExtras>, Without<GltfProcessed>)>();
let mut mesh_extras = world.query_filtered::<(Entity, &Name, &GltfMeshExtras, &Parent), (Added<GltfMeshExtras>, Without<GltfProcessed>)>();
let mut material_extras = world.query_filtered::<(Entity, &Name, &GltfMaterialExtras, &Parent), (Added<GltfMaterialExtras>, Without<GltfProcessed>)>();
let mut entity_components: HashMap<Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>> = let mut entity_components: HashMap<Entity, Vec<(Box<dyn Reflect>, TypeRegistration)>> =
HashMap::new(); HashMap::new();
@ -63,6 +61,7 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
// let gltf_components_config = world.resource::<GltfComponentsConfig>(); // let gltf_components_config = world.resource::<GltfComponentsConfig>();
for (entity, name, extra, parent) in extras.iter(world) { for (entity, name, extra, parent) in extras.iter(world) {
println!("GLTF EXTRA !!!!");
debug!( debug!(
"Name: {}, entity {:?}, parent: {:?}, extras {:?}", "Name: {}, entity {:?}, parent: {:?}, extras {:?}",
name, entity, parent, extra name, entity, parent, extra
@ -78,6 +77,8 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
for (entity, name, extra, parent) in scene_extras.iter(world) { for (entity, name, extra, parent) in scene_extras.iter(world) {
println!("GLTF SCENE EXTRA !!!!");
debug!( debug!(
"Name: {}, entity {:?}, parent: {:?}, scene_extras {:?}", "Name: {}, entity {:?}, parent: {:?}, scene_extras {:?}",
name, entity, parent, extra name, entity, parent, extra
@ -92,6 +93,8 @@ pub fn add_components_from_gltf_extras(world: &mut World) {
} }
for (entity, name, extra, parent) in mesh_extras.iter(world) { for (entity, name, extra, parent) in mesh_extras.iter(world) {
println!("GLTF MESH EXTRA !!!!");
debug!( debug!(
"Name: {}, entity {:?}, parent: {:?}, mesh_extras {:?}", "Name: {}, entity {:?}, parent: {:?}, mesh_extras {:?}",
name, entity, parent, extra name, entity, parent, extra

View File

@ -1,5 +1,5 @@
use bevy::log::{debug, warn}; use bevy::log::{debug, warn};
use bevy::reflect::serde::ReflectDeserializer; use bevy::reflect::serde::{ReflectDeserializer, ReflectSerializer};
use bevy::reflect::{Reflect, TypeRegistration, TypeRegistry}; use bevy::reflect::{Reflect, TypeRegistration, TypeRegistry};
use bevy::utils::HashMap; use bevy::utils::HashMap;
use ron::Value; use ron::Value;
@ -58,12 +58,16 @@ fn components_string_to_components(
parsed_value parsed_value
); );
/*
// usefull to determine what an entity looks like Serialized // usefull to determine what an entity looks like Serialized
/*let test_struct = CameraRenderGraph::new("name"); let test_struct = Color::Srgba(Srgba { red: 0.2, green: 0.2, blue: 0.2, alpha: 0.2 });
//CameraRenderGraph::new("name");
let serializer = ReflectSerializer::new(&test_struct, &type_registry); let serializer = ReflectSerializer::new(&test_struct, &type_registry);
let serialized = let serialized =
ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap(); ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap();
println!("serialized Component {}", serialized);*/ println!("serialized Component {}", serialized);
*/
debug!("component data ron string {}", ron_string); debug!("component data ron string {}", ron_string);
let mut deserializer = ron::Deserializer::from_str(ron_string.as_str()) let mut deserializer = ron::Deserializer::from_str(ron_string.as_str())

View File

@ -13231,11 +13231,11 @@
"type": "object", "type": "object",
"typeInfo": "Struct" "typeInfo": "Struct"
}, },
"blenvy::blueprints::assets::AllAssets": { "blenvy::blueprints::assets::BlenvyAssets": {
"isComponent": true, "isComponent": true,
"isResource": false, "isResource": false,
"items": false, "items": false,
"long_name": "blenvy::blueprints::assets::AllAssets", "long_name": "blenvy::blueprints::assets::BlenvyAssets",
"prefixItems": [ "prefixItems": [
{ {
"type": { "type": {
@ -13243,23 +13243,7 @@
} }
} }
], ],
"short_name": "AllAssets", "short_name": "BlenvyAssets",
"type": "array",
"typeInfo": "TupleStruct"
},
"blenvy::blueprints::assets::LocalAssets": {
"isComponent": true,
"isResource": false,
"items": false,
"long_name": "blenvy::blueprints::assets::LocalAssets",
"prefixItems": [
{
"type": {
"$ref": "#/$defs/alloc::vec::Vec<blenvy::blueprints::assets::MyAsset>"
}
}
],
"short_name": "LocalAssets",
"type": "array", "type": "array",
"typeInfo": "TupleStruct" "typeInfo": "TupleStruct"
}, },

View File

@ -7,7 +7,7 @@ pub use animation::*;
use std::{collections::HashMap, fs, time::Duration}; use std::{collections::HashMap, fs, time::Duration};
use blenvy::{ use blenvy::{
AllAssets, BlueprintAnimationPlayerLink, BlueprintEvent, BlueprintName, GltfBlueprintsSet, SceneAnimations BlenvyAssets, BlueprintAnimationPlayerLink, BlueprintEvent, BlueprintName, GltfBlueprintsSet, SceneAnimations
}; };
use bevy::{ use bevy::{
@ -39,7 +39,7 @@ fn validate_export(
scene_animations: Query<(Entity, &SceneAnimations)>, scene_animations: Query<(Entity, &SceneAnimations)>,
empties_candidates: Query<(Entity, &Name, &GlobalTransform)>, empties_candidates: Query<(Entity, &Name, &GlobalTransform)>,
assets_list: Query<(Entity, &AllAssets)>, assets_list: Query<(Entity, &BlenvyAssets)>,
root: Query<(Entity, &Name, &Children), (Without<Parent>, With<Children>)>, root: Query<(Entity, &Name, &Children), (Without<Parent>, With<Children>)>,
) { ) {
let animations_found = let animations_found =

View File

@ -1,5 +1,5 @@
use bevy::{gltf::{GltfMaterialExtras, GltfMeshExtras, GltfSceneExtras}, prelude::*}; use bevy::{gltf::{GltfMaterialExtras, GltfMeshExtras, GltfSceneExtras}, prelude::*};
use blenvy::{AllAssets, BlueprintInstanceReady}; use blenvy::{BlenvyAssets, BlueprintInstanceReady};
use crate::BasicTest; use crate::BasicTest;
@ -32,7 +32,7 @@ pub fn get_descendants(
all_children: &Query<&Children>, all_children: &Query<&Children>,
all_names:&Query<&Name>, root: &Entity, all_names:&Query<&Name>, root: &Entity,
nesting: usize, nesting: usize,
to_check: &Query<&BasicTest>//&Query<(&BlueprintInstanceReady, &AllAssets)>, to_check: &Query<&BasicTest>//&Query<(&BlueprintInstanceReady, &BlenvyAssets)>,
) )
-> String -> String
{ {
@ -67,7 +67,7 @@ pub fn draw_hierarchy_debug(
all_children: Query<&Children>, all_children: Query<&Children>,
all_names:Query<&Name>, all_names:Query<&Name>,
to_check: Query<&BasicTest>,//Query<(&BlueprintInstanceReady, &AllAssets)>, to_check: Query<&BasicTest>,//Query<(&BlueprintInstanceReady, &BlenvyAssets)>,
mut display: Query<&mut Text, With<HiearchyDebugTag>>, mut display: Query<&mut Text, With<HiearchyDebugTag>>,
){ ){
let mut hierarchy_display: Vec<String> = vec![]; let mut hierarchy_display: Vec<String> = vec![];

View File

@ -15,7 +15,7 @@ Auto export
- [x] main/ library scene names - [x] main/ library scene names
- [x] paths - [x] paths
- [ ] Data storage for custom properties: - [x] Data storage for custom properties:
- for scenes (main scenes) - for scenes (main scenes)
- at scene level - at scene level
- for blueprints - for blueprints
@ -59,12 +59,11 @@ Components:
- [x] BLENVY_OT_component_fix - [x] BLENVY_OT_component_fix
- [x] add handling for core::ops::Range<f32> & other ranges - [x] add handling for core::ops::Range<f32> & other ranges
- [x] fix is_component_valid that is used in gltf_auto_export - [x] fix is_component_valid that is used in gltf_auto_export
- Hashmap Support - [x] Hashmap Support
- [x] fix parsing of keys's type either on Bevy side (prefered) or on the Blender side - [x] fix parsing of keys's type either on Bevy side (prefered) or on the Blender side
- [x] fix weird issue with missing "0" property when adding new entry in empty hashmap => happens only if the values for the "setter" have never been set - [x] fix weird issue with missing "0" property when adding new entry in empty hashmap => happens only if the values for the "setter" have never been set
- [ ] handle missing types in registry for keys & values - [ ] handle missing types in registry for keys & values
- [x] adding a hashmap nukes every existing component ?? - [x] adding a hashmap nukes every existing component ??
- [x] Add correct upgrade handling from individual component to bevy_components - [x] Add correct upgrade handling from individual component to bevy_components
- [x] Settings handling: - [x] Settings handling:
- [x] move saveable settings out to a settings file - [x] move saveable settings out to a settings file
@ -77,8 +76,6 @@ Components:
- perhaps just add a display list of all NON component custom properties, so the user can find them easilly ? - perhaps just add a display list of all NON component custom properties, so the user can find them easilly ?
- [x] status "unregistered" is often false and misleading - [x] status "unregistered" is often false and misleading
-> see in registry ui "for custom_property in object.keys():" -> see in registry ui "for custom_property in object.keys():"
- [x] overhaul / improve the component selector (with built in searching, etc) - [x] overhaul / improve the component selector (with built in searching, etc)
- [x] remove select_component_name_to_replace - [x] remove select_component_name_to_replace
- [x] display of invalid components is not working ? - [x] display of invalid components is not working ?
@ -87,7 +84,6 @@ Components:
- BLENVY_OT_component_list_add_item - BLENVY_OT_component_list_add_item
- BLENVY_OT_component_list_remove_item - BLENVY_OT_component_list_remove_item
- BLENVY_OT_component_list_select_item: merge it into the rest of the actions - BLENVY_OT_component_list_select_item: merge it into the rest of the actions
- [x] clearing invalid flag after a registry change does not work correctly (ie the ui still says the component is invalid) - [x] clearing invalid flag after a registry change does not work correctly (ie the ui still says the component is invalid)
- [x] should reset ALL "invalid" flags IF they have the matching data - [x] should reset ALL "invalid" flags IF they have the matching data
- [x] registry auto reload not working ? - [x] registry auto reload not working ?
@ -96,7 +92,6 @@ Components:
- now switched to tiger_hash - now switched to tiger_hash
- [x] add warning about hash colision (not much we can/ could do if it is the case ?) - [x] add warning about hash colision (not much we can/ could do if it is the case ?)
- [x] double check weird collisions AND/OR reuse existing if applicable - [x] double check weird collisions AND/OR reuse existing if applicable
- [x] annoying default path for registry, should be relative to the assets path - [x] annoying default path for registry, should be relative to the assets path
@ -127,53 +122,55 @@ General issues:
- [ ] add handling of errors when trying to load settings - [ ] add handling of errors when trying to load settings
- [ ] force overwrite of settings files instead of partial updates ?
- [ ] add tests for disabled components
- [x] fix auto export workflow - [x] fix auto export workflow
- [ ] should we write the previous _xxx data only AFTER a sucessfull export only ?
- [x] add hashing of modifiers/ geometry nodes in serialize scene - [x] add hashing of modifiers/ geometry nodes in serialize scene
- [x] add ability to FORCE export specific blueprints & levels - [x] add ability to FORCE export specific blueprints & levels
- [ ] undo after a save removes any saved "serialized scene" data ? DIG into this
- [ ] handle scene renames between saves (breaks diffing)
- [x] change scene selector to work on actual scenes aka to deal with renamed scenes - [x] change scene selector to work on actual scenes aka to deal with renamed scenes
- [x] remove get_main_and_library_scenes as it should not be needed anymore - [x] remove get_main_and_library_scenes as it should not be needed anymore
- [x] fix asset file selection - [x] fix asset file selection
- [x] change "assets" tab to "levels"/worlds tab & modify UI accordingly - [x] change "assets" tab to "levels"/worlds tab & modify UI accordingly
- [ ] add option to 'split out' meshes from blueprints ? - [x] remove local assets, useless
- [ ] ie considering meshletts etc , it would make sense to keep blueprints seperate from purely mesh gltfs
- [x] remove 'export_marked_assets' it should be a default setting - [x] remove 'export_marked_assets' it should be a default setting
- [x] disable/ hide asset editing ui for external assets - [x] disable/ hide asset editing ui for external assets
- [ ] inject_export_path_into_internal_blueprints should be called on every asset/blueprint scan !! Not just on export
- [x] fix level asets UI - [x] fix level asets UI
- [x] remove BlueprintsList & replace is with assets list
- [x] switch to bevy 0.14 rc2
- [x] trigger events when assets are loaded, blueprints are spawned & co
- [x] overall cleanup
- [x] object.add_bevy_component => blenvy.component_add
- [ ] inject_export_path_into_internal_blueprints should be called on every asset/blueprint scan !! Not just on export
- [ ] undo after a save removes any saved "serialized scene" data ? DIG into this
- [ ] handle scene renames between saves (breaks diffing) => very hard to achieve
- [ ] force overwrite of settings files instead of partial updates ?
- [ ] add tests for disabled components
- [ ] should we write the previous _xxx data only AFTER a sucessfull export only ?
- [ ] add option to 'split out' meshes from blueprints ?
- [ ] ie considering meshletts etc , it would make sense to keep blueprints seperate from purely mesh gltfs
- [ ] persist exported materials path in blueprints so that it can be read from library file users - [ ] persist exported materials path in blueprints so that it can be read from library file users
- [ ] just like "export_path" write it into each blueprint's collection - [ ] just like "export_path" write it into each blueprint's collection
- [ ] 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 ?)
- [x] remove BlueprintsList & replace is with assets list
- [ ] update main docs
- [ ] rename project to Blenvy
- [ ] replace all references to the old 2 add-ons with those to Blenvy
- [ ] rename repo to "Blenvy"
- [x] switch to bevy 0.14 rc2
- [ ] find a solution for the new color handling - [ ] find a solution for the new color handling
- [ ] add back lighting_components - [ ] add back lighting_components
- [ ] check if scene components are being deleted through our scene re-orgs in the spawn post process - [ ] check if scene components are being deleted through our scene re-orgs in the spawn post process
- [x] trigger events when assets are loaded, blueprints are spawned & co
- [ ] should "blueprint spawned" only be triggered after all its sub blueprints have spawned ? - [ ] should "blueprint spawned" only be triggered after all its sub blueprints have spawned ?
- [ ] 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
- [ ] do a deprecation release of all bevy_gltf_xxx crates to point at the new Blenvy crate - [ ] try out hot reloading
- [ ] simplify examples: - [ ] 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
- [ ] update main docs
- [ ] rename project to Blenvy
- [ ] replace all references to the old 2 add-ons with those to Blenvy
- [ ] rename repo to "Blenvy"
- [ ] do a deprecation release of all bevy_gltf_xxx crates to point at the new Blenvy crate
- [ ] hidden objects/collections not respected at export !!!
- [x] overall cleanup
- [x] object.add_bevy_component => blenvy.component_add
clear && pytest -svv --blender-template ../../testing/bevy_example/art/testing_library.blend --blender-executable /home/ckaos/tools/blender/blender-4.1.0-linux-x64/blender tests/test_bevy_integration_prepare.py && pytest -svv --blender-executable /home/ckaos/tools/blender/blender-4.1.0-linux-x64/blender tests/test_bevy_integration.py clear && pytest -svv --blender-template ../../testing/bevy_example/art/testing_library.blend --blender-executable /home/ckaos/tools/blender/blender-4.1.0-linux-x64/blender tests/test_bevy_integration_prepare.py && pytest -svv --blender-executable /home/ckaos/tools/blender/blender-4.1.0-linux-x64/blender tests/test_bevy_integration.py

View File

@ -1,5 +1,7 @@
import os import os
import bpy import bpy
from blenvy.assets.assets_scan import get_blueprint_asset_tree
from blenvy.assets.generate_asset_file import write_ron_assets_file
from ..constants import TEMPSCENE_PREFIX from ..constants import TEMPSCENE_PREFIX
from ..common.generate_temporary_scene_and_export import generate_temporary_scene_and_export, copy_hollowed_collection_into, clear_hollow_scene from ..common.generate_temporary_scene_and_export import generate_temporary_scene_and_export, copy_hollowed_collection_into, clear_hollow_scene
from ..common.export_gltf import generate_gltf_export_settings from ..common.export_gltf import generate_gltf_export_settings
@ -37,8 +39,7 @@ def export_blueprints(blueprints, settings, blueprints_data):
all_assets = [] all_assets = []
auto_assets = [] auto_assets = []
collection["local_assets"] = assets_to_fake_ron([{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets) collection["BlenvyAssets"] = assets_to_fake_ron([{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets) #all_assets + [{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets)
collection["AllAssets"] = assets_to_fake_ron([{"name": asset.name, "path": asset.path} for asset in collection.user_assets]) #all_assets + [{"name": asset.name, "path": asset.path} for asset in collection.user_assets] + auto_assets)
# do the actual export # do the actual export
@ -52,6 +53,9 @@ def export_blueprints(blueprints, settings, blueprints_data):
tempScene_cleaner= lambda temp_scene, params: clear_hollow_scene(original_root_collection=collection, temp_scene=temp_scene, **params) tempScene_cleaner= lambda temp_scene, params: clear_hollow_scene(original_root_collection=collection, temp_scene=temp_scene, **params)
) )
#blueprint_asset_tree = get_blueprint_asset_tree(blueprint=blueprint, blueprints_data=blueprints_data, settings=settings)
#write_ron_assets_file(blueprint.name, blueprint_asset_tree, output_path_full = blueprints_path_full)
# reset active collection to the one we save before # reset active collection to the one we save before
bpy.context.view_layer.active_layer_collection = active_collection bpy.context.view_layer.active_layer_collection = active_collection

View File

@ -20,7 +20,7 @@ def generate_temporary_scene_and_export(settings, gltf_export_settings, gltf_out
temp_root_collection = temp_scene.collection temp_root_collection = temp_scene.collection
print("additional_dataAAAAAAAAAAAAAAAH", additional_data) print("additional_dataAAAAAAAAAAAAAAAH", additional_data)
properties_black_list = ['user_assets', 'components_meta'] properties_black_list = ['glTF2ExportSettings', 'user_assets', 'components_meta']
if additional_data is not None: # FIXME not a fan of having this here if additional_data is not None: # FIXME not a fan of having this here
for entry in dict(additional_data): for entry in dict(additional_data):
# we copy everything over except those on the black list # we copy everything over except those on the black list

View File

@ -5,14 +5,12 @@ from blenvy.core.object_makers import make_empty
# TODO: replace this with placing scene level custom properties once support for that has been added to bevy_gltf # TODO: replace this with placing scene level custom properties once support for that has been added to bevy_gltf
def upsert_scene_components(main_scenes): def upsert_scene_components(main_scenes):
for scene in main_scenes: for scene in main_scenes:
"""lighting_components_name = f"lighting_components_{scene.name}" if scene.world is not None:
lighting_components = bpy.data.objects.get(lighting_components_name, None) scene['BlenderBackgroundShader'] = ambient_color_to_component(scene.world)
if not lighting_components: print("FOOOOO WORLD", dir(scene.world))
root_collection = scene.collection print("FOOOO scene", dir(scene))
lighting_components = make_empty('lighting_components_'+scene.name, [0,0,0], [0,0,0], [0,0,0], root_collection)""" print("foooo", dir(scene.view_settings))
print("GNAAA", scene.view_settings.view_transform)
"""if scene.world is not None:
lighting_components['BlenderBackgroundShader'] = ambient_color_to_component(scene.world)""" # FIXME add back
scene['BlenderShadowSettings'] = scene_shadows_to_component(scene) scene['BlenderShadowSettings'] = scene_shadows_to_component(scene)
if scene.eevee.use_bloom: if scene.eevee.use_bloom:
@ -25,13 +23,24 @@ def upsert_scene_components(main_scenes):
elif 'SSAOSettings' in scene: elif 'SSAOSettings' in scene:
del scene['SSAOSettings'] del scene['SSAOSettings']
scene['BlenderToneMapping'] = scene_tonemapping_to_component(scene)
scene['BlenderColorGrading'] = scene_colorgrading_to_component(scene)
def remove_scene_components(main_scenes): def remove_scene_components(main_scenes):
pass pass
"""for scene in main_scenes:
lighting_components_name = f"lighting_components_{scene.name}" def scene_tonemapping_to_component(scene):
lighting_components = bpy.data.objects.get(lighting_components_name, None) tone_mapping = scene.view_settings.view_transform
if lighting_components: blender_to_bevy = {
bpy.data.objects.remove(lighting_components, do_unlink=True)""" 'NONE': '',
'AgX': 'AgX',
'Filmic': 'Filmic',
}
bevy_tone_mapping = blender_to_bevy[tone_mapping] if tone_mapping in blender_to_bevy else None
return bevy_tone_mapping
def scene_colorgrading_to_component(scene):
return f"(exposure: {scene.view_settings.exposure}, gamma: {scene.view_settings.gamma})"
def ambient_color_to_component(world): def ambient_color_to_component(world):
@ -43,9 +52,8 @@ def ambient_color_to_component(world):
except Exception as ex: except Exception as ex:
print("failed to parse ambient color: Only background is supported") print("failed to parse ambient color: Only background is supported")
if color is not None and strength is not None: if color is not None and strength is not None:
colorRgba = f"LinearRgba(red: {color[0]}, green: {color[1]}, blue: {color[2]}, alpha: {color[3]})" colorRgba = f"LinearRgba((red: {color[0]}, green: {color[1]}, blue: {color[2]}, alpha: {color[3]}))"
component = f"( color: {colorRgba}, strength: {strength})" component = f"( color: {colorRgba}, strength: {strength})"
return component return component
return None return None
@ -62,4 +70,4 @@ def scene_bloom_to_component(scene):
def scene_ao_to_component(scene): def scene_ao_to_component(scene):
ssao = scene.eevee.use_gtao ssao = scene.eevee.use_gtao
component= "SSAOSettings()" component= "SSAOSettings()"
return component return component

View File

@ -78,9 +78,7 @@ def export_main_scene(scene, settings, blueprints_data):
materials_exported_path = os.path.join(materials_path, f"{materials_library_name}{export_gltf_extension}") materials_exported_path = os.path.join(materials_path, f"{materials_library_name}{export_gltf_extension}")
material_assets = [{"name": materials_library_name, "path": materials_exported_path}] # we also add the material library as an asset material_assets = [{"name": materials_library_name, "path": materials_exported_path}] # we also add the material library as an asset
#scene["BlenvyAssets"] = assets_to_fake_ron(all_assets + [{"name": asset.name, "path": asset.path} for asset in scene.user_assets] + auto_assets + material_assets)
scene["local_assets"] = assets_to_fake_ron([{"name": asset.name, "path": asset.path} for asset in scene.user_assets] + auto_assets + material_assets)
scene["AllAssets"] = assets_to_fake_ron(all_assets + [{"name": asset.name, "path": asset.path} for asset in scene.user_assets] + auto_assets + material_assets)
if export_separate_dynamic_and_static_objects: if export_separate_dynamic_and_static_objects:
@ -89,6 +87,7 @@ def export_main_scene(scene, settings, blueprints_data):
generate_temporary_scene_and_export( generate_temporary_scene_and_export(
settings, settings,
temp_scene_name=TEMPSCENE_PREFIX, temp_scene_name=TEMPSCENE_PREFIX,
additional_data = scene,
gltf_export_settings=gltf_export_settings, gltf_export_settings=gltf_export_settings,
gltf_output_path=gltf_output_path, gltf_output_path=gltf_output_path,
tempScene_filler= lambda temp_collection: copy_hollowed_collection_into(scene.collection, temp_collection, blueprints_data=blueprints_data, filter=is_object_static, settings=settings), tempScene_filler= lambda temp_collection: copy_hollowed_collection_into(scene.collection, temp_collection, blueprints_data=blueprints_data, filter=is_object_static, settings=settings),
@ -100,6 +99,7 @@ def export_main_scene(scene, settings, blueprints_data):
generate_temporary_scene_and_export( generate_temporary_scene_and_export(
settings, settings,
temp_scene_name=TEMPSCENE_PREFIX, temp_scene_name=TEMPSCENE_PREFIX,
additional_data = scene,
gltf_export_settings=gltf_export_settings, gltf_export_settings=gltf_export_settings,
gltf_output_path=gltf_output_path, gltf_output_path=gltf_output_path,
tempScene_filler= lambda temp_collection: copy_hollowed_collection_into(scene.collection, temp_collection, blueprints_data=blueprints_data, filter=is_object_dynamic, settings=settings), tempScene_filler= lambda temp_collection: copy_hollowed_collection_into(scene.collection, temp_collection, blueprints_data=blueprints_data, filter=is_object_dynamic, settings=settings),

View File

@ -42,6 +42,8 @@ class BLENVY_OT_component_list_actions(Operator):
items=( items=(
('OBJECT', "Object", ""), ('OBJECT', "Object", ""),
('COLLECTION', "Collection", ""), ('COLLECTION', "Collection", ""),
('MESH', "Mesh", ""),
('MATERIAL', "Material", ""),
), ),
default="OBJECT" default="OBJECT"
) # type: ignore ) # type: ignore

View File

@ -37,6 +37,8 @@ class BLENVY_OT_component_map_actions(Operator):
items=( items=(
('OBJECT', "Object", ""), ('OBJECT', "Object", ""),
('COLLECTION', "Collection", ""), ('COLLECTION', "Collection", ""),
('MESH', "Mesh", ""),
('MATERIAL', "Material", ""),
), ),
default="OBJECT" default="OBJECT"
) # type: ignore ) # type: ignore

View File

@ -61,14 +61,18 @@ class ComponentsMeta(PropertyGroup):
@classmethod @classmethod
def register(cls): def register(cls):
# you can add components to both objects & collections # you can add components to both objects , collections , meshes & materials
bpy.types.Object.components_meta = PointerProperty(type=ComponentsMeta) bpy.types.Object.components_meta = PointerProperty(type=ComponentsMeta)
bpy.types.Collection.components_meta = PointerProperty(type=ComponentsMeta) bpy.types.Collection.components_meta = PointerProperty(type=ComponentsMeta)
bpy.types.Mesh.components_meta = PointerProperty(type=ComponentsMeta)
bpy.types.Material.components_meta = PointerProperty(type=ComponentsMeta)
@classmethod @classmethod
def unregister(cls): def unregister(cls):
del bpy.types.Object.components_meta del bpy.types.Object.components_meta
del bpy.types.Collection.components_meta del bpy.types.Collection.components_meta
del bpy.types.Mesh.components_meta
del bpy.types.Material.components_meta
# remove no longer valid metadata from item # remove no longer valid metadata from item
def cleanup_invalid_metadata(item): def cleanup_invalid_metadata(item):

View File

@ -6,7 +6,7 @@ from bpy.props import (StringProperty, EnumProperty)
from .metadata import add_component_from_custom_property, add_component_to_item, apply_customProperty_values_to_item_propertyGroups, apply_propertyGroup_values_to_item_customProperties, apply_propertyGroup_values_to_item_customProperties_for_component, copy_propertyGroup_values_to_another_item, get_bevy_component_value_by_long_name, get_bevy_components, is_bevy_component_in_item, remove_component_from_item, rename_component, toggle_component from .metadata import add_component_from_custom_property, add_component_to_item, apply_customProperty_values_to_item_propertyGroups, apply_propertyGroup_values_to_item_customProperties, apply_propertyGroup_values_to_item_customProperties_for_component, copy_propertyGroup_values_to_another_item, get_bevy_component_value_by_long_name, get_bevy_components, is_bevy_component_in_item, remove_component_from_item, rename_component, toggle_component
from ..utils import get_selected_object_or_collection from ..utils import get_item_by_type, get_selected_item
class BLENVY_OT_component_add(Operator): class BLENVY_OT_component_add(Operator):
"""Add Bevy component to object/collection""" """Add Bevy component to object/collection"""
@ -20,7 +20,7 @@ class BLENVY_OT_component_add(Operator):
) # type: ignore ) # type: ignore
def execute(self, context): def execute(self, context):
target = get_selected_object_or_collection(context) target = get_selected_item(context)
print("adding component ", self.component_type, "to target '"+target.name+"'") print("adding component ", self.component_type, "to target '"+target.name+"'")
has_component_type = self.component_type != "" has_component_type = self.component_type != ""
@ -53,6 +53,8 @@ class BLENVY_OT_component_copy(Operator):
items=( items=(
('OBJECT', "Object", ""), ('OBJECT', "Object", ""),
('COLLECTION', "Collection", ""), ('COLLECTION', "Collection", ""),
('MESH', "Mesh", ""),
('MATERIAL', "Material", ""),
), ),
default="OBJECT" default="OBJECT"
) # type: ignore ) # type: ignore
@ -90,12 +92,14 @@ class BLENVY_OT_component_paste(Operator):
def execute(self, context): def execute(self, context):
source_item_name = context.window_manager.copied_source_item_name source_item_name = context.window_manager.copied_source_item_name
source_item_type = context.window_manager.copied_source_item_type source_item_type = context.window_manager.copied_source_item_type
if source_item_type == 'Object': source_item = get_item_by_type(source_item_type, source_item_name)
print("HEEEERRE", source_item_name, source_item_type, source_item)
"""if source_item_type == 'Object':
source_item = bpy.data.objects.get(source_item_name, None) source_item = bpy.data.objects.get(source_item_name, None)
elif source_item_type == 'Collection': elif source_item_type == 'Collection':
source_item = bpy.data.collections.get(source_item_name, None) source_item = bpy.data.collections.get(source_item_name, None)"""
if source_item == None: if source_item is None:
self.report({"ERROR"}, "The source object to copy a component from does not exist") self.report({"ERROR"}, "The source object to copy a component from does not exist")
else: else:
component_name = context.window_manager.copied_source_component_name component_name = context.window_manager.copied_source_component_name
@ -105,7 +109,7 @@ class BLENVY_OT_component_paste(Operator):
else: else:
print("pasting component to item:", source_item, "component name:", str(component_name), "component value:" + str(component_value)) print("pasting component to item:", source_item, "component name:", str(component_name), "component value:" + str(component_value))
registry = context.window_manager.components_registry registry = context.window_manager.components_registry
target_item = get_selected_object_or_collection(context) target_item = get_selected_item(context)
copy_propertyGroup_values_to_another_item(source_item, target_item, component_name, registry) copy_propertyGroup_values_to_another_item(source_item, target_item, component_name, registry)
return {'FINISHED'} return {'FINISHED'}
@ -133,7 +137,9 @@ class BLENVY_OT_component_remove(Operator):
items=( items=(
('OBJECT', "Object", ""), ('OBJECT', "Object", ""),
('COLLECTION', "Collection", ""), ('COLLECTION', "Collection", ""),
), ('MESH', "Mesh", ""),
('MATERIAL', "Material", ""),
),
default="OBJECT" default="OBJECT"
) # type: ignore ) # type: ignore
@ -142,10 +148,7 @@ class BLENVY_OT_component_remove(Operator):
if self.item_name == "": if self.item_name == "":
self.report({"ERROR"}, "The target to remove ("+ self.component_name +") from does not exist") self.report({"ERROR"}, "The target to remove ("+ self.component_name +") from does not exist")
else: else:
if self.item_type == 'OBJECT': target = get_item_by_type(self.item_type, self.item_name)
target = bpy.data.objects[self.item_name]
elif self.item_type == 'COLLECTION':
target = bpy.data.collections[self.item_name]
print("removing component ", self.component_name, "from object '"+target.name+"'") print("removing component ", self.component_name, "from object '"+target.name+"'")
@ -260,11 +263,7 @@ class BLENVY_OT_component_rename_component(Operator):
if original_name != '' and target_name != '' and original_name != target_name and len(target_items) > 0: if original_name != '' and target_name != '' and original_name != target_name and len(target_items) > 0:
for index, item_data in enumerate(target_items): for index, item_data in enumerate(target_items):
[item_name, item_type] = item_data [item_name, item_type] = item_data
item = None item = get_item_by_type(item_type, item_name)
if item_type == "OBJECT":
item = bpy.data.objects[item_name]
elif item_type == "COLLECTION":
item = bpy.data.collections[item_name]
if item and original_name in get_bevy_components(item) or original_name in item: if item and original_name in get_bevy_components(item) or original_name in item:
try: try:
@ -367,7 +366,7 @@ class BLENVY_OT_component_toggle_visibility(Operator):
) # type: ignore ) # type: ignore
def execute(self, context): def execute(self, context):
target = get_selected_object_or_collection(context) target = get_selected_item(context)
toggle_component(target, self.component_name) toggle_component(target, self.component_name)
return {'FINISHED'} return {'FINISHED'}

View File

@ -1,7 +1,7 @@
import json import json
import bpy import bpy
from ..utils import get_selection_type from ..utils import get_selected_item, get_selection_type
from .metadata import do_item_custom_properties_have_missing_metadata, get_bevy_components from .metadata import do_item_custom_properties_have_missing_metadata, get_bevy_components
@ -176,22 +176,17 @@ class BLENVY_PT_components_panel(bpy.types.Panel):
layout = self.layout layout = self.layout
name = "" name = ""
target_type = "" target_type = ""
object = next(iter(context.selected_objects), None) selected_item = get_selected_item(context)
collection = context.collection target_type = get_selection_type(selected_item)
if object is not None: name = selected_item.name if selected_item is not None else ''
name = object.name
target_type = "Object"
elif collection is not None:
name = collection.name
target_type = "Collection"
# name = context.object.name if context.object is not None else '' # name = context.object.name if context.object is not None else ''
layout.label(text=f"Components for {name} ({target_type})") layout.label(text=f"Components for {name} ({target_type})")
#print("object", context.object, "active", context.active_object, "objects", context.selected_objects) #print("object", context.object, "active", context.active_object, "objects", context.selected_objects)
def draw(self, context): def draw(self, context):
object = next(iter(context.selected_objects), None) selected_item = get_selected_item(context)
collection = context.collection
layout = self.layout layout = self.layout
# we get & load our component registry # we get & load our component registry
@ -199,10 +194,8 @@ class BLENVY_PT_components_panel(bpy.types.Panel):
selected_component = bpy.context.window_manager.blenvy.components.component_selector selected_component = bpy.context.window_manager.blenvy.components.component_selector
registry_has_type_infos = registry.has_type_infos() registry_has_type_infos = registry.has_type_infos()
if object is not None: if selected_item is not None:
draw_component_ui(layout, object, registry, selected_component, registry_has_type_infos, context) draw_component_ui(layout, selected_item, registry, selected_component, registry_has_type_infos, context)
elif collection is not None:
draw_component_ui(layout, collection, registry, selected_component, registry_has_type_infos, context)
else: else:
layout.label(text ="Select an object to edit its components") layout.label(text ="Select an object to edit its components")

View File

@ -4,13 +4,13 @@ import bpy
from .conversions_from_prop_group import property_group_value_to_custom_property_value from .conversions_from_prop_group import property_group_value_to_custom_property_value
from .process_component import process_component from .process_component import process_component
from .utils import update_calback_helper from .utils import update_calback_helper
from ..utils import get_selected_object_or_collection from ..utils import get_selected_item
## main callback function, fired whenever any property changes, no matter the nesting level ## main callback function, fired whenever any property changes, no matter the nesting level
def update_component(self, context, definition, component_name): def update_component(self, context, definition, component_name):
registry = bpy.context.window_manager.components_registry registry = bpy.context.window_manager.components_registry
current_object_or_collection = get_selected_object_or_collection(context) current_object_or_collection = get_selected_item(context)
update_disabled = current_object_or_collection["__disable__update"] if "__disable__update" in current_object_or_collection else False update_disabled = current_object_or_collection["__disable__update"] if "__disable__update" in current_object_or_collection else False
update_disabled = registry.disable_all_object_updates or update_disabled # global settings update_disabled = registry.disable_all_object_updates or update_disabled # global settings
if update_disabled: if update_disabled:

View File

@ -22,6 +22,8 @@ class BLENVY_OT_item_select(Operator):
items=( items=(
('OBJECT', "Object", ""), ('OBJECT', "Object", ""),
('COLLECTION', "Collection", ""), ('COLLECTION', "Collection", ""),
('MESH', "Mesh", ""),
('MATERIAL', "Material", ""),
), ),
default="OBJECT" default="OBJECT"
) # type: ignore ) # type: ignore
@ -53,19 +55,39 @@ class BLENVY_OT_item_select(Operator):
return {'FINISHED'} return {'FINISHED'}
#FIXME: does not work if object is hidden !! def get_selected_item(context):
def get_selected_object_or_collection(context): selection = None
target = None
object = next(iter(context.selected_objects), None) #print("original context", context)
collection = context.collection def get_outliner_area():
if object is not None: if bpy.context.area.type!='OUTLINER':
target = object for area in bpy.context.screen.areas:
elif collection is not None: if area.type == 'OUTLINER':
target = collection return area
return target return None
area = get_outliner_area()
if area is not None:
region = next(region for region in area.regions if region.type == "WINDOW")
with bpy.context.temp_override(area=area, region=region):
#print("overriden context", bpy.context)
for obj in bpy.context.selected_ids:
pass#print(f"Selected: {obj.name} - {type(obj)}")
selection = bpy.context.selected_ids[len(bpy.context.selected_ids) - 1] if len(bpy.context.selected_ids)>0 else None #next(iter(bpy.context.selected_ids), None)
"""if selection is not None:
print("selection", f"Selected: {selection.name} - {type(selection)}")"""
#print("SELECTIONS", context.selected_objects)
return selection
def get_selection_type(selection): def get_selection_type(selection):
#print("bla mesh", isinstance(selection, bpy.types.Mesh), "bli bli", selection.type)
if isinstance(selection, bpy.types.Material):
return 'MATERIAL'
if isinstance(selection, bpy.types.Mesh):
return 'MESH'
if isinstance(selection, bpy.types.Object): if isinstance(selection, bpy.types.Object):
return 'OBJECT' return 'OBJECT'
if isinstance(selection, bpy.types.Collection): if isinstance(selection, bpy.types.Collection):
@ -76,18 +98,13 @@ def get_item_by_type(item_type, item_name):
if item_type == 'OBJECT': if item_type == 'OBJECT':
item = bpy.data.objects[item_name] item = bpy.data.objects[item_name]
elif item_type == 'COLLECTION': elif item_type == 'COLLECTION':
print("item NAME", item_name)
item = bpy.data.collections[item_name] item = bpy.data.collections[item_name]
elif item_type == "MESH":
item = bpy.data.meshes[item_name]
elif item_type == 'MATERIAL':
item = bpy.data.materials[item_name]
return item return item
def get_selected_object_or_collection_by_item_type(context, item_type):
item = None
if item_type == 'OBJECT':
object = next(iter(context.selected_objects), None)
return object
elif item_type == 'COLLECTION':
return context.collection
def add_component_to_ui_list(self, context, _): def add_component_to_ui_list(self, context, _):
items = [] items = []
type_infos = context.window_manager.components_registry.type_infos type_infos = context.window_manager.components_registry.type_infos

View File

@ -121,3 +121,26 @@ def get_main_scene_assets_tree(main_scene, blueprints_data, settings):
added_asset.name = asset["name"] added_asset.name = asset["name"]
added_asset.path = asset["path"] added_asset.path = asset["path"]
return assets_list return assets_list
def get_blueprint_asset_tree(blueprint, blueprints_data, settings):
blueprints_path = getattr(settings, "blueprints_path")
export_gltf_extension = getattr(settings.auto_export, "export_gltf_extension", ".glb")
assets_list = get_user_assets_as_list(blueprint.collection)
for blueprint_name in blueprint.nested_blueprints:
sub_blueprint = blueprints_data.blueprints_per_name.get(blueprint_name, None)
if sub_blueprint is not None:
sub_blueprint_exported_path = None
if sub_blueprint.local:
sub_blueprint_exported_path = os.path.join(blueprints_path, f"{sub_blueprint.name}{export_gltf_extension}")
else:
# get the injected path of the external blueprints
sub_blueprint_exported_path = sub_blueprint.collection['export_path'] if 'export_path' in sub_blueprint.collection else None
if sub_blueprint_exported_path is not None and not does_asset_exist(assets_list, sub_blueprint_exported_path):
assets_list.append({"name": sub_blueprint.name, "path": sub_blueprint_exported_path, "type": "MODEL", "generated": True, "internal": sub_blueprint.local, "parent": None})
assets_list += get_blueprint_assets_tree(sub_blueprint, blueprints_data, parent=sub_blueprint.name, settings=settings)
return assets_list

View File

@ -0,0 +1,28 @@
def write_ron_assets_file(name, assets_hierarchy, internal_only=False, output_path_full="."):
# just for testing, this uses the format of bevy_asset_loader's asset files
'''
({
"world":File (path: "models/StartLevel.glb"),
"level1":File (path: "models/Level1.glb"),
"level2":File (path: "models/Level2.glb"),
"models": Folder (
path: "models/library",
),
"materials": Folder (
path: "materials",
),
})
'''
formated_assets = []
for asset in assets_hierarchy:
if asset["internal"] or not internal_only:
formated_asset = f'\n "{asset["name"]}": File ( path: "{asset["path"]}" ),'
formated_assets.append(formated_asset)
with open(f"{output_path_full}/{name}.assets.ron", "w") as assets_file:
assets_file.write("({")
assets_file.writelines(formated_assets)
assets_file.write("\n})")

View File

@ -7,6 +7,7 @@ from bpy.props import (BoolProperty, StringProperty, EnumProperty)
from .asset_helpers import does_asset_exist, get_user_assets, remove_asset, upsert_asset from .asset_helpers import does_asset_exist, get_user_assets, remove_asset, upsert_asset
from .assets_scan import get_main_scene_assets_tree from .assets_scan import get_main_scene_assets_tree
from ..core.path_helpers import absolute_path_from_blend_file from ..core.path_helpers import absolute_path_from_blend_file
from .generate_asset_file import write_ron_assets_file
class BLENVY_OT_assets_add(Operator): class BLENVY_OT_assets_add(Operator):
"""Add asset""" """Add asset"""
@ -172,32 +173,6 @@ class BLENVY_OT_assets_browse(Operator, ImportHelper):
from types import SimpleNamespace from types import SimpleNamespace
def write_ron_assets_file(level_name, assets_hierarchy, internal_only=False, levels_path_full="."):
# just for testing, this uses the format of bevy_asset_loader's asset files
'''
({
"world":File (path: "models/StartLevel.glb"),
"level1":File (path: "models/Level1.glb"),
"level2":File (path: "models/Level2.glb"),
"models": Folder (
path: "models/library",
),
"materials": Folder (
path: "materials",
),
})
'''
formated_assets = []
for asset in assets_hierarchy:
if asset["internal"] or not internal_only:
bla = f'\n "{asset["name"]}": File ( path: "{asset["path"]}" ),'
formated_assets.append(bla)
with open(f"{levels_path_full}/{level_name}.assets.ron", "w") as assets_file:
assets_file.write("({")
assets_file.writelines(formated_assets)
assets_file.write("\n})")
class BLENVY_OT_assets_generate_files(Operator): class BLENVY_OT_assets_generate_files(Operator):
"""Test assets""" """Test assets"""
bl_idname = "blenvy.assets_generate_files" bl_idname = "blenvy.assets_generate_files"
@ -213,7 +188,7 @@ class BLENVY_OT_assets_generate_files(Operator):
for scene in blenvy.main_scenes: for scene in blenvy.main_scenes:
assets_hierarchy = get_main_scene_assets_tree(scene, blueprints_data, settings) assets_hierarchy = get_main_scene_assets_tree(scene, blueprints_data, settings)
scene["assets"] = json.dumps(assets_hierarchy) # scene["assets"] = json.dumps(assets_hierarchy)
write_ron_assets_file(scene.name, assets_hierarchy, internal_only = False, levels_path_full = blenvy.levels_path_full) write_ron_assets_file(scene.name, assets_hierarchy, internal_only = False, output_path_full = blenvy.levels_path_full)
return {'FINISHED'} return {'FINISHED'}