Weird Problem Loading In Mobile Mesh's

Discuss any questions about BEPUphysics or problems encountered.
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

Im sorry to take up more of your time... but this is a very strange problem...

ive tried this multiple ways to confirm where the proiblem is coming from.

I try to load in a model as a mobile mesh and texture it using an effect. all that works.

For Example Trying this with Just a Cube....

1) if i Model the cube and do not move it in XSI Mod tool, Texture and export it... the Cube Textuing and The BEPUPhysicsDrawer Draws them Overlapping, which they should. Showing you where the physics stop and end and the textureing for the object.

If i Start a XSI Mod tool scean from scratch and create a Cube, and Move it in the Y direction UP, Texture and Export the Cube.

The BEPUPhysicsDrawer Draws the Physics in the Original Location that XSI Spawned the Cube, BEFORE i moved the cube.
Thus the Physics and The Drawing of the Mesh Does Not line up.

If I move the UV in XSI Mod tool, to an alternate location, I can See in my application, where my mesh draws. that this moves with it. However they physics Entity stays put.

So I Created 4 New Models and Named them TestSphere 1 - 4 , I Ensured that there were no offsets and that the= vertecices and indices being loaded in are the ones for the physics, and i have not changed them in any way,

Here Is The List of The 4 Models i made, The Diffrence's in how i made them, and how they react.

spawn
Texture - TestSphere1
Export
----- Works Properly




Spawn
Move - TestSphere2
Export
---- Does Not Work Because Not Textured


Spawn
Texture -TestSphere3
Move
Export
-------Textured Part is in the Correct Position but again the BEPUPhysics Drawer is drawing the object's Physics in the spawned postion

Spawn
Move
Texture TestSphere4
export
Same as TestSphere3 However the Textured Area seems to be only "Half as Far this is just perception i belive but still the Texture and the physics do not overlap


Now here is the World Transform For the Mesh


thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index];

So there is no CreateTranslation...




You would think while moving an object in the Modeling program your changing its vertaices, which is what should be Taken in from BEPU's helper methods, which are the values for the physcs....

So why does moving an object while modeling? not change the position of the physics? You could see how not being able to move objects while modelling would be very difficult to accomplish anything...

Any input is always much appreciated
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

You would think while moving an object in the Modeling program your changing its vertaices, which is what should be Taken in from BEPU's helper methods, which are the values for the physcs....

So why does moving an object while modeling? not change the position of the physics? You could see how not being able to move objects while modelling would be very difficult to accomplish anything...
All shapes center themselves on their local origins. The center of mass is computed and all shape data is offset so that the center of mass lines up perfectly with the local origin.

That way, when the shape is rotated, it's around the center of mass. If the shape weren't recentered, you would have to define the origin of rotation manually- this can be difficult for complicated shapes. Usually it results in the shape 'swinging' around in very unintuitive ways.

To compensate for the recentering, you need to apply a local offset to the graphic so that it lines up in local space prior to transforming it by the entity's world transform. For complex shapes like ConvexHullShapes or MobileMeshShapes, the position (and other information in the mesh case) is output directly for you to use (the ConvexHull/MobileMesh prefab entities use this information to position themselves such that the world space location of the shape is aligned with the original data).

More information can be found in these threads:
viewtopic.php?f=4&t=1511
viewtopic.php?f=4&t=1516
viewtopic.php?f=4&t=1513

If you DO want to force the shape to rotate around an off-center location, use the Entity.CollisionInformation.LocalPosition. Instead of applying the offset to the graphic, apply it to the shape. Again, the origin of the model in the model editor is almost certainly not the true physical center of mass, so only do this if you really want to override the center of mass. Here's a thread with a bit more information about that approach.
viewtopic.php?f=4&t=1494
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

Since this issue is so common (particularly recently), I've created a codeplex documentation page: http://bepuphysics.codeplex.com/wikipag ... ecentering
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

Ok, so after reading alot, Thank You!, Im stuck on how to exactly figure out the offset for each object...

The LocalPosition, seems to be the same as the Position for my mobile mesh.

I understand how to apply the offset but not to sure how to get the variables i need for the offset matrix or where they are...


Edit:

I think i got it due to this post :D viewtopic.php?f=4&t=1511

Thank you norbo !
Last edited by theneonirvana on Mon Jan 09, 2012 6:52 am, edited 1 time in total.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

