Page 6 of 7

Re: Blender 2.5 Exporter [Official]

Posted: Thu Jun 14, 2012 4:52 pm
by BluGeminii
Thanks jonim8or, I will give it a try!

Re: Blender 2.5 Exporter [Official]

Posted: Tue Jun 19, 2012 2:21 am
by ArtOfWarfare
I'm a noob with both Blender and Ogre, so I'm not quite sure where to say this at, but there appears to be a wrapping or normal issue... or maybe I should just describe the symptom and let someone else figure out what's actually wrong:

I made a fairly simple model in Blender. It's made up of 38 vertices and 52 faces. It looks fine in Blender. When I export it to Ogre and try viewing it in my game, roughly half the surfaces are visible. Random faces are hidden. If you move the camera into the middle of the model, some (all?) of the faces that were missing will appear.

Edit: I was able to make my entire model appear by changing the material script to have "cull_hardware none" in stead of "cull_hardware clockwise". My understanding is this will cause a decrease in performance (by a factor of two for each time the material needs to be drawn? I don't know for sure...) but... given I'm still just learning my way around, I think this will do for now...

Re: Blender 2.5 Exporter [Official]

Posted: Tue Jun 19, 2012 9:06 am
by jonim8or
it could be that the problem is in your model, not in the exporter. In blender, select your model, and under the mesh properties, unselect the "double sided" option. Now you should see more clearly which side the faces are facing.
If the mesh shows the same holes as in Ogre, the problem is that the normals were not correct in blender (but you could not see that due to the double sided feature, which is the same as the cull_hardware none option in Ogre)
Then, to fix it, go to edit mode and play with the "flip normals" and "recalculate normals" options.

If this does not fix the problem, can you post your blend file?

Re: Blender 2.5 Exporter [Official]

Posted: Tue Jun 19, 2012 8:18 pm
by duststorm
Press N to show the properties panel and under the heading Draw: select Normals: face
The blue lines you see are the normals, and they should all point outwards. If this is not the case (and recalculating the normals outside did not work), select the face with the wrong normal, and choose Flip.

Re: Blender 2.5 Exporter [Official]

Posted: Wed Jun 20, 2012 11:08 am
by jonim8or
I added another feature, which is quite important in my work (but might not be in yours): directory tree settings.

For my project, I want to have a blender file tree (.blend files, .xcf files) which is under version control, and I want to export the meshes to a different, but similarily structured directory tree. It is now possible to specify two root-directories in the global settings. If the blend file is inside the blender-files root directory, it will create a similar path in the ogre tree.
If the blend file is not inside the blender-files root directory you get a warning and cannot export
The different options in the configuration panel
The different options in the configuration panel
ExporterSettings.jpg (47.09 KiB) Viewed 14138 times

Re: Blender 2.5 Exporter [Official]

Posted: Sat Jun 23, 2012 5:39 am
by nikki
Made a quick hack to get it to work with UV textures (the old 'TEXFACE' stuff) since I use this in my game for specifying materials per-face easily. In my game I've manually written materials that correspond to the texture names for finer control, so I just made it work for what I need, this is not an ideal solution at all but might point to a way to get UV textures to work (it also only works with one UV texture really). This is the change I made (line 248 in

Code: Select all

        for face in blendMesh.tessfaces:
            # get or create submesh.
            uvImage = None

            for uvTex in blendMesh.uv_textures:
                if[face.index].image.source == 'FILE':
                    uvImage =[face.index].image

            if uvImage:
                    if uvImage in self.mSubMeshDict:
                        subMesh = self.mSubMeshDict[uvImage]
                        subMesh = SubMesh(self.mSharedVertexBuffer, self.mSharedMeshVertexIndexLink)
                        subMesh.mMaterial = uvImage # works for now, only needed
                        self.mSubMeshDict[uvImage] = subMesh
            elif (face.material_index in self.mSubMeshDict):
                subMesh = self.mSubMeshDict[face.material_index]
                subMesh = SubMesh(self.mSharedVertexBuffer, self.mSharedMeshVertexIndexLink)
                subMesh.mMaterial = None if (len(materialList) == 0) else materialList[face.material_index]
                self.mSubMeshDict[face.material_index] = subMesh

            # insert face.
            subMesh.insertFace(blendMesh, face)
I would submit a .diff but I had to convert all the tabs to spaces to get indentation to work with the lines I added so the .diff was big. Thanks for the work on this!

Re: Blender 2.5 Exporter [Official]

Posted: Sat Jun 23, 2012 6:40 am
by nikki
So I'm thinking about how to handle vertex normals. If you take the default cube in blender2.4 and export it with the old exporter, you have multiple vertices at each corner to handle the normals, and each normal is axis-aligned. However, if you save this cube and load it up in blender2.6 and use this exporter, you get smoothed-out normals. This causes the cube to be differently shaded in-game. How do you guys think this should be handled? Are the default blender vertex normals the way to go, or should the exporter calculate normals if the face is not smooth (possibly leading to multiple vertices for a single blender vertex)? Here's a snippet from the old exporter:

Code: Select all

		## normal
		if bMFace.smooth:
			# key blocks don't have normals
			self.normal = self._applyfixUpAxis(bMFace.v[bIndex].no)
			# create face normal
			# 1 - 2
			# | /
			# 3
			# n = (v_3 - v_1) x (v_2 - v_1)/||n||
			if (bKey and len(bKey.blocks)):
				# first shape key is rest position
				blockData = bKey.blocks[0].data
				v1 = self._applyfixUpAxis(blockData[bMFace.v[0].index])
				v2 = self._applyfixUpAxis(blockData[bMFace.v[1].index])
				v3 = self._applyfixUpAxis(blockData[bMFace.v[2].index])
				# self.normal = CrossVecs(bMFace.v[1].co - bMFace.v[0].co, bMFace.v[2].co - bMFace.v[0].co)
				v1 = self._applyfixUpAxis(bMFace.v[0].co)
				v2 = self._applyfixUpAxis(bMFace.v[1].co)
				v3 = self._applyfixUpAxis(bMFace.v[2].co)
			self.normal = CrossVecs(v2 - v1, v3 - v1)
This is from the constructor of an internal vertex representation class. As you can see, it calculates the vertex normal if the associated face is not smooth.

EDIT: Anyway - I fixed the exporter to use the face normal for each vertex in a face if it's not smooth. I've attached a patch. This patch also contains the TEXFACE change I described above.

Re: Blender 2.5 Exporter [Official]

Posted: Sat Jun 23, 2012 8:15 am
by nikki
Sorry for all the double posting - made a few changes to this exporter since I needed some stuff for my project. Here's another patch, this time having the OgreXMLConverter command also handle options and extra arguments. Sorry about the whitespace stuff in the diff - my editor put those in...

Re: Blender 2.5 Exporter [Official]

Posted: Mon Jun 25, 2012 8:44 am
by jonim8or
About the vertex normals: I always have my mesh smooth-shaded. Then I use an edgesplit modifier, and depending on the mesh I use an edge angle, or I manually specify which edges should have a sharp crease. This modifier is automatically applied by the exporter, so this approach works seamlessly with the exporter.

In blender I give the materials the same names that I also want to use in the ogre material files. When modeling and texturing, I use GLSL shading mode (which uses the material settings in the 3d viewport, not the texture). This also gives me the possibility to use mult-texture materials, and even to paint multi-texture materials. However I haven't done any models yet with multiple uv sets.

Re: Blender 2.5 Exporter [Official]

Posted: Mon Jun 25, 2012 1:12 pm
by bstone
That's similar to what I did. Keeping consistent names helps big way when creating .material scripts and shaders for Ogre. I used Cg but GLSL should be the same. Blender is awesome for modeling, UV unwrapping, baking/painting textures. Creating .material scripts and shaders is the little what is left after that and it can be made even with notepad.

Re: Blender 2.5 Exporter [Official]

Posted: Wed Jun 27, 2012 8:18 am
by jonim8or
Just found a problem with the exporter (or rather, with blender when the exporter is enabled). Animating objects won't work that nice any more. Steps to reproduce the problem:
1) start new blender file, with the exporter enabled
2) select the default cube, and insert a locrot keyframe
3) select a different point on the timeline
4) rotate the cube. You will see it jumping between the keyframed rotation and the new rotation.