Im stuck on how to exactly figure out the offset for each object...
The MobileMeshShape constructor can directly output the computed center (contained within the shape information out parameter). The offset is the negative position computed by that constructor.

Because the MobileMesh entity uses that constructor to set the initial Position property value, you can also just examine the MobileMesh entity's initial Position value and then negate it for use as the offset to apply to the graphic.
The LocalPosition, seems to be the same as the Position for my mobile mesh.
The LocalPosition is the offset applied to the collision shape in its local space. It should be Vector3.Zero unless you intend to make the origin of rotation something different from the physically computed center of mass.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

On an unrelated note, I should also emphasize that using a mobile mesh usually isn't ideal for performance and robustness. Generally using a convex hull, other simple primitives, or a compound body containing multiple simple hulls and primitives produces better, faster results.
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

Hi there

First on the note of the performance increase, thanks for the input im aware, however i want to just get things set right before i start messing with things... im in a very large project...

Ive gotten Very close to hgaving multiple objects alighned, Some Objects will align some wont.

Once again trying multiple senarios - Note again ive dried the un Negate of this.shapedist.Center and conveshull.Position aswell

Code: Select all

       
var convexhull = new BEPUphysics.Entities.Prefabs.ConvexHull(this.staticMeshVertices, 1);
Vector3 difference = new Vector3(0f, 0f, 0f) - convexhull.Position;

//// THIS WORLD TRANSFORM PERFORMS THE BEST, HOWEVER SOME OBJECTS SEEM TO BE OFF BY 1 Y UNIT 
//thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(((BEPUphysics.Entities.Prefabs.MobileMesh)this.staticMeshvar).Position + difference);

//thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] *Matrix.CreateTranslation(-((BEPUphysics.Entities.Prefabs.MobileMesh)this.staticMeshvar).Position);

//thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(-this.shapedist.Center);

//thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(-convexhull.Position);

/// Shapedist Init 
  shapedist = new BEPUphysics.CollisionShapes.ShapeDistributionInformation();
            var staticsomthing = new BEPUphysics.CollisionShapes.MobileMeshShape(this.staticMeshVertices, this.staticMeshIndices, new AffineTransform(new Vector3(1f, 1f, 1f)), BEPUphysics.CollisionShapes.MobileMeshSolidity.Solid, out shapedist);


/// AND CONVES HULL     0 Note  the NewVector3 is used incase i want to add the y offset 

var convexhull = new BEPUphysics.Entities.Prefabs.ConvexHull(this.staticMeshVertices, 1);
Vector3 difference = new Vector3(0f, 0f, 0f) - convexhull.Position;
     
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

I've created a little demo in the BEPUphysicsDemos showing an application of the process. You can grab the latest version in the development fork.

Here's the body of the demo:

Code: Select all

            //When creating a collision shape based on a model, the graphic will generally be offset at first.
            //This is because the collision shape computes the center of mass and offsets itself to align with the local origin.
            //That offset must be applied to the graphic to make it match the collision shape.

            //Check out the documentation page for more information: 
            //http://bepuphysics.codeplex.com/wikipage?title=Shape%20Recentering

            var model = game.Content.Load<Model>("guy");
            Vector3[] vertices;
            int[] indices;
            TriangleMesh.GetVerticesAndIndicesFromModel(model, out vertices, out indices);

            //Create an entity based on the model.
            ConvexHull hull = new ConvexHull(vertices, 10);
            Space.Add(hull);
            //Create a graphic for the hull.  The BEPUphysicsDrawer will also automatically receive a visualization of the convex hull.
            //The graphic will be offset from the collision shape because we have not attempted to offset it to match the collision shape's origin.
            var graphic = new DisplayEntityModel(hull, model, game.ModelDrawer);
            game.ModelDrawer.Add(graphic);


            //Now let's create another entity from the same vertices.
            hull = new ConvexHull(vertices, 10);
            Space.Add(hull);

            //Note that the prefab entity type ConvexHull uses the ConvexHullShape constructor internally, which outputs the computed center of the shape
            //prior to offset.  The ConvexHull constructor sets the entity's Position to that position so that the initial world space location of the vertices
            //matches what was passed into the constructor.
            //The same process could be performed using this code:

            //Vector3 computedCenter;
            //var shape = new ConvexHullShape(vertices, out computedCenter); //<-- It spits out the computed center here; this is what is used to offset the graphic!
            //var entity = new Entity(shape, 10);
            //entity.Position = computedCenter;
            //Space.Add(entity);

            //For more information about constructing entities, check out the EntityConstructionDemo.
            
            //But for now, let's just use the prefab entity type.  As mentioned earlier, the constructor set the entity's Position using the computed center.
            //Since we didn't overwrite it with some other position yet, we can still use it.
            graphic = new DisplayEntityModel(hull, model, game.ModelDrawer);
            graphic.LocalTransform = Matrix.CreateTranslation(-hull.Position);
            game.ModelDrawer.Add(graphic);

            //This graphic is perfectly aligned with the collision shape!  Hooray!


            Box ground = new Box(new Vector3(0, -1.5f, 0), 50, 1, 50);
            Space.Add(ground);
            game.Camera.Position = new Vector3(0, 6, 15);