It is probably caused by these lines in

Code: Select all

		# NOTE1: we need to remove the callback first before setting the frame.
		# this is because calling frame_set() refreshes the whole scene again which will end up
		# randomly(?) calling this callback function again if we don't stop listening first.
		# NOTE2: we call frame_set() for a stupid hackish reason to refresh the UI to reflect the selection change.
		panel = bpy.types.ogre3d_exporter_panel
		# flag selection refresh state to 2.
		# this is because the poll() event will be triggered again due to scene refresh.
		# this way, the poll event will correctly ignore registering callback for refreshing of selection.
		panel.mSelectionRefreshState = 2
I don't have time to look into this, but if someone has an idea, please help

Re: Blender 2.5 Exporter [Official]

Posted: Wed Sep 26, 2012 2:49 pm
by kromar
this addon causes a core to get stuck at 100% usage. to reproduce just enable the addon, split the window so you have 2 x 3d views and save that as default. then restart blender and one core will get stuck at 100%.

Re: Blender 2.5 Exporter [Official]

Posted: Thu Sep 27, 2012 8:41 am
by jonim8or
You are right. It seems to behave like that if you have multiple 3d windows. If you only have one 3d view, it works fine, as soon as you open another one, it starts consuming a core.
Not sure what is causing it, maybe the update of one panel is triggering an update of the other panel.