You may want to fiddle around with this demo a bit to get comfortable with it in isolation. Perhaps try modifying to use a MobileMesh once you feel you have the hang of it. In addition, you can check out how the DisplayEntityModel uses the local transform.
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

I cant get multiple models to align properly... and i do belive it has somthing to do with my modeling still...

Please Check Solution2 As it gives the best results, however its very weird to see Solution4 with the TestSphere1 Align Properly...

Now Solution2 is almost acceptable if i could get the Y within a variance that isnt to high...

Once again, there must be some step in modeling that is disrupting this.

Seems if i could Model Everything in Once Place without moving anything, i could skip over the problem....

You Migth wana copy this into Notpad++ or somthing to make it a little easier to read its kinda long, trying to provide best detail i could

Code: Select all

  //    CREATING A CONVEX HULL and using its position;    Solution1
            //   TestSphere1 Model Test
            //   Result:   Model is not Set Correctly and Seems to be off to the right and up a little bit
            //----------------------------------------------
            //   Shelf Model Test
            //   up and off to the right   + in the Z   still off center  ----  while negated 
            //   up and off to the left --- while  positave
            //----------------------------------------------
            // House Model Test
            // Result:  Still Off
            var convexhull = new BEPUphysics.Entities.Prefabs.ConvexHull(this.staticMeshVertices, 1);
            //thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(convexhull.Position);


            ///  BEST RESULTS    Solution2
            //  Caluclating the Diffrent of the Convex Hull and Using it in Conjuction with the staticmesh position
            // TestSphere1 Model Test
            // Result:   The Objects Physics are 1F  TO High
            //-----------------------------------------------
            // Shelf Model Test
            // Result:   Aligned Correctly on X and Z The Textured Graphic is a little bit to Low on the Y Axis....
            //   Result2:  Aligned correctly on X and Z But the Physics but the Physics for the objects are to high.
            //------------------------------------------------------------------
            /// House Model Test
            /// Result:  Allighed Correctly on X and Z,   The Textured Graphic is a little bit to High on the Y Axis....
            /// Result2:   With The Difference Vector set to a -1Y in the calculation, the Models are aligned perfectly;
            Vector3 difference = new Vector3(0f, -1f, 0f) - convexhull.Position;
            //thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(((BEPUphysics.Entities.Prefabs.MobileMesh)this.staticMeshvar).Position + difference);




////  Solution3
            //  Creating a ConvexHullShape and Outputting the center to use...  
            // TestSphere1 Model Test
            // Results:     Same result as    Test Number 1 convexhull.Position 
            //-------------------------------------
            //   Shelf Model Test
            // Results:   While Negated -- object is off and to the right again    while negated
            //            While Posative  -- object is off to the left againe
            //-------------------------------------------------------------------
            // House Model Test
            // close but no cigar   off in the Z 
            // SameResults (obviously with Negated or Posative Center)
            Vector3 computedCenter;
            var shape = new BEPUphysics.CollisionShapes.ConvexShapes.ConvexHullShape(this.staticMeshVertices, out computedCenter);
            //thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(computedCenter);
            