Re: Blender 2.5 Exporter [Official]

Posted: Thu Sep 27, 2012 6:41 pm
by nazggul

Was investigated bug reported by Kromar from Blender side. Unfortunately, there's not much we can help from that side. But wanted to give some ideas about possible ways of fixing this.

First of all, i'm not sure why that tricks with adding/removing handlers are needed. Seems having single handler which would iterate through regions and tagging them for redraw would do exactly what all that tricks are supposed to do.

Code to iterate and tag areas for update would be:

Code: Select all

    for screen in
        for area in screen.areas:
            if area.type == 'VIEW_3D':
                for region in area.regions:
                    if region.type == 'TOOLS':
Further but not checked yet, probably bpy.context.screen would be correct in handler callback so you can use it instead of iterating through screens.

This should make MainExporterPanel.poll be unneeded -- what would needed to do be done is register scene_update_pre handler in addon's register function (and do not forget to unregister it from addon's undergister function :)

Some more tips:
- RNA collection actually has got clear() method, why not use it instead of using per-element removing in a while?
- You could probably check whether selection was changed or not avoiding unneeded refresh tags
- scene_update_post/pre handlers are accepting scene argument, not a context. This is currently harmless naming, but in the future could backfire

Hopefully this information would be enough to solve CPU usage issue :)

Feel free to drop to our IRC #blendercoders ar and kick me (nick sergey-) if there'll be difficulties (not sure i'll be able to keep a track on this thread often),

Re: Blender 2.5 Exporter [Official]

Posted: Tue Oct 16, 2012 12:22 am
by lf3thn4d
Hey guys,

I'm back from a long silence again. I've managed to find more time to fix up things and added a primitive log manager. :-)
Anyways, here's the change log:
  • - Fix mesh exporter to follow new Blender mesh API change.
    - Fix UV export to flip Y axis. (Blender's UV coord is bottom left, Ogre's top left)
    - Mesh exporter now observes mesh smoothing function (flat faces will generate new vertices as nessesary).
    - Simplify mesh override settings (Created a function to merge mesh settings with global settings)
    - Added initial log manager implementation (Shows export progress and logs).
    - Exporting now uses the MODAL operator.
    • - Each selected object is exported after each MODAL event triggers.
      - This allowed blender to refresh and show progress.
      - No more freeze when exporting tons of meshes.
      - However if mesh is huge and complex, it may still freeze for a bit.
I've fixed up the Y-flipped problem. Thanks for pointing it out and submitting a patch :-) I've yet to add your xml converter patch. That is next on my list. :-)
I'm not too sure about the directory tree thing though. It's not exactly a generic solution.
I'll take a look at the animation problem. You are right about those lines. It's a hack to make selection list auto update. I've never thought of the issue of multiple 3D view. It's probably hooking up the callback multiple time. Need checking. Either way, I've did some tiny optimization to the way I update the selection list. So the cpu usage isn't that high now. I still don't really like the current hack though. Will see what I can do.

Hmm.. remind me again how this was achieved with the old 2.49 exporter? Was it done using the Game Engine Material option? If not, i think we could add a new option to say "use TEXFACE as material name" or something like that.
As for the normals problem, I've fixed it. The problem was that the new exporter did not observe the face smoothing/flat setting. I was assuming that blender will give me the correct vertex normal. Apparently this isn't the case.
Still, the best way for any artist is to use the edgesplit modifier like what jonim8or says. It's actually a better way to do it and produces 100% expected result.

Thanks for the tip. I'll look into it. :-)

edit: I've fixed up the auto selection list update hack as suggested by nazggul. It should now use very little CPU. I'm not too happy that the callback is being done every render refresh though. I wish there's a new handler in blender that only calls when input happens (I.E. Mouse pressed/released). Ideally, if they have a selection changed handler, it'll be the best. Maybe this can be a feature request for them. :-)

Re: Blender 2.5 Exporter [Official]

Posted: Tue Oct 16, 2012 11:37 am
by jonim8or
Thanks for the update.
However, for me it didn't work. I had to add an index[0] to the users_scene, because it is a tuple. this small change in

Code: Select all

mesh = meshObject.to_mesh(meshObject.users_scene[0], True, 'PREVIEW')
After that it worked as a charm. Haven't tried with huge meshes yet, but I like the log feature.

btw I would suggest moving the code to a folder named ogre_mesh_exporter in the repo, because then installing it in blender is more straightforward.

Re: Blender 2.5 Exporter [Official]

Posted: Tue Oct 16, 2012 12:09 pm
by lf3thn4d
Hmm.. you are right. Ok. I'll move it to a sub folder + that apply modifier fix. Forgot to test that.

Edit: Ok. Fixed and done. I've also added XMLConverter support. :-D
Edit2: Updated support to XMLConverter:
- Made XMLConverter execution parellel. This makes batch converting faster.
- Hid XMLConverter output from console. (parallelization caused it to print garbage to the blender console since they are all printing at the same time)
- Added ESC key canceling of export.

Re: Blender 2.5 Exporter [Official]

Posted: Sun Oct 21, 2012 3:34 pm
by lf3thn4d
Hey guys, I've did more work on the exporter. We can now define submesh naming and change shared vertices setting(make submesh not share mesh vertex buffer).
This also means the basic mesh exporting front is complete! :-) The next move is to get into the animation exports (skeletal, pose, morph)

P.S. Whoever changed the wiki page without my consent, please message me before doing changes at your own whims. This exporter is still alive and progressing.

Re: Blender 2.5 Exporter [Official]

Posted: Sun Oct 21, 2012 3:39 pm
by Wolfmanfx
Nice work!
But your are still working in the wrong branch you should work in 1.8 and not in default branch - last time david transplanted your commits to 1.8 but this gonna suck in the long run when you still commiting in default.

Re: Blender 2.5 Exporter [Official]

Posted: Sun Oct 21, 2012 4:36 pm
by lf3thn4d
Oh crap. I'll fix that. thanks.

Edit: Fixed. All changes will now be commited to v1-8 branch.
Edit2: Main post now updated. I've started releasing official WIP builds for those who do not want the hassle of getting them from Ogre's source.

Re: Blender 2.5 Exporter [Official]