/// Solution4
            /// Using just the Mobile Meshes Position
            // TestSphere1 Model Test
            // Result:   The Models are Aligned Properly..... 
            //-----------------------------
            // Shelf Model Test
            // Result: Only a little bit off, mostly in the Y little bit in the Z direction    in the posative
            //--------------------------------------------------------------------
            //  House Model Test
            //  Result:   MobileMesh Position Way off
            // thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] *Matrix.CreateTranslation(((BEPUphysics.Entities.Prefabs.MobileMesh)this.staticMeshvar).Position);


            
            /// Solution5
            /// Creating Shape Distribution Information and Using the Center Negated.
            /* THIS HAPPENS IN THE UPDATE    JUST SHOWING HERE FOR REFERENCE 
            shapedist = new BEPUphysics.CollisionShapes.ShapeDistributionInformation();
            var staticsomthing = new BEPUphysics.CollisionShapes.MobileMeshShape(this.staticMeshVertices, this.staticMeshIndices, new AffineTransform(new Vector3(1f, 1f, 1f)), BEPUphysics.CollisionShapes.MobileMeshSolidity.Solid, out shapedist);*/
            //   TestSphere1 Model Test
            //   Result:    The Models Physics are wrong and Up and to the Right 
            //--------------------------------------------------
            //    Shelf Model Test
            //  Result: Physics are way off to the up and right
            //----------------------------------------------------------
            ////  House Model Test
            ///  Result :way off and down 
            //thisWorld = ((Matrix[])staticworld)[this.playgroundModelModel.Meshes[0].ParentBone.Index] * Matrix.CreateTranslation(-this.shapedist.Center);
            
     

theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

It deffinitally has somthing to do with the modeling...

ive created many randmon models, an astrix, a shelf, a desk, a pyramid,

It seems about 75% match up properly and the remainding models are off by a 1 unit or so, some in x, some z, and some y...


now i have noticed weird things as well, for my house models if i create the 4 walls and then the roof using a cone, it will be offset but if i just create 4 walls... its fine...

if i create just the cone its fine,,, at any size,

if i make a cone and then a cube, that is not hollow just to resemble a block house its fine...

there is nothing that i can see in the modeling that is messing with this...

Moving, or chaning the UV does not affect this.... moving or changing the object dosnt matter, so it seems ive figure that part out, however,

Im not to sure where to take this... i may have to deal with the 1 unit offset,

could it be due to maybe walls or Cubes in my models being to thin? ive tried numeris models with diffrent sized things, once again some work some dont i couldnt tell u a good percentage tho..



EDIT so just to confirm, ive done this a ton of times now, i create 4 walls, merge into 1 mesh,texture it, and export, and it works fine...

going from the poly mesh i just made, create a cube, make it flat, make it a flat roof and position it above all 4 walls, Merge all the walls and the top into 1 mesh, texture it, export, and its off by a float.

Same result over and over again if i make from scrate or dont duplicate or anything...

PLEASE READ
EDIT AGAIN!!!!! --- ok, so instead of putting a roof on the 4 walls i thought of putting a floor, and i get the exact opposite response...

So if i add a Roof, the BEPU physics are to low, and u can see the physics model being Extruded....
In this Photo:
http://imageshack.us/photo/my-images/811/bottem.jpg/

If i Put a Floot instead of a roof, the BEPUphysics are to high.... and the physics extruded from the top of the model as show in this picture...
http://imageshack.us/photo/my-images/84/topfil.jpg/


This leaves me BAFFLED....

Norbo can u please shed some light? i have given u a ton to read i know but could u help that light above my head turn on? :)
Please

LAST EDIT

Tried a Dohnut, with a block above it, merged and textured, same thing, here are photos of what i made in XSI and photos of how it renders in my application
http://imageshack.us/photo/my-images/171/62837403.jpg/
http://imageshack.us/photo/my-images/213/xsip.jpg/
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

Sorry, there's a bit too much information for to parse down, but it seems like there are two issues in play here.

1) The mesh windings don't seem to be consistent, so sometimes you can see the interior of of objects instead of their exterior.

2)
EDIT so just to confirm, ive done this a ton of times now, i create 4 walls, merge into 1 mesh,texture it, and export, and it works fine...

going from the poly mesh i just made, create a cube, make it flat, make it a flat roof and position it above all 4 walls, Merge all the walls and the top into 1 mesh, texture it, export, and its off by a float.

Same result over and over again if i make from scrate or dont duplicate or anything...
This sounds a lot like what I was referring to earlier with recentering. Four walls of a box is symmetrical so if the origin happened to be in the center of the box in the modelling program, it would just happen to work properly. It will fail as soon as a 'roof' is added because the model origin is no longer coincidentally aligned with the center of mass. This can be fixed by offsetting the graphic to match.

It's important to note that if any models don't align correctly, then the offset implementation isn't correct. A correct offset implementation will fix the problem across the board.