Posted: Thu Mar 06, 2014 9:50 am
by jonim8or
In my version (what we use in the company) of the exporter, I've added manual distance-LOD support. The only problem is that then you also need to know the relative path of the mesh file in the resources directory. In the setup we use at our company that's quite easy, but if you want to be able to select a specific output location that might be more difficult.
Can't really submit a patch here, because I've made other changes as well (we have a directory tree of blend files, and a directory of ogre files, and it exports the blend files to the corresponding ogre folder)

added to

Code: Select all

    lodLevel2Object = StringProperty(
        name = "LOD Level 2",
        description = "2nd level of detail object"
    lodLevel2Distance = FloatProperty(
        name = "LOD Level 2 Distance",
        description = "LOD distance for 2nd level of detail object",
        default = 100

    lodLevel3Object = StringProperty(
        name = "LOD Level 3",
        description = "3rd level of detail object"
    lodLevel3Distance = FloatProperty(
        name = "LOD Level 3 Distance",
        description = "LOD distance for 3rd level of detail object",
        default = 500

    def getLODs(self):
        lods = []
        if self.lodLevel2Object:
            lods.append((self.lodLevel2Object, self.lodLevel2Distance))
        if self.lodLevel3Object:
            lods.append((self.lodLevel3Object, self.lodLevel3Distance))
        return lods
added to

Code: Select all

        row = col.row(True)
        row.prop_search(meshSettings, "lodLevel2Object",  context.scene, "objects")
        row.prop(meshSettings, "lodLevel2Distance")

        row = col.row(True)
        row.prop_search(meshSettings, "lodLevel3Object",  context.scene, "objects")
        row.prop(meshSettings, "lodLevel3Distance")
modified in

Code: Select all

class Mesh():
    def __init__(self, blendMesh = None, exportSettings = MeshExportSettings(), lods=[]):
        # Lets do some pre checking to show warnings if needed.
        if (len(blendMesh.uv_layers) > 8): LogManager.logMessage("More than 8 UV layers in this mesh. Only 8 will be exported.", Message.LVL_WARNING)
        if (len(blendMesh.vertex_colors) > 2): LogManager.logMessage("More than 2 color layers in this mesh. Only 2 will be exported.", Message.LVL_WARNING)

        # shared vertex buffer.
        self.mSharedVertexBuffer = VertexBuffer()
        # Blender mesh -> shared vertex index link.
        self.mSharedMeshVertexIndexLink = dict()
        # collection of submeshes.
        self.mSubMeshDict = dict()

        # skip blend mesh conversion if no blend mesh passed in.
        if (blendMesh is None): return

        # setup shared vertex buffer.

        # split up the mesh into submeshes by materials.
        materialList = blendMesh.materials
        LogManager.logMessage("Material Count: %d" % len(materialList), Message.LVL_INFO)
        for polygon in blendMesh.polygons:
            # get or create submesh.
            if (polygon.material_index in self.mSubMeshDict):
                subMesh = self.mSubMeshDict[polygon.material_index]
                subMesh = SubMesh(self.mSharedVertexBuffer, self.mSharedMeshVertexIndexLink)
                subMesh.mMaterial = None if (len(materialList) == 0) else materialList[polygon.material_index]
                if (exportSettings.requireMaterials and subMesh.mMaterial == None):
                    LogManager.logMessage("Some faces are not assigned with a material!", Message.LVL_WARNING)
                    LogManager.logMessage("To hide this warning, please uncheck the 'Require Materials' option.", Message.LVL_WARNING)
                self.mSubMeshDict[polygon.material_index] = subMesh

            # insert polygon.
            subMesh.insertPolygon(blendMesh, polygon, exportSettings.fixUpAxisToY)

        self.lods = lods

    def serialize(self, file):

        # write shared vertex buffer if available.
        sharedVertexCount = self.mSharedVertexBuffer.vertexCount()
        if (sharedVertexCount > 0):
            file.write('\t<sharedgeometry vertexcount="%d">\n' % sharedVertexCount)
            self.mSharedVertexBuffer.serialize(file, '\t\t')

        # write submeshes.
        for subMesh in self.mSubMeshDict.values():

        if self.lods:
            file.write('\t<levelofdetail strategy="Distance" numlevels="{0}" manual="true">\n'.format(len(self.lods)))
            for meshname, distance in self.lods:
                file.write('\t\t<lodmanual value="{0}" meshname="{1}" />\n'.format(distance, meshname))
modified in

Code: Select all

def exportMesh(meshObject, filepath, context):
    result = (False, None)
        print('Filepath: {}'.format(filepath))
        LogManager.logMessage("Output: %s" % filepath, Message.LVL_INFO)

        # get combined mesh override & global settings.
        meshExportSettings = MeshExportSettings.fromRNA(meshObject)

        # If modifiers need to be applied, we will need to create a new mesh with flattened modifiers.
        LogManager.logMessage("Apply Modifier: %s" % meshExportSettings.applyModifiers, Message.LVL_INFO)
        if (meshExportSettings.applyModifiers):
            mesh = meshObject.to_mesh(context.scene, True, 'PREVIEW')
            cleanUpMesh = True
            mesh =
            cleanUpMesh = False

        globalSettings = context.scene.ogre_mesh_exporter
        lod_info = meshObject.ogre_mesh_exporter.getLODs()

        relpath = globalSettings.getLocalExportPath()
        lods = [(os.path.join(relpath, '{}.mesh'.format(name)), distance) for name, distance in lod_info]

        # prepare mesh.
        ogreMesh = Mesh(mesh, meshExportSettings, lods)

Re: Blender 2.5 Exporter [Official]

Posted: Thu Mar 27, 2014 8:38 pm
by Germanunkol
Hi everyone,

I tried to get the exporter working with Blender 2.70, and can't see anything on the 3d Side panel, besides the "Ogre mesh exporter" title and a "Selected:".

I got it to work with 2.63a, though...

Re: Blender 2.5 Exporter [Official]

Posted: Fri Apr 25, 2014 11:38 am
by jonim8or
Strange, my version works fine in 2.70a. Can you do a Window->Toggle System Console and tell what it says there?

I recently moved the settings that were being saved in a config file, into an AddonPreferences, because I got path problems when using the same file tree on different machines.
Only problem with my solution there is that when you disable the exporter, it forgets the preferences... :-(

Re: Blender 2.5 Exporter [Official]

Posted: Thu May 01, 2014 2:31 pm
by aterlamia
I hade teh same problen in 2.70 console gave me:

Code: Select all

location: <unknown location>:-1
Traceback (most recent call last):
  File "/home/melvin/.config/blender/2.70/scripts/addons/ogre_mesh_exporter/", line 149, in draw
    col.template_list(selectedObjectList, "collection", selectedObjectList, "collectionIndex")
TypeError: UILayout.template_list(): error with argument 1, "listtype_name" -  Function.listtype_name expected a string type, not SelectedObjectList

location: <unknown location>:-1
changing the folowing in file on line 149 worked for me

Code: Select all

col.template_list("UI_UL_list", "collection", selectedObjectList, "collection", selectedObjectList, "collectionIndex") 
accordingly to ... PI_Changes

I did not really take a look at the rest of the code and im not a pyton developer but it should give an idea what to change.

Re: Blender 2.5 Exporter [Official]

Posted: Thu May 01, 2014 7:07 pm
by Germanunkol
Hm, trying what aterlamia suggested gives me:

Code: Select all

Traceback (most recent call last):
  File "/usr/share/blender/2.70/scripts/modules/", line 299, in enable
    mod = __import__(module_name)
  File "/home/micha/.config/blender/2.70/scripts/addons/ogre_mesh_exporter/", line 47, in <module>
    from . import global_properties
ImportError: cannot import name 'global_properties'
I've never used python - so no clue where to start here.
This time I tried using blender 2.70a.
The error here only appears when I try to enable the exporter - I can install it just fine. Now I can't even see "Ogre Mesh Exporter:" and "Selected" on the side panel any more (I assume that's because the python script never runs correctly.

The API change does seem to be the problem here, though, because there's also tabs on the side that weren't there before...

Edit: A quit web search showed me that this might have to do with the fact that my blender and python aren't all that compatible. Using ArchLinux...