It appears that a lot of the attempts include fairly random variations, like negations and arbitrary offsets- I would recommend dropping all of those and focusing on a single case where you know it's not behaving correctly yet. Rigorously work through it step by step, visualizing each transformation being created and applied. Avoid succumbing to the temptation to try out four different ways of doing it without having a very strong theory as to why that method would work in all cases :)

A good starting point would be trying to modify the GraphicMatchingDemo included in the development fork BEPUphysicsDemos. Try loading in a single one of your models and modifying the code to make the graphic match the BEPUphysicsDrawer visualization (which matches the collision shape).
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

just an update...
ive looking into the new example norbo.. now if i set the local transform to this... i can get a couple models to align properly.

graphic.LocalTransform = Matrix.CreateTranslation(hull.Position - computedCenter * 2f);

after changing to a convexhull and adding the hull to the physics, i get much better results, but regardless of the coding, i cant get all models to line up with the same code...

i know a properly implemented solution should fix everything, however im still not sure as to why say,, your fish model works without multiplying the computedCenter,

but all my models are off a bit and need the final adjustment,

i think if i can figure that out, my code would work as a blanket on all things.
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: Weird Problem Loading In Mobile Mesh's

Post by Norbo »

graphic.LocalTransform = Matrix.CreateTranslation(hull.Position - computedCenter * 2f);
Something is off here. Generally, you only have an external computedCenter if you are creating a ConvexHullShape directly and passing that to an entity (or entities) later. Creating a ConvexHull prefab entity type creates a ConvexHullShape internally, which it then uses to define ConvexHull's Position property.

It sounds like you're creating both a ConvexHullShape externally followed by a ConvexHull from the same point set. In that case, hull.Position is the same value as the computedCenter you get from the shape constructor. So that hull.Position - computedCenter * 2 is the same value as -computedCenter or -hull.Position alone. To save time and complexity, only use one of them and get rid of the other redundant method.

I can tell you the most correct implementation will not include arbitrary multipliers or offsets, so if you start seeing them, something is going wrong :)
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

Well im quite lost Norbo,

Im not sure if i explained my self well enough.

Using an Unmodified version of BEPU physics and the GraphicMatchingDemo, Loading in only one of my models, the shapes do not align, Reverting back to any one of your models, with the unmodified code. Everything works perfectly.

Therefor the only variable in my issue seems to be my models.

What lead me to changing the BEPU physics Transform and adding the multiply was,.
Try loading in a single one of your models and modifying the code to make the graphic match the BEPUphysicsDrawer visualization (which matches the collision shape).


It sounds like you're creating both a ConvexHullShape externally followed by a ConvexHull from the same point set. In that case, hull.Position is the same value as the computedCenter you get from the shape constructor. So that hull.Position - computedCenter * 2 is the same value as -computedCenter or -hull.Position alone.
Once again, you are absolutly correct. I Do create Both a ConvexhullShape and a ConvexHull The Values do match however.

However Upon removing my ConvexHullShape and changing the Translation to -Convexhull.Position. The Models Get Close... However, i still have misalignment by about 1 on any given axis. Exactly the issue i had before...

Now..
This sounds a lot like what I was referring to earlier with recentering. Four walls of a box is symmetrical so if the origin happened to be in the center of the box in the modelling program, it would just happen to work properly. It will fail as soon as a 'roof' is added because the model origin is no longer coincidentally aligned with the center of mass. This can be fixed by offsetting the graphic to match.
Is exactly what is happening, you are right, and i do understand...

However what i do not understand is, if a proper solution will not use arbitary multiplyers or offsets. That means then Multiplying Vectors togather or with other constant values is out.

and im not quite sure if i should start multplying matrix's or wat....

im gunna do alot more digging

I understand not giving an answer and i appreciate you making me work for it i do :P

I will continue to work on the problem till i find out how to offset the graphic perfectly.
However... i can see this problem happening alot and i dont expect you or any one else, to have a XNA project full of symetrical Models...
Last edited by theneonirvana on Sat Jan 14, 2012 1:41 am, edited 1 time in total.
theneonirvana
Posts: 24
Joined: Wed Aug 17, 2011 9:20 pm

Re: Weird Problem Loading In Mobile Mesh's

Post by theneonirvana »

PS.

Regardless, Thank you a Billion for always lending a Ear


Its more appreciated then text can display :)
Post Reply