Saturday merger of bf-blender in orange branch.
authorTon Roosendaal <ton@blender.org>
Sat, 17 Dec 2005 20:25:41 +0000 (20:25 +0000)
committerTon Roosendaal <ton@blender.org>
Sat, 17 Dec 2005 20:25:41 +0000 (20:25 +0000)
184 files changed:
SConstruct
intern/bmfont/intern/BMF_BitmapFont.cpp
intern/boolop/intern/BOP_Face2Face.cpp
intern/boolop/intern/BOP_Interface.cpp
intern/boolop/intern/BOP_Mesh.cpp
intern/boolop/intern/BOP_Mesh.h
intern/bsp/intern/CSG_BooleanOps.cpp
intern/elbeem/SConscript
intern/elbeem/intern/blenderdummy.cpp
intern/elbeem/make/msvc_6_0/elbeem.dsp
intern/elbeem/make/msvc_7_0/elbeem.vcproj
intern/ghost/intern/GHOST_SystemCarbon.cpp
intern/opennl/extern/ONL_opennl.h
intern/opennl/intern/opennl.c
projectfiles/blender/imbuf/BL_imbuf.dsp
projectfiles_vc7/blender/blender.vcproj
projectfiles_vc7/blender/imbuf/BL_imbuf.vcproj
release/Makefile
release/scripts/3ds_export.py [deleted file]
release/scripts/3ds_import.py [deleted file]
release/scripts/ac3d_export.py
release/scripts/ac3d_import.py
release/scripts/bevel_center.py
release/scripts/blenderLipSynchro.py [deleted file]
release/scripts/bvh2arm.py
release/scripts/bvh_export.py
release/scripts/bvh_import.py
release/scripts/console.py
release/scripts/lightwave_import.py
release/scripts/md2_export.py [deleted file]
release/scripts/md2_import.py [deleted file]
release/scripts/mirror_bone_weights.py [deleted file]
release/scripts/uv_export.py
release/scripts/widgetwizard.py [deleted file]
release/scripts/xsi_export.py [deleted file]
source/blender/blenkernel/BKE_DerivedMesh.h
source/blender/blenkernel/BKE_anim.h
source/blender/blenkernel/BKE_bad_level_calls.h
source/blender/blenkernel/BKE_depsgraph.h
source/blender/blenkernel/BKE_displist.h
source/blender/blenkernel/BKE_effect.h
source/blender/blenkernel/BKE_font.h
source/blender/blenkernel/BKE_group.h
source/blender/blenkernel/BKE_material.h
source/blender/blenkernel/BKE_scene.h
source/blender/blenkernel/BKE_utildefines.h
source/blender/blenkernel/bad_level_call_stubs/stubs.c
source/blender/blenkernel/intern/DerivedMesh.c
source/blender/blenkernel/intern/action.c
source/blender/blenkernel/intern/anim.c
source/blender/blenkernel/intern/armature.c
source/blender/blenkernel/intern/depsgraph.c
source/blender/blenkernel/intern/displist.c
source/blender/blenkernel/intern/effect.c
source/blender/blenkernel/intern/font.c
source/blender/blenkernel/intern/group.c
source/blender/blenkernel/intern/library.c
source/blender/blenkernel/intern/material.c
source/blender/blenkernel/intern/mball.c
source/blender/blenkernel/intern/nla.c
source/blender/blenkernel/intern/object.c
source/blender/blenkernel/intern/scene.c
source/blender/blenkernel/intern/softbody.c
source/blender/blenlib/BLI_blenlib.h
source/blender/blenlib/intern/util.c
source/blender/blenloader/intern/readblenentry.c
source/blender/blenloader/intern/readfile.c
source/blender/blenloader/intern/writefile.c
source/blender/include/BDR_drawobject.h
source/blender/include/BDR_unwrapper.h
source/blender/include/BIF_editarmature.h
source/blender/include/BIF_editgroup.h
source/blender/include/BIF_meshtools.h
source/blender/include/BIF_outliner.h
source/blender/include/BIF_poseobject.h
source/blender/include/BIF_resources.h
source/blender/include/BIF_space.h
source/blender/include/BIF_toolbox.h
source/blender/include/BSE_drawview.h
source/blender/include/BSE_filesel.h
source/blender/include/blendef.h
source/blender/include/butspace.h
source/blender/include/transform.h
source/blender/makesdna/DNA_action_types.h
source/blender/makesdna/DNA_armature_types.h
source/blender/makesdna/DNA_effect_types.h
source/blender/makesdna/DNA_group_types.h
source/blender/makesdna/DNA_material_types.h
source/blender/makesdna/DNA_nla_types.h
source/blender/makesdna/DNA_object_types.h
source/blender/makesdna/DNA_scene_types.h
source/blender/makesdna/DNA_space_types.h
source/blender/makesdna/DNA_view3d_types.h
source/blender/makesdna/DNA_world_types.h
source/blender/python/api2_2x/Armature.c
source/blender/python/api2_2x/Bone.h
source/blender/python/api2_2x/Object.c
source/blender/radiosity/intern/source/radrender.c
source/blender/render/extern/include/render.h
source/blender/render/extern/include/render_types.h
source/blender/render/intern/include/pixelshading.h
source/blender/render/intern/include/rendercore.h
source/blender/render/intern/include/texture.h
source/blender/render/intern/source/envmap.c
source/blender/render/intern/source/initrender.c
source/blender/render/intern/source/pixelshading.c
source/blender/render/intern/source/ray.c
source/blender/render/intern/source/renderHelp.c
source/blender/render/intern/source/renderPreAndPost.c
source/blender/render/intern/source/rendercore.c
source/blender/render/intern/source/renderdatabase.c
source/blender/render/intern/source/shadbuf.c
source/blender/render/intern/source/texture.c
source/blender/render/intern/source/vanillaRenderPipe.c
source/blender/render/intern/source/zbuf.c
source/blender/renderconverter/intern/convertBlenderScene.c
source/blender/src/SConscript
source/blender/src/butspace.c
source/blender/src/buttons_editing.c
source/blender/src/buttons_object.c
source/blender/src/buttons_shading.c
source/blender/src/drawaction.c
source/blender/src/drawarmature.c
source/blender/src/drawimasel.c
source/blender/src/drawnla.c
source/blender/src/drawobject.c
source/blender/src/drawview.c
source/blender/src/edit.c
source/blender/src/editaction.c
source/blender/src/editarmature.c
source/blender/src/editconstraint.c
source/blender/src/editgroup.c
source/blender/src/editimasel.c
source/blender/src/editipo.c
source/blender/src/editmesh.c
source/blender/src/editmesh_mods.c
source/blender/src/editnla.c
source/blender/src/editobject.c
source/blender/src/editscreen.c
source/blender/src/editview.c
source/blender/src/filesel.c
source/blender/src/header_buttonswin.c
source/blender/src/header_image.c
source/blender/src/header_info.c
source/blender/src/header_oops.c
source/blender/src/header_view3d.c
source/blender/src/headerbuttons.c
source/blender/src/interface_panel.c
source/blender/src/meshtools.c
source/blender/src/outliner.c
source/blender/src/parametrizer.c [new file with mode: 0644]
source/blender/src/parametrizer.h [new file with mode: 0644]
source/blender/src/parametrizer_intern.h [new file with mode: 0644]
source/blender/src/poseobject.c
source/blender/src/previewrender.c
source/blender/src/space.c
source/blender/src/toets.c
source/blender/src/toolbox.c
source/blender/src/transform_conversions.c
source/blender/src/transform_generics.c
source/blender/src/transform_manipulator.c
source/blender/src/unwrapper.c
source/blender/src/view.c
source/gameengine/Expressions/KX_HashedPtr.cpp
source/gameengine/Expressions/KX_HashedPtr.h
source/gameengine/Ketsji/KX_CameraIpoSGController.cpp
source/gameengine/Ketsji/KX_GameObject.cpp
source/gameengine/Ketsji/KX_IPO_SGController.cpp
source/gameengine/Ketsji/KX_LightIpoSGController.cpp
source/gameengine/Ketsji/KX_ObColorIpoSGController.cpp
source/gameengine/Ketsji/KX_PyConstraintBinding.cpp
source/gameengine/Ketsji/KX_WorldIpoController.cpp
source/gameengine/Physics/BlOde/OdePhysicsEnvironment.h
source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.cpp
source/gameengine/Physics/Dummy/DummyPhysicsEnvironment.h
source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.cpp
source/gameengine/Physics/Sumo/SumoPhysicsEnvironment.h
source/gameengine/Physics/common/PHY_IPhysicsEnvironment.h
source/kernel/gen_system/GEN_HashedPtr.cpp
source/kernel/gen_system/GEN_HashedPtr.h
source/nan_definitions.mk
tools/scons/bs/bs_dirs.py

index 4f35471661abb4c992ad8dcfcfbf23ece656dfcf..732f3d393ece0b890879d64196b6f346dee9211e 100644 (file)
@@ -387,7 +387,7 @@ elif sys.platform == 'win32':
        platform_libs = [ 'qtmlClient', 'soundsystem',
                                         'ws2_32', 'dxguid', 'vfw32', 'winmm',
                                         'iconv', 'kernel32', 'user32', 'gdi32',
-                                        'comdlg32', 'advapi32', 'shell32',
+                                        'winspool', 'comdlg32', 'advapi32', 'shell32',
                                         'ole32', 'oleaut32', 'uuid', 
                                         'libcmt', 'libc']
        platform_libpath = ['#../lib/windows/iconv/lib',
index 7997a94344b93d0f0df68f2bdd9bde38fda6c811..bbba2c978dd71597ab4d6568bb089b87e17af3c5 100644 (file)
 #include "BMF_BitmapFont.h"
 
 
-#ifdef __APPLE__        
-#include <stdio.h>
-
-static int needs_nvidia_rasterpos_workaround(void)
-{
-       static int well_is_it= -1;
-       
-       if (well_is_it==-1)
-       {
-               well_is_it= (strncmp((char *)glGetString(GL_RENDERER), "NVIDIA GeForce 6800", 18) == 0);
-               if ( well_is_it != 0)
-               {
-                       const GLubyte* vers = glGetString(GL_VERSION);
-                       const GLubyte* v = vers;
-                       int major = 0, minor = 0, sub = 0;
-                       
-                       //advance to the '-'
-                       while ((*v != 0) && (*v!='-'))
-                               v++;
-                       
-                       if (*v == '-')
-                       {
-                               int i = 0;
-                               v++;
-                               
-                               while ((v[i] <= '9') && (v[i] >= '0'))
-                               {
-                                       major *=10;
-                                       major += v[i]-'0';
-                                       i++;
-                               }
-                               
-                               if (v[i] == '.')
-                               {
-                                       i++;
-                                       while ((v[i] <= '9') && (v[i] >= '0'))
-                                       {
-                                               minor *=10;
-                                               minor += v[i]-'0';
-                                               i++;
-                                       }
-                               }
-                               else
-                                       major = -1;
-                               
-                               if (v[i] == '.')
-                               {
-                                       i++;
-                                       while ((v[i] <= '9') && (v[i] >= '0'))
-                                       {
-                                               sub *=10;
-                                               sub += v[i]-'0';
-                                               i++;
-                                       }
-                               }
-                               else
-                                       minor = -1;
-                       }
-
-                       //OS X 10.4.3 is the first version that contained the fix for this problem
-                       // and the 6800's driver version in it is 1.4.16.  So anything after that
-                       // doesn't need the workaround
-
-                       if ( (major == -1) || (minor == -1))
-                       //If anything went wrong don't do the workaround
-                       //
-                               well_is_it = 0;
-                       else if ( (major <= 1) && (minor <= 4) && (sub < 16))
-                               well_is_it = 1;
-                       else
-                               well_is_it = 0;
-               }       
-       }
-
-       return well_is_it;
-}
-
-
-#endif
-
 BMF_BitmapFont::BMF_BitmapFont(BMF_FontData* fontData)
 : m_fontData(fontData)
 {
@@ -154,19 +74,7 @@ void BMF_BitmapFont::DrawString(char* str)
        GLint alignment;
        unsigned char c;
 
-#ifdef __APPLE__        
-     GLint vp[4];  // hack stuff        
-     GLubyte nullm = 0;      // hack stuff      
-        
-     if(needs_nvidia_rasterpos_workaround()) {  // was is_a_really_crappy_nvidia_card()
-             glGetIntegerv(GL_VIEWPORT, vp);   // hack stuff    
-        
-             glBitmap(1, 1, 0, 0, -vp[0], vp[1], &nullm);       
-        
-         }      
- #endif
-       glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
+       glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        
        while ( (c = (unsigned char) *str++) ) {
index bdd3637a5986bcbe0c918a1eb115874a245cf1c2..08928935f33da85c5869a70a4687746dc3c4ad26 100644 (file)
@@ -146,7 +146,7 @@ void BOP_mergeVertexs(BOP_Mesh *mesh, unsigned int firstFace);
  * @param facesB set of faces from object B
  */
 void BOP_Face2Face(BOP_Mesh *mesh, BOP_Faces *facesA, BOP_Faces *facesB)
-{
+{              
        for(unsigned int idxFaceA=0;idxFaceA<facesA->size();idxFaceA++) {
                BOP_Face *faceA = (*facesA)[idxFaceA];
                MT_Plane3 planeA = faceA->getPlane();
@@ -160,28 +160,28 @@ void BOP_Face2Face(BOP_Mesh *mesh, BOP_Faces *facesA, BOP_Faces *facesB)
                        idxFaceB<facesB->size() && (faceA->getTAG() != BROKEN) && (faceA->getTAG() != PHANTOM);) {
                        BOP_Face *faceB = (*facesB)[idxFaceB];
                        if ((faceB->getTAG() != BROKEN) && (faceB->getTAG() != PHANTOM)) {
-                               BOP_BBox boxB(mesh->getVertex(faceB->getVertex(0))->getPoint(),
-                                                         mesh->getVertex(faceB->getVertex(1))->getPoint(),
-                                                         mesh->getVertex(faceB->getVertex(2))->getPoint());
-                               if (boxA.intersect(boxB)) {
+                         BOP_BBox boxB(mesh->getVertex(faceB->getVertex(0))->getPoint(),
+                                       mesh->getVertex(faceB->getVertex(1))->getPoint(),
+                                       mesh->getVertex(faceB->getVertex(2))->getPoint());
+                         if (boxA.intersect(boxB)) {
 
-                                       MT_Plane3 planeB = faceB->getPlane();
-                                       if (BOP_containsPoint(planeB,p1) && 
-                                               BOP_containsPoint(planeB,p2) && 
-                                               BOP_containsPoint(planeB,p3)) {
-                                               if (BOP_orientation(planeB,planeA)>0) {
-                                                       BOP_intersectCoplanarFaces(mesh,facesB,faceA,faceB,false);
-                                               }
-                                       }
-                                       else {
-                                               BOP_intersectNonCoplanarFaces(mesh,facesA,facesB,faceA,faceB);
-                                       }
-                               }                         
+                           MT_Plane3 planeB = faceB->getPlane();
+                           if (BOP_containsPoint(planeB,p1) && 
+                               BOP_containsPoint(planeB,p2) && 
+                               BOP_containsPoint(planeB,p3)) {
+                             if (BOP_orientation(planeB,planeA)>0) {
+                               BOP_intersectCoplanarFaces(mesh,facesB,faceA,faceB,false);
+                             }
+                           }
+                           else {
+                             BOP_intersectNonCoplanarFaces(mesh,facesA,facesB,faceA,faceB);
+                           }
+                         }                       
                        }
                        if (faceB->getTAG()==BROKEN){
-                               facesB->erase(facesB->begin()+idxFaceB);
+                         facesB->erase(facesB->begin()+idxFaceB);
                        }else
-                               idxFaceB++;
+                         idxFaceB++;
                }
        }
        
index 1ef394963ac03387033464336286ff408c2ef6f6..02945340d55e25dd34c0405a764e154955b1597f 100644 (file)
@@ -92,9 +92,9 @@ BoolOpState BOP_performBooleanOperation(BoolOpType                    opType,
                                                                                CSG_VertexIteratorDescriptor  obBVertices,
                                                                                CSG_InterpolateUserFaceVertexDataFunc interpFunc)
 {
-#ifdef DEBUG
+       #ifdef DEBUG
        cout << "BEGIN BOP_performBooleanOperation" << endl;
-#endif
+       #endif
 
        // Set invert flags depending on boolean operation type:
        // INTERSECTION: A^B = and(A,B)
@@ -121,9 +121,6 @@ BoolOpState BOP_performBooleanOperation(BoolOpType                    opType,
        // Add B-mesh into C-mesh
        BOP_addMesh(&meshC, &meshBFacesId, &materials, obBProps, obBFaces, obBVertices, invertMeshB);
 
-       if (!meshC.isClosedMesh())
-               return BOP_NO_SOLID;
-
        // Perform the intersection boolean operation.
        BoolOpState result = BOP_intersectionBoolOp(&meshC, &meshAFacesId, &meshBFacesId, 
                                                                                                invertMeshA, invertMeshB);
@@ -131,9 +128,9 @@ BoolOpState BOP_performBooleanOperation(BoolOpType                    opType,
        // Invert the output mesh if is required
        *outputMesh = BOP_exportMesh(&meshC, &materials, outputProps, invertMeshC);
 
-#ifdef DEBUG
+       #ifdef DEBUG
        cout << "END BOP_performBooleanOperation" << endl;
-#endif
+       #endif
        
        return result;
 }
@@ -154,13 +151,13 @@ BoolOpState BOP_intersectionBoolOp(BOP_Mesh*  meshC,
                                                                   bool       invertMeshA,
                                                                   bool       invertMeshB)
 {
-#ifdef DEBUG
+       #ifdef DEBUG
        BOP_Chrono chrono;
        float t = 0.0f;
        float c = 0.0f;
        chrono.start();  
        cout << "---" << endl;
-#endif
+       #endif
 
        // Create BSPs trees for mesh A & B
        BOP_BSPTree bspA;
@@ -171,10 +168,10 @@ BoolOpState BOP_intersectionBoolOp(BOP_Mesh*  meshC,
        bspB.addMesh(meshC, *facesB);
        bspB.computeBox();
        
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "Create BSP     " << c << endl; 
-#endif
+       #endif
 
        unsigned int numVertices = meshC->getNumVertexs();
        
@@ -187,54 +184,54 @@ BoolOpState BOP_intersectionBoolOp(BOP_Mesh*  meshC,
        if ((0.25*facesB->size()) > bspA.getDeep())
          BOP_meshFilter(meshC, facesB, &bspA);
        
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "mesh Filter    " << c << endl; 
-#endif
+       #endif
 
        // Face 2 Face
        BOP_Face2Face(meshC,facesA,facesB);
 
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "Face2Face      " << c << endl;
-#endif
+       #endif
 
        // BSP classification
        BOP_meshClassify(meshC,facesA,&bspB);
        BOP_meshClassify(meshC,facesB,&bspA);
        
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "Classification " << c << endl;
-#endif
+       #endif
        
        // Process overlapped faces
        BOP_removeOverlappedFaces(meshC,facesA,facesB);
        
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "Remove overlap " << c << endl;
-#endif
+       #endif
 
        // Sew two meshes
        BOP_sew(meshC,facesA,facesB);
 
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "Sew            " << c << endl;
-#endif
+       #endif
 
        // Merge faces
        BOP_Merge::getInstance().mergeFaces(meshC,numVertices);
 
-#ifdef DEBUG
+       #ifdef DEBUG
        c = chrono.stamp(); t += c;
        cout << "Merge faces    " << c << endl;
        cout << "Total          " << t << endl;
        // Test integrity
        meshC->testMesh();
-#endif
+       #endif
        
        return BOP_OK;
 }
index a7e7ef61e435e2fa2d84942187eb1ed2b73db347..24d5b3fb6a90b64df4cadd8865750a8ab36d99b8 100644 (file)
@@ -553,23 +553,6 @@ BOP_Index BOP_Mesh::replaceVertexIndex(BOP_Index oldIndex, BOP_Index newIndex)
        return newIndex;
 }
 
-bool BOP_Mesh::isClosedMesh()
-{
-       for(unsigned int i=0; i<m_edges.size(); i++) {
-               BOP_Edge *edge = m_edges[i];
-               BOP_Indexs faces = edge->getFaces();
-               unsigned int count = 0;
-               const BOP_IT_Indexs facesEnd = faces.end();
-               for(BOP_IT_Indexs it = faces.begin();it!=facesEnd;it++) {
-                       if (m_faces[*it]->getTAG()!=BROKEN)
-                               count++;
-               }
-
-               if ((count%2)!=0) return false;
-       }
-
-       return true;
-}
 
 
 /** ***************************************************************************
index adc92c915594e9d50523b4173257fdc89ea6c258..6751df7c4e76058f12db0be546c4111acd447290 100644 (file)
@@ -82,7 +82,6 @@ public:
        unsigned int getNumVertexs(BOP_TAG tag);
        unsigned int getNumFaces(BOP_TAG tag);
        BOP_Index replaceVertexIndex(BOP_Index oldIndex, BOP_Index newIndex);
-       bool isClosedMesh();
        
        // Debug functions
        void print();
index a677c9c6e94a9029e43a382a510f52ff4c99efec..6c9fecd88e14feb7703b5061cf10b350ae5b7757 100755 (executable)
@@ -103,15 +103,15 @@ CSG_DescibeOperands(
 /**
  * Compute the boolean operation, UNION, INTERSECION or DIFFERENCE
  */
-int
+       int
 CSG_PerformBooleanOperation(
-                                                       CSG_BooleanOperation                 *operation,
-                                                       CSG_OperationType                     op_type,
-                                                       CSG_FaceIteratorDescriptor            obAFaces,
-                                                       CSG_VertexIteratorDescriptor          obAVertices,
-                                                       CSG_FaceIteratorDescriptor            obBFaces,
-                                                       CSG_VertexIteratorDescriptor          obBVertices,
-                                                       CSG_InterpolateUserFaceVertexDataFunc interp_func
+       CSG_BooleanOperation                 *operation,
+       CSG_OperationType                     op_type,
+       CSG_FaceIteratorDescriptor            obAFaces,
+       CSG_VertexIteratorDescriptor          obAVertices,
+       CSG_FaceIteratorDescriptor            obBFaces,
+       CSG_VertexIteratorDescriptor          obBVertices,
+       CSG_InterpolateUserFaceVertexDataFunc interp_func
 ){
        if (operation == NULL) return 0;
        BSP_MeshInfo * mesh_info = static_cast<BSP_MeshInfo *>(operation->CSG_info);
@@ -128,39 +128,33 @@ CSG_PerformBooleanOperation(
        
        switch( op_type ) {
        case e_csg_union:
-               boolType = BOP_UNION;
-               break;
+         boolType = BOP_UNION;
+         break;
        case e_csg_difference:
-               boolType = BOP_DIFFERENCE;
-               break;
+         boolType = BOP_DIFFERENCE;
+         break;
        default:
-               boolType = BOP_INTERSECTION;
-               break;
+         boolType = BOP_INTERSECTION;
+         break;
        }
 
-       BoolOpState boolOpResult;
        try {
-               boolOpResult= BOP_performBooleanOperation( boolType,
-                                                                                                  mesh_info->output_descriptor,
-                                                                                                  (BSP_CSGMesh**) &(mesh_info->output_mesh),
-                                                                                                  mesh_info->obB_descriptor,
-                                                                                                  obBFaces,
-                                                                                                  obBVertices,
-                                                                                                  mesh_info->obA_descriptor,
-                                                                                                  obAFaces,
-                                                                                                  obAVertices,
-                                                                                                  interp_func );
+       BOP_performBooleanOperation( boolType,
+                                    mesh_info->output_descriptor,
+                                    (BSP_CSGMesh**) &(mesh_info->output_mesh),
+                                        mesh_info->obB_descriptor,
+                                        obBFaces,
+                                        obBVertices,
+                                        mesh_info->obA_descriptor,
+                                    obAFaces,
+                                    obAVertices,
+                                    interp_func );
        }
        catch(...) {
                return 0;
        }
 
-       switch (boolOpResult) {
-       case BOP_OK: return 1;
-       case BOP_NO_SOLID: return -2;
-       case BOP_ERROR: return 0;
-       default: return 1;
-       }
+       return success;
 }
 
        int
index 5d30b58a98230ac8a14332934360deeb08912632..3ef20b9be3af4aa302a94a4ce6d510c2135d82cb 100644 (file)
@@ -10,8 +10,6 @@ elbeem_env.Append(CPPDEFINES= [('ELBEEM_BLENDER',1)] );
 if use_fluidsim=='false':
        # print "El'Beem Fluid Simulation Disabled..." # debug
        elbeem_env.Append (CPPPATH = user_options_dict['PNG_INCLUDE'])
-       elbeem_env.Append (CPPPATH = user_options_dict['SDL_INCLUDE'])
-       elbeem_env.Append(CPPDEFINES= 'ELBEEM_DUMMIES');
        # dummy interface build
        Sources = [ 
                "intern/utilities.cpp",
index 3111c9359dd6264b509e94420cf9f86d0413d023..4d672dee528bcecf9d2b9a944aeb0bf030bd5b8f 100644 (file)
@@ -9,30 +9,11 @@
  *
  *****************************************************************************/
  
-#ifdef ELBEEM_DUMMIES
-
 #include <stdlib.h>
-#include "ntl_vector3dim.h"
 
 extern "C" 
 int performElbeemSimulation(char *cfgfilename) {
-       return 1; // dummy
+       return 1;
 };
 
-// dummies from intern/elbeem/intern/solver_interface.cpp
-// for utilities.cpp
-
-void initGridSizes(int &sizex, int &sizey, int &sizez,
-               ntlVec3Gfx &geoStart, ntlVec3Gfx &geoEnd, 
-               int mMaxRefine, bool parallel) 
-{
-       // dummy
-}
-
-void calculateMemreqEstimate( int resx,int resy,int resz, int refine,
-               double *reqret, string *reqstr) {
-       *reqret =  0.0; // dummy
-}
-
-#endif // ELBEEM_DUMMIES
 
index ec6e094efef4b6f8ac7adfb8f5853155bd1d0a24..78b3282b7662f8d4458531fd81c5a9157872abbd 100644 (file)
@@ -70,7 +70,7 @@ PostBuild_Cmds=ECHO copy to lib ...   xcopy /Y .\release\blender_elbeem.lib ..\..\
 # PROP Target_Dir ""
 LINK32=link.exe -lib
 # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../../../../lib/windows/sdl/include" /I "../../../../../lib/windows/zlib/include" /I "../../../../../lib/windows/png/include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "NOGUI" /D "ELBEEM_BLENDER" /YX /FD /GZ /c
+# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../../../../lib/windows/sdl/include" /I "../../../../../lib/windows/zlib/include" /I "../../../../../lib/windows/png/include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D "NOGUI" /D "ELBEEM_BLENDER" /YX /FD /GZ /c
 # ADD BASE RSC /l 0x407 /d "_DEBUG"
 # ADD RSC /l 0x407 /d "_DEBUG"
 BSC32=bscmake.exe
index f2c4451233848a38188d54d08d5cc5af238620ac..afd4c345ccd4680787c443526642d34352988845 100644 (file)
@@ -273,9 +273,6 @@ ECHO Done
                        <File
                                RelativePath="..\..\intern\ntl_scene.cpp">
                        </File>
-                       <File
-                               RelativePath="..\..\intern\ntl_world.cpp">
-                       </File>
                        <File
                                RelativePath="..\..\intern\parametrizer.cpp">
                        </File>
@@ -285,18 +282,6 @@ ECHO Done
                        <File
                                RelativePath="..\..\intern\simulation_object.cpp">
                        </File>
-                       <File
-                               RelativePath="..\..\intern\solver_init.cpp">
-                       </File>
-                       <File
-                               RelativePath="..\..\intern\solver_interface.cpp">
-                       </File>
-                       <File
-                               RelativePath="..\..\intern\solver_main.cpp">
-                       </File>
-                       <File
-                               RelativePath="..\..\intern\solver_util.cpp">
-                       </File>
                        <File
                                RelativePath="..\..\intern\utilities.cpp">
                        </File>
@@ -311,9 +296,6 @@ ECHO Done
                        <File
                                RelativePath="..\..\intern\cfgparser.h">
                        </File>
-                       <File
-                               RelativePath="..\..\intern\elbeem.h">
-                       </File>
                        <File
                                RelativePath="..\..\intern\globals.h">
                        </File>
@@ -368,9 +350,6 @@ ECHO Done
                        <File
                                RelativePath="..\..\intern\ntl_vector3dim.h">
                        </File>
-                       <File
-                               RelativePath="..\..\intern\ntl_world.h">
-                       </File>
                        <File
                                RelativePath="..\..\intern\parametrizer.h">
                        </File>
@@ -380,18 +359,6 @@ ECHO Done
                        <File
                                RelativePath="..\..\intern\simulation_object.h">
                        </File>
-                       <File
-                               RelativePath="..\..\intern\solver_class.h">
-                       </File>
-                       <File
-                               RelativePath="..\..\intern\solver_dimenions.h">
-                       </File>
-                       <File
-                               RelativePath="..\..\intern\solver_interface.h">
-                       </File>
-                       <File
-                               RelativePath="..\..\intern\solver_relax.h">
-                       </File>
                        <File
                                RelativePath="..\..\intern\utilities.h">
                        </File>
index ee76349ededded616172d377408535fed415fcf0..d1caadab219edcf7f5d180fbe1c71d9f930f8b0d 100644 (file)
@@ -655,7 +655,6 @@ OSStatus GHOST_SystemCarbon::handleWindowEvent(EventRef event)
                        case kEventWindowActivated:
                                m_windowManager->setActiveWindow(window);
                                window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
-                               window->updateDrawingContext();
                                pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window) );
                                break;
                        case kEventWindowDeactivated:
@@ -664,7 +663,6 @@ OSStatus GHOST_SystemCarbon::handleWindowEvent(EventRef event)
                                break;
                        case kEventWindowUpdate:
                                //if (getFullScreen()) GHOST_PRINT("GHOST_SystemCarbon::handleWindowEvent(): full-screen update event\n");
-                               window->updateDrawingContext();
                                pushEvent( new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowUpdate, window) );
                                break;
                        case kEventWindowBoundsChanged:
index 128f1b137bcfb12550dc2e2ba5182165948c9981..345cf0dc7170f8f77b9a98b57a6a375277f24c0b 100644 (file)
@@ -89,10 +89,6 @@ typedef void* NLContext;
 #define NL_SYMMETRIC        0x106
 #define NL_ERROR            0x108
 
-/* Enable / Disable */
-
-#define NL_NORMALIZE_ROWS  0x400
-
 /* Row parameters */
 
 #define NL_RIGHT_HAND_SIDE 0x500
@@ -142,7 +138,9 @@ void nlRightHandSideAdd(NLuint index, NLfloat value);
 
 /* Solve */
 
-NLboolean nlSolve(void);
+void nlPrintMatrix(void);
+NLboolean nlSolve();
+NLboolean nlSolveAdvanced(NLint *permutation, NLboolean solveAgain);
 
 #ifdef __cplusplus
 }
index 7773582e0272932262883ea2424bc18b7c5d29c3..c5518731c6bccf3e106cebbde1ad36d9715ad2f8 100644 (file)
  *
  *  Contact: Bruno Levy
  *
- *     levy@loria.fr
+ *      levy@loria.fr
  *
- *     ISA Project
- *     LORIA, INRIA Lorraine, 
- *     Campus Scientifique, BP 239
- *     54506 VANDOEUVRE LES NANCY CEDEX 
- *     FRANCE
+ *      ISA Project
+ *      LORIA, INRIA Lorraine, 
+ *      Campus Scientifique, BP 239
+ *      54506 VANDOEUVRE LES NANCY CEDEX 
+ *      FRANCE
  *
  *  Note that the GNU General Public License does not permit incorporating
  *  the Software into proprietary programs. 
 
 
 static void __nl_assertion_failed(char* cond, char* file, int line) {
-    fprintf(
-        stderr, 
-        "OpenNL assertion failed: %s, file:%s, line:%d\n",
-        cond,file,line
-    );
-    abort();
+       fprintf(
+               stderr, 
+               "OpenNL assertion failed: %s, file:%s, line:%d\n",
+               cond,file,line
+       );
+       abort();
 }
 
 static void __nl_range_assertion_failed(
-    float x, float min_val, float max_val, char* file, int line
+       float x, float min_val, float max_val, char* file, int line
 ) {
-    fprintf(
-        stderr, 
-        "OpenNL range assertion failed: %f in [ %f ... %f ], file:%s, line:%d\n",
-        x, min_val, max_val, file,line
-    );
-    abort();
+       fprintf(
+               stderr, 
+               "OpenNL range assertion failed: %f in [ %f ... %f ], file:%s, line:%d\n",
+               x, min_val, max_val, file,line
+       );
+       abort();
 }
 
 static void __nl_should_not_have_reached(char* file, int line) {
-    fprintf(
-        stderr, 
-        "OpenNL should not have reached this point: file:%s, line:%d\n",
-        file,line
-    );
-    abort();
+       fprintf(
+               stderr, 
+               "OpenNL should not have reached this point: file:%s, line:%d\n",
+               file,line
+       );
+       abort();
 }
 
 
-#define __nl_assert(x) {                                        \
-    if(!(x)) {                                                  \
-        __nl_assertion_failed(#x,__FILE__, __LINE__);          \
-    }                                                           \
+#define __nl_assert(x) {                                                                               \
+       if(!(x)) {                                                                                                \
+               __nl_assertion_failed(#x,__FILE__, __LINE__);             \
+       }                                                                                                                  \
 } 
 
-#define __nl_range_assert(x,min_val,max_val) {                  \
-    if(((x) < (min_val)) || ((x) > (max_val))) {                \
-        __nl_range_assertion_failed(x, min_val, max_val,        \
-            __FILE__, __LINE__                                  \
-        );                                                     \
-    }                                                           \
+#define __nl_range_assert(x,min_val,max_val) {                           \
+       if(((x) < (min_val)) || ((x) > (max_val))) {                            \
+               __nl_range_assertion_failed(x, min_val, max_val,                \
+                       __FILE__, __LINE__                                                                \
+               );                                                                                                       \
+       }                                                                                                                  \
 }
 
-#define __nl_assert_not_reached {                               \
-    __nl_should_not_have_reached(__FILE__, __LINE__);          \
+#define __nl_assert_not_reached {                                                         \
+       __nl_should_not_have_reached(__FILE__, __LINE__);                 \
 }
 
 #ifdef NL_DEBUG
@@ -135,301 +135,301 @@ static void __nl_should_not_have_reached(char* file, int line) {
 /************************************************************************************/
 /* memory management */
 
-#define __NL_NEW(T)                (T*)(calloc(1, sizeof(T))) 
-#define __NL_NEW_ARRAY(T,NB)       (T*)(calloc((NB),sizeof(T))) 
+#define __NL_NEW(T)                            (T*)(calloc(1, sizeof(T))) 
+#define __NL_NEW_ARRAY(T,NB)      (T*)(calloc((NB),sizeof(T))) 
 #define __NL_RENEW_ARRAY(T,x,NB)   (T*)(realloc(x,(NB)*sizeof(T))) 
-#define __NL_DELETE(x)             free(x); x = NULL 
-#define __NL_DELETE_ARRAY(x)       free(x); x = NULL
+#define __NL_DELETE(x)                  free(x); x = NULL 
+#define __NL_DELETE_ARRAY(x)      free(x); x = NULL
 
-#define __NL_CLEAR(T, x)           memset(x, 0, sizeof(T)) 
+#define __NL_CLEAR(T, x)                  memset(x, 0, sizeof(T)) 
 #define __NL_CLEAR_ARRAY(T,x,NB)   memset(x, 0, (NB)*sizeof(T)) 
 
 /************************************************************************************/
 /* Dynamic arrays for sparse row/columns */
 
 typedef struct {
-    NLuint   index;
-    NLfloat value;
+       NLuint   index;
+       NLfloat value;
 } __NLCoeff;
 
 typedef struct {
-    NLuint size;
-    NLuint capacity;
-    __NLCoeff* coeff;
+       NLuint size;
+       NLuint capacity;
+       __NLCoeff* coeff;
 } __NLRowColumn;
 
 static void __nlRowColumnConstruct(__NLRowColumn* c) {
-    c->size     = 0;
-    c->capacity = 0;
-    c->coeff    = NULL;
+       c->size  = 0;
+       c->capacity = 0;
+       c->coeff        = NULL;
 }
 
 static void __nlRowColumnDestroy(__NLRowColumn* c) {
-    __NL_DELETE_ARRAY(c->coeff);
+       __NL_DELETE_ARRAY(c->coeff);
 #ifdef NL_PARANOID
-    __NL_CLEAR(__NLRowColumn, c); 
+       __NL_CLEAR(__NLRowColumn, c); 
 #endif
 }
 
 static void __nlRowColumnGrow(__NLRowColumn* c) {
-    if(c->capacity != 0) {
-        c->capacity = 2 * c->capacity;
-        c->coeff = __NL_RENEW_ARRAY(__NLCoeff, c->coeff, c->capacity);
-    } else {
-        c->capacity = 4;
-        c->coeff = __NL_NEW_ARRAY(__NLCoeff, c->capacity);
-    }
+       if(c->capacity != 0) {
+               c->capacity = 2 * c->capacity;
+               c->coeff = __NL_RENEW_ARRAY(__NLCoeff, c->coeff, c->capacity);
+       } else {
+               c->capacity = 4;
+               c->coeff = __NL_NEW_ARRAY(__NLCoeff, c->capacity);
+       }
 }
 
 static void __nlRowColumnAdd(__NLRowColumn* c, NLint index, NLfloat value) {
-    NLuint i;
-    for(i=0; i<c->size; i++) {
-        if(c->coeff[i].index == (NLuint)index) {
-            c->coeff[i].value += value;
-            return;
-        }
-    }
-    if(c->size == c->capacity) {
-        __nlRowColumnGrow(c);
-    }
-    c->coeff[c->size].index = index;
-    c->coeff[c->size].value = value;
-    c->size++;
+       NLuint i;
+       for(i=0; i<c->size; i++) {
+               if(c->coeff[i].index == (NLuint)index) {
+                       c->coeff[i].value += value;
+                       return;
+               }
+       }
+       if(c->size == c->capacity) {
+               __nlRowColumnGrow(c);
+       }
+       c->coeff[c->size].index = index;
+       c->coeff[c->size].value = value;
+       c->size++;
 }
 
 /* Does not check whether the index already exists */
 static void __nlRowColumnAppend(__NLRowColumn* c, NLint index, NLfloat value) {
-    if(c->size == c->capacity) {
-        __nlRowColumnGrow(c);
-    }
-    c->coeff[c->size].index = index;
-    c->coeff[c->size].value = value;
-    c->size++;
+       if(c->size == c->capacity) {
+               __nlRowColumnGrow(c);
+       }
+       c->coeff[c->size].index = index;
+       c->coeff[c->size].value = value;
+       c->size++;
 }
 
 static void __nlRowColumnZero(__NLRowColumn* c) {
-    c->size = 0;
+       c->size = 0;
 }
 
 static void __nlRowColumnClear(__NLRowColumn* c) {
-    c->size     = 0;
-    c->capacity = 0;
-    __NL_DELETE_ARRAY(c->coeff);
+       c->size  = 0;
+       c->capacity = 0;
+       __NL_DELETE_ARRAY(c->coeff);
 }
 
 /************************************************************************************/
 /* SparseMatrix data structure */
 
-#define __NL_ROWS      1
+#define __NL_ROWS        1
 #define __NL_COLUMNS   2
 #define __NL_SYMMETRIC 4
 
 typedef struct {
-    NLuint m;
-    NLuint n;
-    NLuint diag_size;
-    NLenum storage;
-    __NLRowColumn* row;
-    __NLRowColumn* column;
-    NLfloat*      diag;
+       NLuint m;
+       NLuint n;
+       NLuint diag_size;
+       NLenum storage;
+       __NLRowColumn* row;
+       __NLRowColumn* column;
+       NLfloat*          diag;
 } __NLSparseMatrix;
 
 
 static void __nlSparseMatrixConstruct(
-    __NLSparseMatrix* M, NLuint m, NLuint n, NLenum storage
+       __NLSparseMatrix* M, NLuint m, NLuint n, NLenum storage
 ) {
-    NLuint i;
-    M->m = m;
-    M->n = n;
-    M->storage = storage;
-    if(storage & __NL_ROWS) {
-        M->row = __NL_NEW_ARRAY(__NLRowColumn, m);
-        for(i=0; i<n; i++) {
-            __nlRowColumnConstruct(&(M->row[i]));
-        }
-    } else {
-        M->row = NULL;
-    }
-
-    if(storage & __NL_COLUMNS) {
-        M->column = __NL_NEW_ARRAY(__NLRowColumn, n);
-        for(i=0; i<n; i++) {
-            __nlRowColumnConstruct(&(M->column[i]));
-        }
-    } else {
-        M->column = NULL;
-    }
-
-    M->diag_size = MIN(m,n);
-    M->diag = __NL_NEW_ARRAY(NLfloat, M->diag_size);
+       NLuint i;
+       M->m = m;
+       M->n = n;
+       M->storage = storage;
+       if(storage & __NL_ROWS) {
+               M->row = __NL_NEW_ARRAY(__NLRowColumn, m);
+               for(i=0; i<n; i++) {
+                       __nlRowColumnConstruct(&(M->row[i]));
+               }
+       } else {
+               M->row = NULL;
+       }
+
+       if(storage & __NL_COLUMNS) {
+               M->column = __NL_NEW_ARRAY(__NLRowColumn, n);
+               for(i=0; i<n; i++) {
+                       __nlRowColumnConstruct(&(M->column[i]));
+               }
+       } else {
+               M->column = NULL;
+       }
+
+       M->diag_size = MIN(m,n);
+       M->diag = __NL_NEW_ARRAY(NLfloat, M->diag_size);
 }
 
 static void __nlSparseMatrixDestroy(__NLSparseMatrix* M) {
-    NLuint i;
-    __NL_DELETE_ARRAY(M->diag);
-    if(M->storage & __NL_ROWS) {
-        for(i=0; i<M->m; i++) {
-            __nlRowColumnDestroy(&(M->row[i]));
-        }
-        __NL_DELETE_ARRAY(M->row);
-    }
-    if(M->storage & __NL_COLUMNS) {
-        for(i=0; i<M->n; i++) {
-            __nlRowColumnDestroy(&(M->column[i]));
-        }
-        __NL_DELETE_ARRAY(M->column);
-    }
+       NLuint i;
+       __NL_DELETE_ARRAY(M->diag);
+       if(M->storage & __NL_ROWS) {
+               for(i=0; i<M->m; i++) {
+                       __nlRowColumnDestroy(&(M->row[i]));
+               }
+               __NL_DELETE_ARRAY(M->row);
+       }
+       if(M->storage & __NL_COLUMNS) {
+               for(i=0; i<M->n; i++) {
+                       __nlRowColumnDestroy(&(M->column[i]));
+               }
+               __NL_DELETE_ARRAY(M->column);
+       }
 #ifdef NL_PARANOID
-    __NL_CLEAR(__NLSparseMatrix,M);
+       __NL_CLEAR(__NLSparseMatrix,M);
 #endif
 }
 
 static void __nlSparseMatrixAdd(
-    __NLSparseMatrix* M, NLuint i, NLuint j, NLfloat value
+       __NLSparseMatrix* M, NLuint i, NLuint j, NLfloat value
 ) {
-    __nl_parano_range_assert(i, 0, M->m - 1);
-    __nl_parano_range_assert(j, 0, M->n - 1);
-    if((M->storage & __NL_SYMMETRIC) && (j > i)) {
-        return;
-    }
-    if(i == j) {
-        M->diag[i] += value;
-    }
-    if(M->storage & __NL_ROWS) {
-        __nlRowColumnAdd(&(M->row[i]), j, value);
-    }
-    if(M->storage & __NL_COLUMNS) {
-        __nlRowColumnAdd(&(M->column[j]), i, value);
-    }
+       __nl_parano_range_assert(i, 0, M->m - 1);
+       __nl_parano_range_assert(j, 0, M->n - 1);
+       if((M->storage & __NL_SYMMETRIC) && (j > i)) {
+               return;
+       }
+       if(i == j) {
+               M->diag[i] += value;
+       }
+       if(M->storage & __NL_ROWS) {
+               __nlRowColumnAdd(&(M->row[i]), j, value);
+       }
+       if(M->storage & __NL_COLUMNS) {
+               __nlRowColumnAdd(&(M->column[j]), i, value);
+       }
 }
 
 static void __nlSparseMatrixClear( __NLSparseMatrix* M) {
-    NLuint i;
-    if(M->storage & __NL_ROWS) {
-        for(i=0; i<M->m; i++) {
-            __nlRowColumnClear(&(M->row[i]));
-        }
-    }
-    if(M->storage & __NL_COLUMNS) {
-        for(i=0; i<M->n; i++) {
-            __nlRowColumnClear(&(M->column[i]));
-        }
-    }
-    __NL_CLEAR_ARRAY(NLfloat, M->diag, M->diag_size);    
+       NLuint i;
+       if(M->storage & __NL_ROWS) {
+               for(i=0; i<M->m; i++) {
+                       __nlRowColumnClear(&(M->row[i]));
+               }
+       }
+       if(M->storage & __NL_COLUMNS) {
+               for(i=0; i<M->n; i++) {
+                       __nlRowColumnClear(&(M->column[i]));
+               }
+       }
+       __NL_CLEAR_ARRAY(NLfloat, M->diag, M->diag_size);       
 }
 
 /* Returns the number of non-zero coefficients */
 static NLuint __nlSparseMatrixNNZ( __NLSparseMatrix* M) {
-    NLuint nnz = 0;
-    NLuint i;
-    if(M->storage & __NL_ROWS) {
-        for(i = 0; i<M->m; i++) {
-            nnz += M->row[i].size;
-        }
-    } else if (M->storage & __NL_COLUMNS) {
-        for(i = 0; i<M->n; i++) {
-            nnz += M->column[i].size;
-        }
-    } else {
-        __nl_assert_not_reached;
-    }
-    return nnz;
+       NLuint nnz = 0;
+       NLuint i;
+       if(M->storage & __NL_ROWS) {
+               for(i = 0; i<M->m; i++) {
+                       nnz += M->row[i].size;
+               }
+       } else if (M->storage & __NL_COLUMNS) {
+               for(i = 0; i<M->n; i++) {
+                       nnz += M->column[i].size;
+               }
+       } else {
+               __nl_assert_not_reached;
+       }
+       return nnz;
 }
 
 /************************************************************************************/
 /* SparseMatrix x Vector routines, internal helper routines */
 
 static void __nlSparseMatrix_mult_rows_symmetric(
-    __NLSparseMatrix* A, NLfloat* x, NLfloat* y
+       __NLSparseMatrix* A, NLfloat* x, NLfloat* y
 ) {
-    NLuint m = A->m;
-    NLuint i,ij;
-    __NLRowColumn* Ri = NULL;
-    __NLCoeff* c = NULL;
-    for(i=0; i<m; i++) {
-        y[i] = 0;
-        Ri = &(A->row[i]);
-        for(ij=0; ij<Ri->size; ij++) {
-            c = &(Ri->coeff[ij]);
-            y[i] += c->value * x[c->index];
-            if(i != c->index) {
-                y[c->index] += c->value * x[i];
-            }
-        }
-    }
+       NLuint m = A->m;
+       NLuint i,ij;
+       __NLRowColumn* Ri = NULL;
+       __NLCoeff* c = NULL;
+       for(i=0; i<m; i++) {
+               y[i] = 0;
+               Ri = &(A->row[i]);
+               for(ij=0; ij<Ri->size; ij++) {
+                       c = &(Ri->coeff[ij]);
+                       y[i] += c->value * x[c->index];
+                       if(i != c->index) {
+                               y[c->index] += c->value * x[i];
+                       }
+               }
+       }
 }
 
 static void __nlSparseMatrix_mult_rows(
-    __NLSparseMatrix* A, NLfloat* x, NLfloat* y
+       __NLSparseMatrix* A, NLfloat* x, NLfloat* y
 ) {
-    NLuint m = A->m;
-    NLuint i,ij;
-    __NLRowColumn* Ri = NULL;
-    __NLCoeff* c = NULL;
-    for(i=0; i<m; i++) {
-        y[i] = 0;
-        Ri = &(A->row[i]);
-        for(ij=0; ij<Ri->size; ij++) {
-            c = &(Ri->coeff[ij]);
-            y[i] += c->value * x[c->index];
-        }
-    }
+       NLuint m = A->m;
+       NLuint i,ij;
+       __NLRowColumn* Ri = NULL;
+       __NLCoeff* c = NULL;
+       for(i=0; i<m; i++) {
+               y[i] = 0;
+               Ri = &(A->row[i]);
+               for(ij=0; ij<Ri->size; ij++) {
+                       c = &(Ri->coeff[ij]);
+                       y[i] += c->value * x[c->index];
+               }
+       }
 }
 
 static void __nlSparseMatrix_mult_cols_symmetric(
-    __NLSparseMatrix* A, NLfloat* x, NLfloat* y
+       __NLSparseMatrix* A, NLfloat* x, NLfloat* y
 ) {
-    NLuint n = A->n;
-    NLuint j,ii;
-    __NLRowColumn* Cj = NULL;
-    __NLCoeff* c = NULL;
-    for(j=0; j<n; j++) {
-        y[j] = 0;
-        Cj = &(A->column[j]);
-        for(ii=0; ii<Cj->size; ii++) {
-            c = &(Cj->coeff[ii]);
-            y[c->index] += c->value * x[j];
-            if(j != c->index) {
-                y[j] += c->value * x[c->index];
-            }
-        }
-    }
+       NLuint n = A->n;
+       NLuint j,ii;
+       __NLRowColumn* Cj = NULL;
+       __NLCoeff* c = NULL;
+       for(j=0; j<n; j++) {
+               y[j] = 0;
+               Cj = &(A->column[j]);
+               for(ii=0; ii<Cj->size; ii++) {
+                       c = &(Cj->coeff[ii]);
+                       y[c->index] += c->value * x[j];
+                       if(j != c->index) {
+                               y[j] += c->value * x[c->index];
+                       }
+               }
+       }
 }
 
 static void __nlSparseMatrix_mult_cols(
-    __NLSparseMatrix* A, NLfloat* x, NLfloat* y
+       __NLSparseMatrix* A, NLfloat* x, NLfloat* y
 ) {
-    NLuint n = A->n;
-    NLuint j,ii; 
-    __NLRowColumn* Cj = NULL;
-    __NLCoeff* c = NULL;
-    __NL_CLEAR_ARRAY(NLfloat, y, A->m);
-    for(j=0; j<n; j++) {
-        Cj = &(A->column[j]);
-        for(ii=0; ii<Cj->size; ii++) {
-            c = &(Cj->coeff[ii]);
-            y[c->index] += c->value * x[j];
-        }
-    }
+       NLuint n = A->n;
+       NLuint j,ii; 
+       __NLRowColumn* Cj = NULL;
+       __NLCoeff* c = NULL;
+       __NL_CLEAR_ARRAY(NLfloat, y, A->m);
+       for(j=0; j<n; j++) {
+               Cj = &(A->column[j]);
+               for(ii=0; ii<Cj->size; ii++) {
+                       c = &(Cj->coeff[ii]);
+                       y[c->index] += c->value * x[j];
+               }
+       }
 }
 
 /************************************************************************************/
 /* SparseMatrix x Vector routines, main driver routine */
 
 static void __nlSparseMatrixMult(__NLSparseMatrix* A, NLfloat* x, NLfloat* y) {
-    if(A->storage & __NL_ROWS) {
-        if(A->storage & __NL_SYMMETRIC) {
-            __nlSparseMatrix_mult_rows_symmetric(A, x, y);
-        } else {
-            __nlSparseMatrix_mult_rows(A, x, y);
-        }
-    } else {
-        if(A->storage & __NL_SYMMETRIC) {
-            __nlSparseMatrix_mult_cols_symmetric(A, x, y);
-        } else {
-            __nlSparseMatrix_mult_cols(A, x, y);
-        }
-    }
+       if(A->storage & __NL_ROWS) {
+               if(A->storage & __NL_SYMMETRIC) {
+                       __nlSparseMatrix_mult_rows_symmetric(A, x, y);
+               } else {
+                       __nlSparseMatrix_mult_rows(A, x, y);
+               }
+       } else {
+               if(A->storage & __NL_SYMMETRIC) {
+                       __nlSparseMatrix_mult_cols_symmetric(A, x, y);
+               } else {
+                       __nlSparseMatrix_mult_cols(A, x, y);
+               }
+       }
 }
 
 /************************************************************************************/
@@ -438,513 +438,467 @@ static void __nlSparseMatrixMult(__NLSparseMatrix* A, NLfloat* x, NLfloat* y) {
 typedef void(*__NLMatrixFunc)(float* x, float* y);
 
 typedef struct {
-    NLfloat  value;
-    NLboolean locked;
-    NLuint    index;
+       NLfloat  value;
+       NLboolean locked;
+       NLuint  index;
 } __NLVariable;
 
-#define __NL_STATE_INITIAL            0
-#define __NL_STATE_SYSTEM             1
-#define __NL_STATE_MATRIX             2
-#define __NL_STATE_ROW                3
-#define __NL_STATE_MATRIX_CONSTRUCTED 4
-#define __NL_STATE_SYSTEM_CONSTRUCTED 5
-#define __NL_STATE_SOLVED             6
+#define __NL_STATE_INITIAL                             0
+#define __NL_STATE_SYSTEM                              1
+#define __NL_STATE_MATRIX                              2
+#define __NL_STATE_ROW                                 3
+#define __NL_STATE_MATRIX_CONSTRUCTED  4
+#define __NL_STATE_SYSTEM_CONSTRUCTED  5
+#define __NL_STATE_SYSTEM_SOLVED               7
 
 typedef struct {
-    NLenum           state;
-    __NLVariable*    variable;
-    NLuint           n;
-    __NLSparseMatrix M;
-    __NLRowColumn    af;
-    __NLRowColumn    al;
-    __NLRowColumn    xl;
-    NLfloat*        x;
-    NLfloat*        b;
-    NLfloat         right_hand_side;
-    NLfloat         row_scaling;
-    NLuint           nb_variables;
-    NLuint           current_row;
-    NLboolean        least_squares;
-    NLboolean        symmetric;
-    NLboolean        normalize_rows;
-    NLboolean        alloc_M;
-    NLboolean        alloc_af;
-    NLboolean        alloc_al;
-    NLboolean        alloc_xl;
-    NLboolean        alloc_variable;
-    NLboolean        alloc_x;
-    NLboolean        alloc_b;
-    NLfloat         error;
-    __NLMatrixFunc   matrix_vector_prod;
+       NLenum             state;
+       __NLVariable*   variable;
+       NLuint             n;
+       __NLSparseMatrix M;
+       __NLRowColumn   af;
+       __NLRowColumn   al;
+       NLfloat*                x;
+       NLfloat*                b;
+       NLfloat          right_hand_side;
+       NLuint             nb_variables;
+       NLuint             current_row;
+       NLboolean               least_squares;
+       NLboolean               symmetric;
+       NLboolean               solve_again;
+       NLboolean               alloc_M;
+       NLboolean               alloc_af;
+       NLboolean               alloc_al;
+       NLboolean               alloc_variable;
+       NLboolean               alloc_x;
+       NLboolean               alloc_b;
+       NLfloat          error;
+       __NLMatrixFunc   matrix_vector_prod;
+
+       struct __NLSuperLUContext {
+               NLboolean alloc_slu;
+               SuperMatrix L, U;
+               NLint *perm_c, *perm_r;
+               SuperLUStat_t stat;
+       } slu;
 } __NLContext;
 
 static __NLContext* __nlCurrentContext = NULL;
 
 static void __nlMatrixVectorProd_default(NLfloat* x, NLfloat* y) {
-    __nlSparseMatrixMult(&(__nlCurrentContext->M), x, y);
+       __nlSparseMatrixMult(&(__nlCurrentContext->M), x, y);
 }
 
 
 NLContext nlNewContext(void) {
-    __NLContext* result      = __NL_NEW(__NLContext);
-    result->state            = __NL_STATE_INITIAL;
-    result->row_scaling      = 1.0;
-    result->right_hand_side  = 0.0;
-    result->matrix_vector_prod = __nlMatrixVectorProd_default;
-    nlMakeCurrent(result);
-    return result;
+       __NLContext* result       = __NL_NEW(__NLContext);
+       result->state                   = __NL_STATE_INITIAL;
+       result->right_hand_side  = 0.0;
+       result->matrix_vector_prod = __nlMatrixVectorProd_default;
+       nlMakeCurrent(result);
+       return result;
 }
 
+static void __nlFree_SUPERLU(__NLContext *context);
+
 void nlDeleteContext(NLContext context_in) {
-    __NLContext* context = (__NLContext*)(context_in);
-    if(__nlCurrentContext == context) {
-        __nlCurrentContext = NULL;
-    }
-    if(context->alloc_M) {
-        __nlSparseMatrixDestroy(&context->M);
-    }
-    if(context->alloc_af) {
-        __nlRowColumnDestroy(&context->af);
-    }
-    if(context->alloc_al) {
-        __nlRowColumnDestroy(&context->al);
-    }
-    if(context->alloc_xl) {
-        __nlRowColumnDestroy(&context->xl);
-    }
-    if(context->alloc_variable) {
-        __NL_DELETE_ARRAY(context->variable);
-    }
-    if(context->alloc_x) {
-        __NL_DELETE_ARRAY(context->x);
-    }
-    if(context->alloc_b) {
-        __NL_DELETE_ARRAY(context->b);
-    }
+       __NLContext* context = (__NLContext*)(context_in);
+       if(__nlCurrentContext == context) {
+               __nlCurrentContext = NULL;
+       }
+       if(context->alloc_M) {
+               __nlSparseMatrixDestroy(&context->M);
+       }
+       if(context->alloc_af) {
+               __nlRowColumnDestroy(&context->af);
+       }
+       if(context->alloc_al) {
+               __nlRowColumnDestroy(&context->al);
+       }
+       if(context->alloc_variable) {
+               __NL_DELETE_ARRAY(context->variable);
+       }
+       if(context->alloc_x) {
+               __NL_DELETE_ARRAY(context->x);
+       }
+       if(context->alloc_b) {
+               __NL_DELETE_ARRAY(context->b);
+       }
+       if (context->slu.alloc_slu) {
+               __nlFree_SUPERLU(context);
+       }
 
 #ifdef NL_PARANOID
-    __NL_CLEAR(__NLContext, context);
+       __NL_CLEAR(__NLContext, context);
 #endif
-    __NL_DELETE(context);
+       __NL_DELETE(context);
 }
 
 void nlMakeCurrent(NLContext context) {
-    __nlCurrentContext = (__NLContext*)(context);
+       __nlCurrentContext = (__NLContext*)(context);
 }
 
 NLContext nlGetCurrent(void) {
-    return __nlCurrentContext;
+       return __nlCurrentContext;
 }
 
 static void __nlCheckState(NLenum state) {
-    __nl_assert(__nlCurrentContext->state == state);
+       __nl_assert(__nlCurrentContext->state == state);
 }
 
 static void __nlTransition(NLenum from_state, NLenum to_state) {
-    __nlCheckState(from_state);
-    __nlCurrentContext->state = to_state;
+       __nlCheckState(from_state);
+       __nlCurrentContext->state = to_state;
 }
 
 /************************************************************************************/
 /* Get/Set parameters */
 
 void nlSolverParameterf(NLenum pname, NLfloat param) {
-    __nlCheckState(__NL_STATE_INITIAL);
-    switch(pname) {
-    case NL_NB_VARIABLES: {
-        __nl_assert(param > 0);
-        __nlCurrentContext->nb_variables = (NLuint)param;
-    } break;
-    case NL_LEAST_SQUARES: {
-        __nlCurrentContext->least_squares = (NLboolean)param;
-    } break;
-    case NL_SYMMETRIC: {
-        __nlCurrentContext->symmetric = (NLboolean)param;        
-    }
-    default: {
-        __nl_assert_not_reached;
-    } break;
-    }
+       __nlCheckState(__NL_STATE_INITIAL);
+       switch(pname) {
+       case NL_NB_VARIABLES: {
+               __nl_assert(param > 0);
+               __nlCurrentContext->nb_variables = (NLuint)param;
+       } break;
+       case NL_LEAST_SQUARES: {
+               __nlCurrentContext->least_squares = (NLboolean)param;
+       } break;
+       case NL_SYMMETRIC: {
+               __nlCurrentContext->symmetric = (NLboolean)param;               
+       }
+       default: {
+               __nl_assert_not_reached;
+       } break;
+       }
 }
 
 void nlSolverParameteri(NLenum pname, NLint param) {
-    __nlCheckState(__NL_STATE_INITIAL);
-    switch(pname) {
-    case NL_NB_VARIABLES: {
-        __nl_assert(param > 0);
-        __nlCurrentContext->nb_variables = (NLuint)param;
-    } break;
-    case NL_LEAST_SQUARES: {
-        __nlCurrentContext->least_squares = (NLboolean)param;
-    } break;
-    case NL_SYMMETRIC: {
-        __nlCurrentContext->symmetric = (NLboolean)param;        
-    }
-    default: {
-        __nl_assert_not_reached;
-    } break;
-    }
+       __nlCheckState(__NL_STATE_INITIAL);
+       switch(pname) {
+       case NL_NB_VARIABLES: {
+               __nl_assert(param > 0);
+               __nlCurrentContext->nb_variables = (NLuint)param;
+       } break;
+       case NL_LEAST_SQUARES: {
+               __nlCurrentContext->least_squares = (NLboolean)param;
+       } break;
+       case NL_SYMMETRIC: {
+               __nlCurrentContext->symmetric = (NLboolean)param;               
+       }
+       default: {
+               __nl_assert_not_reached;
+       } break;
+       }
 }
 
 void nlRowParameterf(NLenum pname, NLfloat param) {
-    __nlCheckState(__NL_STATE_MATRIX);
-    switch(pname) {
-    case NL_RIGHT_HAND_SIDE: {
-        __nlCurrentContext->right_hand_side = param;
-    } break;
-    case NL_ROW_SCALING: {
-        __nlCurrentContext->row_scaling = param;
-    } break;
-    }
+       __nlCheckState(__NL_STATE_MATRIX);
+       switch(pname) {
+       case NL_RIGHT_HAND_SIDE: {
+               __nlCurrentContext->right_hand_side = param;
+       } break;
+       }
 }
 
 void nlRowParameteri(NLenum pname, NLint param) {
-    __nlCheckState(__NL_STATE_MATRIX);
-    switch(pname) {
-    case NL_RIGHT_HAND_SIDE: {
-        __nlCurrentContext->right_hand_side = (NLfloat)param;
-    } break;
-    case NL_ROW_SCALING: {
-        __nlCurrentContext->row_scaling = (NLfloat)param;
-    } break;
-    }
+       __nlCheckState(__NL_STATE_MATRIX);
+       switch(pname) {
+       case NL_RIGHT_HAND_SIDE: {
+               __nlCurrentContext->right_hand_side = (NLfloat)param;
+       } break;
+       }
 }
 
 void nlGetBooleanv(NLenum pname, NLboolean* params) {
-    switch(pname) {
-    case NL_LEAST_SQUARES: {
-        *params = __nlCurrentContext->least_squares;
-    } break;
-    case NL_SYMMETRIC: {
-        *params = __nlCurrentContext->symmetric;
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    } break;
-    }
+       switch(pname) {
+       case NL_LEAST_SQUARES: {
+               *params = __nlCurrentContext->least_squares;
+       } break;
+       case NL_SYMMETRIC: {
+               *params = __nlCurrentContext->symmetric;
+       } break;
+       default: {
+               __nl_assert_not_reached;
+       } break;
+       }
 }
 
 void nlGetFloatv(NLenum pname, NLfloat* params) {
-    switch(pname) {
-    case NL_NB_VARIABLES: {
-        *params = (NLfloat)(__nlCurrentContext->nb_variables);
-    } break;
-    case NL_LEAST_SQUARES: {
-        *params = (NLfloat)(__nlCurrentContext->least_squares);
-    } break;
-    case NL_SYMMETRIC: {
-        *params = (NLfloat)(__nlCurrentContext->symmetric);
-    } break;
-    case NL_ERROR: {
-        *params = (NLfloat)(__nlCurrentContext->error);
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    } break;
-    }
+       switch(pname) {
+       case NL_NB_VARIABLES: {
+               *params = (NLfloat)(__nlCurrentContext->nb_variables);
+       } break;
+       case NL_LEAST_SQUARES: {
+               *params = (NLfloat)(__nlCurrentContext->least_squares);
+       } break;
+       case NL_SYMMETRIC: {
+               *params = (NLfloat)(__nlCurrentContext->symmetric);
+       } break;
+       case NL_ERROR: {
+               *params = (NLfloat)(__nlCurrentContext->error);
+       } break;
+       default: {
+               __nl_assert_not_reached;
+       } break;
+       }
 }
 
 void nlGetIntergerv(NLenum pname, NLint* params) {
-    switch(pname) {
-    case NL_NB_VARIABLES: {
-        *params = (NLint)(__nlCurrentContext->nb_variables);
-    } break;
-    case NL_LEAST_SQUARES: {
-        *params = (NLint)(__nlCurrentContext->least_squares);
-    } break;
-    case NL_SYMMETRIC: {
-        *params = (NLint)(__nlCurrentContext->symmetric);
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    } break;
-    }
+       switch(pname) {
+       case NL_NB_VARIABLES: {
+               *params = (NLint)(__nlCurrentContext->nb_variables);
+       } break;
+       case NL_LEAST_SQUARES: {
+               *params = (NLint)(__nlCurrentContext->least_squares);
+       } break;
+       case NL_SYMMETRIC: {
+               *params = (NLint)(__nlCurrentContext->symmetric);
+       } break;
+       default: {
+               __nl_assert_not_reached;
+       } break;
+       }
 }
 
 /************************************************************************************/
 /* Enable / Disable */
 
 void nlEnable(NLenum pname) {
-    switch(pname) {
-    case NL_NORMALIZE_ROWS: {
-        __nl_assert(__nlCurrentContext->state != __NL_STATE_ROW);
-        __nlCurrentContext->normalize_rows = NL_TRUE;
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    }
-    }
+       switch(pname) {
+       default: {
+               __nl_assert_not_reached;
+       }
+       }
 }
 
 void nlDisable(NLenum pname) {
-    switch(pname) {
-    case NL_NORMALIZE_ROWS: {
-        __nl_assert(__nlCurrentContext->state != __NL_STATE_ROW);
-        __nlCurrentContext->normalize_rows = NL_FALSE;
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    }
-    }
+       switch(pname) {
+       default: {
+               __nl_assert_not_reached;
+       }
+       }
 }
 
 NLboolean nlIsEnabled(NLenum pname) {
-    switch(pname) {
-    case NL_NORMALIZE_ROWS: {
-        return __nlCurrentContext->normalize_rows;
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    }
-    }
-    return NL_FALSE;
+       switch(pname) {
+       default: {
+               __nl_assert_not_reached;
+       }
+       }
+       return NL_FALSE;
 }
 
 /************************************************************************************/
 /* Get/Set Lock/Unlock variables */
 
 void nlSetVariable(NLuint index, NLfloat value) {
-    __nlCheckState(__NL_STATE_SYSTEM);
-    __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
-    __nlCurrentContext->variable[index].value = value;    
+       __nlCheckState(__NL_STATE_SYSTEM);
+       __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
+       __nlCurrentContext->variable[index].value = value;      
 }
 
 NLfloat nlGetVariable(NLuint index) {
-    __nl_assert(__nlCurrentContext->state != __NL_STATE_INITIAL);
-    __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
-    return __nlCurrentContext->variable[index].value;
+       __nl_assert(__nlCurrentContext->state != __NL_STATE_INITIAL);
+       __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
+       return __nlCurrentContext->variable[index].value;
 }
 
 void nlLockVariable(NLuint index) {
-    __nlCheckState(__NL_STATE_SYSTEM);
-    __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
-    __nlCurrentContext->variable[index].locked = NL_TRUE;
+       __nlCheckState(__NL_STATE_SYSTEM);
+       __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
+       __nlCurrentContext->variable[index].locked = NL_TRUE;
 }
 
 void nlUnlockVariable(NLuint index) {
-    __nlCheckState(__NL_STATE_SYSTEM);
-    __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
-    __nlCurrentContext->variable[index].locked = NL_FALSE;
+       __nlCheckState(__NL_STATE_SYSTEM);
+       __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
+       __nlCurrentContext->variable[index].locked = NL_FALSE;
 }
 
 NLboolean nlVariableIsLocked(NLuint index) {
-    __nl_assert(__nlCurrentContext->state != __NL_STATE_INITIAL);
-    __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
-    return __nlCurrentContext->variable[index].locked;
+       __nl_assert(__nlCurrentContext->state != __NL_STATE_INITIAL);
+       __nl_parano_range_assert(index, 0, __nlCurrentContext->nb_variables - 1);
+       return __nlCurrentContext->variable[index].locked;
 }
 
 /************************************************************************************/
 /* System construction */
 
 static void __nlVariablesToVector() {
-    NLuint i;
-    __nl_assert(__nlCurrentContext->alloc_x);
-    __nl_assert(__nlCurrentContext->alloc_variable);
-    for(i=0; i<__nlCurrentContext->nb_variables; i++) {
-        __NLVariable* v = &(__nlCurrentContext->variable[i]);
-        if(!v->locked) {
-            __nl_assert(v->index < __nlCurrentContext->n);
-            __nlCurrentContext->x[v->index] = v->value;
-        }
-    }
+       NLuint i;
+       __nl_assert(__nlCurrentContext->alloc_x);
+       __nl_assert(__nlCurrentContext->alloc_variable);
+       for(i=0; i<__nlCurrentContext->nb_variables; i++) {
+               __NLVariable* v = &(__nlCurrentContext->variable[i]);
+               if(!v->locked) {
+                       __nl_assert(v->index < __nlCurrentContext->n);
+                       __nlCurrentContext->x[v->index] = v->value;
+               }
+       }
 }
 
 static void __nlVectorToVariables() {
-    NLuint i;
-    __nl_assert(__nlCurrentContext->alloc_x);
-    __nl_assert(__nlCurrentContext->alloc_variable);
-    for(i=0; i<__nlCurrentContext->nb_variables; i++) {
-        __NLVariable* v = &(__nlCurrentContext->variable[i]);
-        if(!v->locked) {
-            __nl_assert(v->index < __nlCurrentContext->n);
-            v->value = __nlCurrentContext->x[v->index];
-        }
-    }
+       NLuint i;
+       __nl_assert(__nlCurrentContext->alloc_x);
+       __nl_assert(__nlCurrentContext->alloc_variable);
+       for(i=0; i<__nlCurrentContext->nb_variables; i++) {
+               __NLVariable* v = &(__nlCurrentContext->variable[i]);
+               if(!v->locked) {
+                       __nl_assert(v->index < __nlCurrentContext->n);
+                       v->value = __nlCurrentContext->x[v->index];
+               }
+       }
 }
 
-
 static void __nlBeginSystem() {
-    __nlTransition(__NL_STATE_INITIAL, __NL_STATE_SYSTEM);
-    __nl_assert(__nlCurrentContext->nb_variables > 0);
-    __nlCurrentContext->variable = __NL_NEW_ARRAY(
-        __NLVariable, __nlCurrentContext->nb_variables
-    );
-    __nlCurrentContext->alloc_variable = NL_TRUE;
+       __nl_assert(__nlCurrentContext->nb_variables > 0);
+
+       if (__nlCurrentContext->solve_again)
+               __nlTransition(__NL_STATE_SYSTEM_SOLVED, __NL_STATE_SYSTEM);
+       else {
+               __nlTransition(__NL_STATE_INITIAL, __NL_STATE_SYSTEM);
+
+               __nlCurrentContext->variable = __NL_NEW_ARRAY(
+                       __NLVariable, __nlCurrentContext->nb_variables
+               );
+               __nlCurrentContext->alloc_variable = NL_TRUE;
+       }
 }
 
 static void __nlEndSystem() {
-    __nlTransition(__NL_STATE_MATRIX_CONSTRUCTED, __NL_STATE_SYSTEM_CONSTRUCTED);    
+       __nlTransition(__NL_STATE_MATRIX_CONSTRUCTED, __NL_STATE_SYSTEM_CONSTRUCTED);   
 }
 
 static void __nlBeginMatrix() {
-    NLuint i;
-    NLuint n = 0;
-    NLenum storage = __NL_ROWS;
-
-    __nlTransition(__NL_STATE_SYSTEM, __NL_STATE_MATRIX);
-
-    for(i=0; i<__nlCurrentContext->nb_variables; i++) {
-        if(!__nlCurrentContext->variable[i].locked) {
-            __nlCurrentContext->variable[i].index = n;
-            n++;
-        } else {
-            __nlCurrentContext->variable[i].index = ~0;
-        }
-    }
-
-    __nlCurrentContext->n = n;
-
-    /* a least squares problem results in a symmetric matrix */
-    if(__nlCurrentContext->least_squares) {
-        __nlCurrentContext->symmetric = NL_TRUE;
-    }
-
-    if(__nlCurrentContext->symmetric) {
-        storage = (storage | __NL_SYMMETRIC);
-    }
-
-    /* SuperLU storage does not support symmetric storage */
-    storage = (storage & ~__NL_SYMMETRIC);
-
-    __nlSparseMatrixConstruct(&__nlCurrentContext->M, n, n, storage);
-    __nlCurrentContext->alloc_M = NL_TRUE;
-
-    __nlCurrentContext->x = __NL_NEW_ARRAY(NLfloat, n);
-    __nlCurrentContext->alloc_x = NL_TRUE;
-    
-    __nlCurrentContext->b = __NL_NEW_ARRAY(NLfloat, n);
-    __nlCurrentContext->alloc_b = NL_TRUE;
-
-    __nlVariablesToVector();
-
-    __nlRowColumnConstruct(&__nlCurrentContext->af);
-    __nlCurrentContext->alloc_af = NL_TRUE;
-    __nlRowColumnConstruct(&__nlCurrentContext->al);
-    __nlCurrentContext->alloc_al = NL_TRUE;
-    __nlRowColumnConstruct(&__nlCurrentContext->xl);
-    __nlCurrentContext->alloc_xl = NL_TRUE;
-
-    __nlCurrentContext->current_row = 0;
+       NLuint i;
+       NLuint n = 0;
+       NLenum storage = __NL_ROWS;
+
+       __nlTransition(__NL_STATE_SYSTEM, __NL_STATE_MATRIX);
+
+       if (!__nlCurrentContext->solve_again) {
+               for(i=0; i<__nlCurrentContext->nb_variables; i++) {
+                       if(!__nlCurrentContext->variable[i].locked)
+                               __nlCurrentContext->variable[i].index = n++;
+                       else
+                               __nlCurrentContext->variable[i].index = ~0;
+               }
+
+               __nlCurrentContext->n = n;
+
+               /* a least squares problem results in a symmetric matrix */
+               if(__nlCurrentContext->least_squares)
+                       __nlCurrentContext->symmetric = NL_TRUE;
+
+               if(__nlCurrentContext->symmetric)
+                       storage = (storage | __NL_SYMMETRIC);
+
+               /* SuperLU storage does not support symmetric storage */
+               storage = (storage & ~__NL_SYMMETRIC);
+
+               __nlSparseMatrixConstruct(&__nlCurrentContext->M, n, n, storage);
+               __nlCurrentContext->alloc_M = NL_TRUE;
+
+               __nlCurrentContext->x = __NL_NEW_ARRAY(NLfloat, n);
+               __nlCurrentContext->alloc_x = NL_TRUE;
+               
+               __nlCurrentContext->b = __NL_NEW_ARRAY(NLfloat, n);
+               __nlCurrentContext->alloc_b = NL_TRUE;
+       }
+       else {
+               /* need to recompute b only, A is not constructed anymore */
+               __NL_CLEAR_ARRAY(NLfloat, __nlCurrentContext->b, __nlCurrentContext->n);
+       }
+
+       __nlVariablesToVector();
+
+       __nlRowColumnConstruct(&__nlCurrentContext->af);
+       __nlCurrentContext->alloc_af = NL_TRUE;
+       __nlRowColumnConstruct(&__nlCurrentContext->al);
+       __nlCurrentContext->alloc_al = NL_TRUE;
+
+       __nlCurrentContext->current_row = 0;
 }
 
 static void __nlEndMatrix() {
-    __nlTransition(__NL_STATE_MATRIX, __NL_STATE_MATRIX_CONSTRUCTED);    
-    
-    __nlRowColumnDestroy(&__nlCurrentContext->af);
-    __nlCurrentContext->alloc_af = NL_FALSE;
-    __nlRowColumnDestroy(&__nlCurrentContext->al);
-    __nlCurrentContext->alloc_al = NL_FALSE;
-    __nlRowColumnDestroy(&__nlCurrentContext->xl);
-    __nlCurrentContext->alloc_al = NL_FALSE;
-    
+       __nlTransition(__NL_STATE_MATRIX, __NL_STATE_MATRIX_CONSTRUCTED);       
+       
+       __nlRowColumnDestroy(&__nlCurrentContext->af);
+       __nlCurrentContext->alloc_af = NL_FALSE;
+       __nlRowColumnDestroy(&__nlCurrentContext->al);
+       __nlCurrentContext->alloc_al = NL_FALSE;
+       
 #if 0
-    if(!__nlCurrentContext->least_squares) {
-        __nl_assert(
-            __nlCurrentContext->current_row == 
-            __nlCurrentContext->n
-        );
-    }
+       if(!__nlCurrentContext->least_squares) {
+               __nl_assert(
+                       __nlCurrentContext->current_row == 
+                       __nlCurrentContext->n
+               );
+       }
 #endif
 }
 
 static void __nlBeginRow() {
-    __nlTransition(__NL_STATE_MATRIX, __NL_STATE_ROW);
-    __nlRowColumnZero(&__nlCurrentContext->af);
-    __nlRowColumnZero(&__nlCurrentContext->al);
-    __nlRowColumnZero(&__nlCurrentContext->xl);
-}
-
-static void __nlScaleRow(NLfloat s) {
-    __NLRowColumn*    af = &__nlCurrentContext->af;
-    __NLRowColumn*    al = &__nlCurrentContext->al;
-    NLuint nf            = af->size;
-    NLuint nl            = al->size;
-    NLuint i;
-    for(i=0; i<nf; i++) {
-        af->coeff[i].value *= s;
-    }
-    for(i=0; i<nl; i++) {
-        al->coeff[i].value *= s;
-    }
-    __nlCurrentContext->right_hand_side *= s;
-}
-
-static void __nlNormalizeRow(NLfloat weight) {
-    __NLRowColumn*    af = &__nlCurrentContext->af;
-    __NLRowColumn*    al = &__nlCurrentContext->al;
-    NLuint nf            = af->size;
-    NLuint nl            = al->size;
-    NLuint i;
-    NLfloat norm = 0.0;
-    for(i=0; i<nf; i++) {
-        norm += af->coeff[i].value * af->coeff[i].value;
-    }
-    for(i=0; i<nl; i++) {
-        norm += al->coeff[i].value * al->coeff[i].value;
-    }
-    norm = sqrt(norm);
-    __nlScaleRow(weight / norm);
+       __nlTransition(__NL_STATE_MATRIX, __NL_STATE_ROW);
+       __nlRowColumnZero(&__nlCurrentContext->af);
+       __nlRowColumnZero(&__nlCurrentContext->al);
 }
 
 static void __nlEndRow() {
-    __NLRowColumn*    af = &__nlCurrentContext->af;
-    __NLRowColumn*    al = &__nlCurrentContext->al;
-    __NLRowColumn*    xl = &__nlCurrentContext->xl;
-    __NLSparseMatrix* M  = &__nlCurrentContext->M;
-    NLfloat* b        = __nlCurrentContext->b;
-    NLuint nf          = af->size;
-    NLuint nl          = al->size;
-    NLuint current_row = __nlCurrentContext->current_row;
-    NLuint i;
-    NLuint j;
-    NLfloat S;
-    __nlTransition(__NL_STATE_ROW, __NL_STATE_MATRIX);
-
-    if(__nlCurrentContext->normalize_rows) {
-        __nlNormalizeRow(__nlCurrentContext->row_scaling);
-    } else {
-        __nlScaleRow(__nlCurrentContext->row_scaling);
-    }
-
-    if(__nlCurrentContext->least_squares) {
-        for(i=0; i<nf; i++) {
-            for(j=0; j<nf; j++) {
-                __nlSparseMatrixAdd(
-                    M, af->coeff[i].index, af->coeff[j].index,
-                    af->coeff[i].value * af->coeff[j].value
-                );
-            }
-        }
-        S = -__nlCurrentContext->right_hand_side;
-        for(j=0; j<nl; j++) {
-            S += al->coeff[j].value * xl->coeff[j].value;
-        }
-        for(i=0; i<nf; i++) {
-            b[ af->coeff[i].index ] -= af->coeff[i].value * S;
-        }
-    } else {
-        for(i=0; i<nf; i++) {
-            __nlSparseMatrixAdd(
-                M, current_row, af->coeff[i].index, af->coeff[i].value
-            );
-        }
-        b[current_row] = -__nlCurrentContext->right_hand_side;
-        for(i=0; i<nl; i++) {
-            b[current_row] -= al->coeff[i].value * xl->coeff[i].value;
-        }
-    }
-    __nlCurrentContext->current_row++;
-    __nlCurrentContext->right_hand_side = 0.0;    
-    __nlCurrentContext->row_scaling     = 1.0;
+       __NLRowColumn*  af = &__nlCurrentContext->af;
+       __NLRowColumn*  al = &__nlCurrentContext->al;
+       __NLSparseMatrix* M  = &__nlCurrentContext->M;
+       NLfloat* b              = __nlCurrentContext->b;
+       NLuint nf                 = af->size;
+       NLuint nl                 = al->size;
+       NLuint current_row = __nlCurrentContext->current_row;
+       NLuint i;
+       NLuint j;
+       NLfloat S;
+       __nlTransition(__NL_STATE_ROW, __NL_STATE_MATRIX);
+
+       if(__nlCurrentContext->least_squares) {
+               if (!__nlCurrentContext->solve_again) {
+                       for(i=0; i<nf; i++) {
+                               for(j=0; j<nf; j++) {
+                                       __nlSparseMatrixAdd(
+                                               M, af->coeff[i].index, af->coeff[j].index,
+                                               af->coeff[i].value * af->coeff[j].value
+                                       );
+                               }
+                       }
+               }
+
+               S = -__nlCurrentContext->right_hand_side;
+               for(j=0; j<nl; j++)
+                       S += al->coeff[j].value;
+
+               for(i=0; i<nf; i++)
+                       b[ af->coeff[i].index ] -= af->coeff[i].value * S;
+       } else {
+               if (!__nlCurrentContext->solve_again) {
+                       for(i=0; i<nf; i++) {
+                               __nlSparseMatrixAdd(
+                                       M, current_row, af->coeff[i].index, af->coeff[i].value
+                               );
+                       }
+               }
+               b[current_row] = -__nlCurrentContext->right_hand_side;
+               for(i=0; i<nl; i++) {
+                       b[current_row] -= al->coeff[i].value;
+               }
+       }
+       __nlCurrentContext->current_row++;
+       __nlCurrentContext->right_hand_side = 0.0;      
 }
 
 void nlMatrixAdd(NLuint row, NLuint col, NLfloat value)
 {
-    __NLSparseMatrix* M  = &__nlCurrentContext->M;
-    __nlCheckState(__NL_STATE_MATRIX);
-    __nl_range_assert(row, 0, __nlCurrentContext->n - 1);
-    __nl_range_assert(col, 0, __nlCurrentContext->nb_variables - 1);
+       __NLSparseMatrix* M  = &__nlCurrentContext->M;
+       __nlCheckState(__NL_STATE_MATRIX);
+       __nl_range_assert(row, 0, __nlCurrentContext->n - 1);
+       __nl_range_assert(col, 0, __nlCurrentContext->nb_variables - 1);
        __nl_assert(!__nlCurrentContext->least_squares);
 
        __nlSparseMatrixAdd(M, row, col, value);
@@ -952,226 +906,264 @@ void nlMatrixAdd(NLuint row, NLuint col, NLfloat value)
 
 void nlRightHandSideAdd(NLuint index, NLfloat value)
 {
-    NLfloat* b = __nlCurrentContext->b;
+       NLfloat* b = __nlCurrentContext->b;
 
-    __nlCheckState(__NL_STATE_MATRIX);
-    __nl_range_assert(index, 0, __nlCurrentContext->n - 1);
+       __nlCheckState(__NL_STATE_MATRIX);
+       __nl_range_assert(index, 0, __nlCurrentContext->n - 1);
        __nl_assert(!__nlCurrentContext->least_squares);
 
        b[index] += value;
 }
 
 void nlCoefficient(NLuint index, NLfloat value) {
-    __NLVariable* v;
+       __NLVariable* v;
        unsigned int zero= 0;
-    __nlCheckState(__NL_STATE_ROW);
-    __nl_range_assert(index, zero, __nlCurrentContext->nb_variables - 1);
-    v = &(__nlCurrentContext->variable[index]);
-    if(v->locked) {
-        __nlRowColumnAppend(&(__nlCurrentContext->al), 0, value);
-        __nlRowColumnAppend(&(__nlCurrentContext->xl), 0, v->value);
-    } else {
-        __nlRowColumnAppend(&(__nlCurrentContext->af), v->index, value);
-    }
+       __nlCheckState(__NL_STATE_ROW);
+       __nl_range_assert(index, zero, __nlCurrentContext->nb_variables - 1);
+       v = &(__nlCurrentContext->variable[index]);
+       if(v->locked)
+               __nlRowColumnAppend(&(__nlCurrentContext->al), 0, value*v->value);
+       else
+               __nlRowColumnAppend(&(__nlCurrentContext->af), v->index, value);
 }
 
 void nlBegin(NLenum prim) {
-    switch(prim) {
-    case NL_SYSTEM: {
-        __nlBeginSystem();
-    } break;
-    case NL_MATRIX: {
-        __nlBeginMatrix();
-    } break;
-    case NL_ROW: {
-        __nlBeginRow();
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    }
-    }
+       switch(prim) {
+       case NL_SYSTEM: {
+               __nlBeginSystem();
+       } break;
+       case NL_MATRIX: {
+               __nlBeginMatrix();
+       } break;
+       case NL_ROW: {
+               __nlBeginRow();
+       } break;
+       default: {
+               __nl_assert_not_reached;
+       }
+       }
 }
 
 void nlEnd(NLenum prim) {
-    switch(prim) {
-    case NL_SYSTEM: {
-        __nlEndSystem();
-    } break;
-    case NL_MATRIX: {
-        __nlEndMatrix();
-    } break;
-    case NL_ROW: {
-        __nlEndRow();
-    } break;
-    default: {
-        __nl_assert_not_reached;
-    }
-    }
+       switch(prim) {
+       case NL_SYSTEM: {
+               __nlEndSystem();
+       } break;
+       case NL_MATRIX: {
+               __nlEndMatrix();
+       } break;
+       case NL_ROW: {
+               __nlEndRow();
+       } break;
+       default: {
+               __nl_assert_not_reached;
+       }
+       }
 }
 
 /************************************************************************/
 /* SuperLU wrapper */
 
-/* Note: SuperLU is difficult to call, but it is worth it.    */
+/* Note: SuperLU is difficult to call, but it is worth it.     */
 /* Here is a driver inspired by A. Sheffer's "cow flattener". */
-static NLboolean __nlSolve_SUPERLU( NLboolean do_perm) {
-
-    /* OpenNL Context */
-    __NLSparseMatrix* M  = &(__nlCurrentContext->M);
-    NLfloat* b          = __nlCurrentContext->b;
-    NLfloat* x          = __nlCurrentContext->x;
-
-    /* Compressed Row Storage matrix representation */
-    NLuint    n      = __nlCurrentContext->n;
-    NLuint    nnz    = __nlSparseMatrixNNZ(M); /* Number of Non-Zero coeffs */
-    NLint*    xa     = __NL_NEW_ARRAY(NLint, n+1);
-    NLfloat* rhs    = __NL_NEW_ARRAY(NLfloat, n);
-    NLfloat* a      = __NL_NEW_ARRAY(NLfloat, nnz);
-    NLint*    asub   = __NL_NEW_ARRAY(NLint, nnz);
-
-    /* Permutation vector */
-    NLint*    perm_r  = __NL_NEW_ARRAY(NLint, n);
-    NLint*    perm    = __NL_NEW_ARRAY(NLint, n);
-
-    /* SuperLU variables */
-    SuperMatrix A, B; /* System       */
-    SuperMatrix L, U; /* Inverse of A */
-    NLint info;       /* status code  */
-    DNformat *vals = NULL; /* access to result */
-    float *rvals  = NULL; /* access to result */
-
-    /* SuperLU options and stats */
-    superlu_options_t options;
-    SuperLUStat_t     stat;
-
-
-    /* Temporary variables */
-    __NLRowColumn* Ri = NULL;
-    NLuint         i,jj,count;
-    
-    __nl_assert(!(M->storage & __NL_SYMMETRIC));
-    __nl_assert(M->storage & __NL_ROWS);
-    __nl_assert(M->m == M->n);
-    
-    
-    /*
-     * Step 1: convert matrix M into SuperLU compressed column 
-     *   representation.
-     * -------------------------------------------------------
-     */
-
-    count = 0;
-    for(i=0; i<n; i++) {
-        Ri = &(M->row[i]);
-        xa[i] = count;
-        for(jj=0; jj<Ri->size; jj++) {
-            a[count]    = Ri->coeff[jj].value;
-            asub[count] = Ri->coeff[jj].index;
-            count++;
-        }
-    }
-    xa[n] = nnz;
-
-    /* Save memory for SuperLU */
-    __nlSparseMatrixClear(M);
-
-
-    /*
-     * Rem: symmetric storage does not seem to work with
-     * SuperLU ... (->deactivated in main SLS::Solver driver)
-     */
-    sCreate_CompCol_Matrix(
-        &A, n, n, nnz, a, asub, xa, 
-        SLU_NR,              /* Row_wise, no supernode */
-        SLU_S,               /* floats                */ 
-        SLU_GE               /* general storage        */
-    );
-
-    /* Step 2: create vector */
-    sCreate_Dense_Matrix(
-        &B, n, 1, b, n, 
-        SLU_DN, /* Fortran-type column-wise storage */
-        SLU_S,  /* floats                          */
-        SLU_GE  /* general                          */
-    );
-            
-
-    /* Step 3: get permutation matrix 
-     * ------------------------------
-     * com_perm: 0 -> no re-ordering
-     *           1 -> re-ordering for A^t.A
-     *           2 -> re-ordering for A^t+A
-     *           3 -> approximate minimum degree ordering
-     */
-    get_perm_c(do_perm ? 3 : 0, &A, perm);
-
-    /* Step 4: call SuperLU main routine
-     * ---------------------------------
-     */
-
-    set_default_options(&options);
-    options.ColPerm = MY_PERMC;
-    StatInit(&stat);
-
-    sgssv(&options, &A, perm, perm_r, &L, &U, &B, &stat, &info);
-
-    /* Step 5: get the solution
-     * ------------------------
-     * Fortran-type column-wise storage
-     */
-    vals = (DNformat*)B.Store;
-    rvals = (float*)(vals->nzval);
-    if(info == 0) {
-        for(i = 0; i <  n; i++){
-            x[i] = rvals[i];
-        }
-    }
-
-    /* Step 6: cleanup
-     * ---------------
-     */
-
-    /*
-     *  For these two ones, only the "store" structure
-     * needs to be deallocated (the arrays have been allocated
-     * by us).
-     */
-    Destroy_SuperMatrix_Store(&A);
-    Destroy_SuperMatrix_Store(&B);
-
-    
-    /*
-     *   These ones need to be fully deallocated (they have been
-     * allocated by SuperLU).
-     */
-    Destroy_SuperNode_Matrix(&L);
-    Destroy_CompCol_Matrix(&U);
-
-    StatFree(&stat);
-
-    __NL_DELETE_ARRAY(xa);
-    __NL_DELETE_ARRAY(rhs);
-    __NL_DELETE_ARRAY(a);
-    __NL_DELETE_ARRAY(asub);
-    __NL_DELETE_ARRAY(perm_r);
-    __NL_DELETE_ARRAY(perm);
-
-    return (info == 0);
+static NLboolean __nlFactorize_SUPERLU(__NLContext *context, NLint *permutation) {
+
+       /* OpenNL Context */
+       __NLSparseMatrix* M = &(context->M);
+       NLuint n = context->n;
+       NLuint nnz = __nlSparseMatrixNNZ(M); /* number of non-zero coeffs */
+
+       /* Compressed Row Storage matrix representation */
+       NLint   *xa             = __NL_NEW_ARRAY(NLint, n+1);
+       NLfloat *rhs    = __NL_NEW_ARRAY(NLfloat, n);
+       NLfloat *a              = __NL_NEW_ARRAY(NLfloat, nnz);
+       NLint   *asub   = __NL_NEW_ARRAY(NLint, nnz);
+       NLint   *etree  = __NL_NEW_ARRAY(NLint, n);
+
+       /* SuperLU variables */
+       SuperMatrix At, AtP;
+       NLint info, panel_size, relax;
+       superlu_options_t options;
+
+       /* Temporary variables */
+       __NLRowColumn* Ri = NULL;
+       NLuint i, jj, count;
+       
+       __nl_assert(!(M->storage & __NL_SYMMETRIC));
+       __nl_assert(M->storage & __NL_ROWS);
+       __nl_assert(M->m == M->n);
+       
+       /* Convert M to compressed column format */
+       for(i=0, count=0; i<n; i++) {
+               __NLRowColumn *Ri = M->row + i;
+               xa[i] = count;
+
+               for(jj=0; jj<Ri->size; jj++, count++) {
+                       a[count] = Ri->coeff[jj].value;
+                       asub[count] = Ri->coeff[jj].index;
+               }
+       }
+       xa[n] = nnz;
+
+       /* Free M, don't need it anymore at this point */
+       __nlSparseMatrixClear(M);
+
+       /* Create superlu A matrix transposed */
+       sCreate_CompCol_Matrix(
+               &At, n, n, nnz, a, asub, xa, 
+               SLU_NC,         /* Colum wise, no supernode */
+               SLU_S,          /* floats */ 
+               SLU_GE          /* general storage */
+       );
+
+       /* Set superlu options */
+       set_default_options(&options);
+       options.ColPerm = MY_PERMC;
+       options.Fact = DOFACT;
+
+       StatInit(&(context->slu.stat));
+
+       panel_size = sp_ienv(1); /* sp_ienv give us the defaults */
+       relax = sp_ienv(2);
+
+       /* Compute permutation and permuted matrix */
+       context->slu.perm_r = __NL_NEW_ARRAY(NLint, n);
+       context->slu.perm_c = __NL_NEW_ARRAY(NLint, n);
+
+       if ((permutation == NULL) || (*permutation == -1)) {
+               get_perm_c(3, &At, context->slu.perm_c);
+
+               if (permutation)
+                       memcpy(permutation, context->slu.perm_c, sizeof(NLint)*n);
+       }
+       else
+               memcpy(context->slu.perm_c, permutation, sizeof(NLint)*n);
+
+       sp_preorder(&options, &At, context->slu.perm_c, etree, &AtP);
+
+       /* Decompose into L and U */
+       sgstrf(&options, &AtP, relax, panel_size,
+               etree, NULL, 0, context->slu.perm_c, context->slu.perm_r,
+               &(context->slu.L), &(context->slu.U), &(context->slu.stat), &info);
+
+       /* Cleanup */
+
+       Destroy_SuperMatrix_Store(&At);
+       Destroy_SuperMatrix_Store(&AtP);
+
+       __NL_DELETE_ARRAY(etree);
+       __NL_DELETE_ARRAY(xa);
+       __NL_DELETE_ARRAY(rhs);
+       __NL_DELETE_ARRAY(a);
+       __NL_DELETE_ARRAY(asub);
+
+       context->slu.alloc_slu = NL_TRUE;
+
+       return (info == 0);
+}
+
+static NLboolean __nlInvert_SUPERLU(__NLContext *context) {
+
+       /* OpenNL Context */
+       NLfloat* b = context->b;
+       NLfloat* x = context->x;
+       NLuint n = context->n;
+
+       /* SuperLU variables */
+       SuperMatrix B;
+       NLint info;
+
+       /* Create superlu array for B */
+       sCreate_Dense_Matrix(
+               &B, n, 1, b, n, 
+               SLU_DN, /* Fortran-type column-wise storage */
+               SLU_S,  /* floats                                                 */
+               SLU_GE  /* general                                                */
+       );
+
+       /* Forward/Back substitution to compute x */
+       sgstrs(TRANS, &(context->slu.L), &(context->slu.U),
+               context->slu.perm_c, context->slu.perm_r, &B,
+               &(context->slu.stat), &info);
+
+       if(info == 0)
+               memcpy(x, ((DNformat*)B.Store)->nzval, sizeof(*x)*n);
+
+       Destroy_SuperMatrix_Store(&B);
+
+       return (info == 0);
+}
+
+static void __nlFree_SUPERLU(__NLContext *context) {
+
+       Destroy_SuperNode_Matrix(&(context->slu.L));
+       Destroy_CompCol_Matrix(&(context->slu.U));
+
+       StatFree(&(context->slu.stat));
+
+       __NL_DELETE_ARRAY(context->slu.perm_r);
+       __NL_DELETE_ARRAY(context->slu.perm_c);
+
+       context->slu.alloc_slu = NL_FALSE;
 }
 
+void nlPrintMatrix(void) {
+       __NLSparseMatrix* M  = &(__nlCurrentContext->M);
+       float *b = __nlCurrentContext->b;
+       NLuint i, jj, k;
+       NLuint n = __nlCurrentContext->n;
+       __NLRowColumn* Ri = NULL;
+       float *value = malloc(sizeof(*value)*n);
+
+       printf("A:\n");
+       for(i=0; i<n; i++) {
+               Ri = &(M->row[i]);
+
+               memset(value, 0.0, sizeof(*value)*n);
+               for(jj=0; jj<Ri->size; jj++)
+                       value[Ri->coeff[jj].index] = Ri->coeff[jj].value;
+
+               for (k = 0; k<n; k++)
+                       printf("%.3f ", value[k]);
+               printf("\n");
+       }
+
+       printf("b:\n");
+       for(i=0; i<n; i++)
+               printf("%f ", b[i]);
+       printf("\n");
+
+       free(value);
+}
 
 /************************************************************************/
 /* nlSolve() driver routine */
 
-NLboolean nlSolve(void) {
-    NLboolean result = NL_TRUE;
+NLboolean nlSolveAdvanced(NLint *permutation, NLboolean solveAgain) {
+       NLboolean result = NL_TRUE;
+
+       __nlCheckState(__NL_STATE_SYSTEM_CONSTRUCTED);
+
+       if (!__nlCurrentContext->solve_again)
+               result = __nlFactorize_SUPERLU(__nlCurrentContext, permutation);
+
+       if (result) {
+               result = __nlInvert_SUPERLU(__nlCurrentContext);
 
-    __nlCheckState(__NL_STATE_SYSTEM_CONSTRUCTED);
-    result = __nlSolve_SUPERLU(NL_TRUE);
+               if (result) {
+                       __nlVectorToVariables();
 
-    __nlVectorToVariables();
-    __nlTransition(__NL_STATE_SYSTEM_CONSTRUCTED, __NL_STATE_SOLVED);
+                       if (solveAgain)
+                               __nlCurrentContext->solve_again = NL_TRUE;
+
+                       __nlTransition(__NL_STATE_SYSTEM_CONSTRUCTED, __NL_STATE_SYSTEM_SOLVED);
+               }
+       }
+
+       return result;
+}
 
-    return result;
+NLboolean nlSolve() {
+       return nlSolveAdvanced(NULL, NL_FALSE);
 }
 
index b6134b5d805db97204934854e205b9ce46003f15..ef99a25239c64eb39f645d60edc8b9ac9b6fd33c 100644 (file)
@@ -70,7 +70,7 @@ LIB32=link.exe -lib
 MTL=midl.exe
 LINK32=link.exe -lib
 # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
-# ADD CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /I "..\..\..\source\blender\imbuf\intern" /I "..\..\..\source\blender\quicktime" /I "..\..\..\source\blender\blenloader" /I "..\..\..\source\blender\render\extern\include" /I "..\..\..\..\lib\windows\guardedalloc\include" /I "..\..\..\source\blender\avi" /I "..\..\..\source\blender\imbuf" /I "..\..\..\source\blender\blenkernel" /I "..\..\..\source\blender\blenlib" /I "..\..\..\source\blender\include" /I "..\..\..\..\lib\windows\jpeg\include" /I "..\..\..\..\lib\windows\zlib\include" /I "..\..\..\..\lib\windows\png\include" /I "..\..\..\source\blender\makesdna" /I "..\..\..\..\lib\windows\tiff\include" /D "_DEBUG" /D "WIN32" /D "_MBCS" /D "_LIB" /D "WITH_QUICKTIME" /YX /FD /I /GZ "..\..\..\source\blender\imbuf" /c
+# ADD CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /I "..\..\..\source\blender\imbuf\intern" /I "..\..\..\source\blender\quicktime" /I "..\..\..\source\blender\blenloader" /I "..\..\..\source\blender\render\extern\include" /I "..\..\..\..\lib\windows\guardedalloc\include" /I "..\..\..\source\blender\avi" /I "..\..\..\source\blender\imbuf" /I "..\..\..\source\blender\blenkernel" /I "..\..\..\source\blender\blenlib" /I "..\..\..\source\blender\include" /I "..\..\..\..\lib\windows\jpeg\include" /I "..\..\..\..\lib\windows\zlib\include" /I "..\..\..\..\lib\windows\png\include" /I "..\..\..\source\blender\makesdna..\..\..\lib\windows\\" /I "..\..\..\..\lib\windows\tiff\include" /D "_DEBUG" /D "WIN32" /D "_MBCS" /D "_LIB" /D "WITH_QUICKTIME" /YX /FD /I /GZ "..\..\..\source\blender\imbuf" /c
 # ADD BASE RSC /l 0x409 /d "_DEBUG"
 # ADD RSC /l 0x409 /d "_DEBUG"
 BSC32=bscmake.exe
index e8a8580bb590551d6e77f5f12602ff786a4f220e..7da591109f5c53604035edb1ab2308a3012c3759 100644 (file)
@@ -63,7 +63,6 @@ ECHO Copying required 3rd party dlls...
 XCOPY /Y ..\..\..\lib\windows\python\lib\python24.dll ..\..\bin
 XCOPY /Y ..\..\..\lib\windows\gettext\lib\*.dll ..\..\bin
 XCOPY /Y ..\..\..\lib\windows\sdl\lib\*.dll ..\..\bin
-XCOPY /Y ..\..\..\lib\windows\tiff\lib\libtiff.dll ..\..\bin
 ECHO Copying language folder
 ECHO Done
 "/>
@@ -141,7 +140,6 @@ XCOPY /Y ..\..\..\lib\windows\gettext\lib\*.dll ..\..\bin\debug
 XCOPY /Y ..\..\..\lib\windows\sdl\lib\*.dll ..\..\bin\debug
 XCOPY /Y ..\..\..\lib\windows\python\lib\python24_d.dll ..\..\bin\debug
 XCOPY /Y ..\..\..\lib\windows\CRTL\lib\msvcrtd.dll ..\..\bin\debug
-XCOPY /Y ..\..\..\lib\windows\tiff\lib\libtiff.dll ..\..\bin\debug
 ECHO Copying language folder
 IF NOT EXIST ..\..\bin\debug\.blender MKDIR ..\..\bin\debug\.blender
 XCOPY /Y ..\..\bin\.blender ..\..\bin\debug\.blender /E
index 2ce865373dc3ba25f1adfbb80d4a150ce02523bc..c608b3044eae7fbefe09265b0e0a57d6fd5b1d68 100644 (file)
@@ -21,7 +21,7 @@
                        <Tool
                                Name="VCCLCompilerTool"
                                Optimization="0"
-                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\lib\windows\tiff\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
+                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
                                PreprocessorDefinitions="_DEBUG,WIN32,_LIB,WITH_QUICKTIME"
                                BasicRuntimeChecks="3"
                                RuntimeLibrary="1"
@@ -73,7 +73,7 @@
                        <Tool
                                Name="VCCLCompilerTool"
                                Optimization="0"
-                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\lib\windows\tiff\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
+                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
                                PreprocessorDefinitions="_DEBUG,WIN32,_LIB"
                                BasicRuntimeChecks="3"
                                RuntimeLibrary="3"
                        <Tool
                                Name="VCCLCompilerTool"
                                InlineFunctionExpansion="1"
-                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\lib\windows\tiff\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
+                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
                                PreprocessorDefinitions="NDEBUG,WIN32,_LIB,WITH_QUICKTIME"
                                StringPooling="TRUE"
                                RuntimeLibrary="2"
                        <Tool
                                Name="VCCLCompilerTool"
                                InlineFunctionExpansion="1"
-                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\lib\windows\tiff\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
+                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
                                PreprocessorDefinitions="NDEBUG,WIN32,_LIB,WITH_QUICKTIME"
                                StringPooling="TRUE"
                                RuntimeLibrary="0"
                        <Tool
                                Name="VCCLCompilerTool"
                                Optimization="0"
-                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\lib\windows\tiff\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
+                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
                                PreprocessorDefinitions="_DEBUG,WIN32,_LIB,WITH_QUICKTIME"
                                BasicRuntimeChecks="3"
                                RuntimeLibrary="1"
                        <Tool
                                Name="VCCLCompilerTool"
                                InlineFunctionExpansion="1"
-                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\lib\windows\tiff\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
+                               AdditionalIncludeDirectories="..\..\..\..\lib\windows\jpeg\include;..\..\..\..\lib\windows\zlib\include;..\..\..\..\lib\windows\png\include;..\..\..\..\lib\windows\QTDevWin\CIncludes;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\source\blender\avi;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\include;..\..\..\source\blender\quicktime;..\..\..\source\blender\blenkernel;..\..\..\source\blender\blenloader;..\..\..\source\blender\makesdna;..\..\..\source\blender\imbuf\intern;..\..\..\source\blender\readstreamglue;..\..\..\source\blender\render\extern\include"
                                PreprocessorDefinitions="NDEBUG,WIN32,_LIB,WITH_QUICKTIME"
                                StringPooling="TRUE"
                                RuntimeLibrary="0"
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\divers.c">
                        </File>
-                       <File
-                               RelativePath="..\..\..\source\blender\imbuf\intern\dynlibtiff.c">
-                       </File>
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\filter.c">
                        </File>
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\targa.c">
                        </File>
-                       <File
-                               RelativePath="..\..\..\source\blender\imbuf\intern\tiff.c">
-                       </File>
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\util.c">
                        </File>
                <Filter
                        Name="Header Files"
                        Filter="h;hpp;hxx;hm;inl">
-                       <File
-                               RelativePath="..\..\..\source\blender\imbuf\intern\dynlibtiff.h">
-                       </File>
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\IMB_allocimbuf.h">
                        </File>
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\IMB_targa.h">
                        </File>
-                       <File
-                               RelativePath="..\..\..\source\blender\imbuf\intern\IMB_tiff.h">
-                       </File>
                        <File
                                RelativePath="..\..\..\source\blender\imbuf\intern\imbuf.h">
                        </File>
index d9f7af1bdef6045366aa8fb8f393fc25c4ba6393..31a7f04dbb07b20f5c2fafdb5d6cdf1096dd51d9 100644 (file)
@@ -55,7 +55,14 @@ all:
       ifeq ($(CPU),alpha)
        @$(MAKE) pkg TYPE="" TAR="tar cf" EXT1=".tar" \
            COMPRESS="gzip -f --best" EXT2=".gz"
-      else
+      endif
+      ifeq ($(CPU),i386)
+       @$(MAKE) pkg TYPE="" TAR="tar cf" EXT1=".tar" \
+           COMPRESS="gzip -f --best" EXT2=".gz"
+       @$(MAKE) pkg TYPE="-static" TAR="tar cf" EXT1=".tar" \
+           COMPRESS="gzip -f --best" EXT2=".gz"
+      endif
+      ifeq ($(CPU),powerpc)
        @$(MAKE) pkg TYPE="" TAR="tar cf" EXT1=".tar" \
            COMPRESS="gzip -f --best" EXT2=".gz"
        @$(MAKE) pkg TYPE="-static" TAR="tar cf" EXT1=".tar" \
diff --git a/release/scripts/3ds_export.py b/release/scripts/3ds_export.py
deleted file mode 100644 (file)
index ebe06c3..0000000
+++ /dev/null
@@ -1,673 +0,0 @@
-#!BPY
-
-""" 
-Name: '3D Studio (.3ds)...'
-Blender: 237
-Group: 'Export'
-Tooltip: 'Export to 3DS file format (.3ds).'
-"""
-
-__author__ = ["Campbell Barton", "Bob Holcomb", "Richard Lärkäng", "Damien McGinnes"]
-__url__ = ("blender", "elysiun", "http://www.gametutorials.com")
-__version__ = "0.82"
-__bpydoc__ = """\
-
-3ds Exporter
-
-This script Exports a 3ds file and the materials into blender for editing.
-
-Exporting is based on 3ds loader from www.gametutorials.com(Thanks DigiBen).
-"""
-
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# Script copyright (C) Bob Holcomb 
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-# --------------------------------------------------------------------------
-
-
-######################################################
-# Importing modules
-######################################################
-
-import Blender
-from Blender import NMesh, Scene, Object, Material
-import struct
-
-
-######################################################
-# Data Structures
-######################################################
-
-#Some of the chunks that we will export
-#----- Primary Chunk, at the beginning of each file
-PRIMARY= long("0x4D4D",16)
-
-#------ Main Chunks
-OBJECTINFO   =      long("0x3D3D",16);      #This gives the version of the mesh and is found right before the material and object information
-VERSION      =      long("0x0002",16);      #This gives the version of the .3ds file
-EDITKEYFRAME=      long("0xB000",16);      #This is the header for all of the key frame info
-
-#------ sub defines of OBJECTINFO
-MATERIAL=45055         #0xAFFF                         // This stored the texture info
-OBJECT=16384           #0x4000                         // This stores the faces, vertices, etc...
-
-#>------ sub defines of MATERIAL
-MATNAME    =      long("0xA000",16);      # This holds the material name
-MATAMBIENT   =      long("0xA010",16);      # Ambient color of the object/material
-MATDIFFUSE   =      long("0xA020",16);      # This holds the color of the object/material
-MATSPECULAR   =      long("0xA030",16);      # SPecular color of the object/material
-MATSHINESS   =      long("0xA040",16);      # ??
-MATMAP       =      long("0xA200",16);      # This is a header for a new material
-MATMAPFILE    =      long("0xA300",16);      # This holds the file name of the texture
-
-RGB1=  long("0x0011",16)
-RGB2=  long("0x0012",16)
-
-#>------ sub defines of OBJECT
-OBJECT_MESH  =      long("0x4100",16);      # This lets us know that we are reading a new object
-OBJECT_LIGHT =      long("0x4600",16);      # This lets un know we are reading a light object
-OBJECT_CAMERA=      long("0x4700",16);      # This lets un know we are reading a camera object
-
-#>------ sub defines of CAMERA
-OBJECT_CAM_RANGES=   long("0x4720",16);      # The camera range values
-
-#>------ sub defines of OBJECT_MESH
-OBJECT_VERTICES =   long("0x4110",16);      # The objects vertices
-OBJECT_FACES    =   long("0x4120",16);      # The objects faces
-OBJECT_MATERIAL =   long("0x4130",16);      # This is found if the object has a material, either texture map or color
-OBJECT_UV       =   long("0x4140",16);      # The UV texture coordinates
-OBJECT_TRANS_MATRIX  =   long("0x4160",16); # The Object Matrix
-
-#==============================================#
-# Strips the slashes from the back of a string #
-#==============================================#
-def stripPath(path):
-       return path.split('/')[-1].split('\\')[-1]
-
-#==================================================#
-# New name based on old with a different extension #
-#==================================================#
-def newFName(ext):
-       return Blender.Get('filename')[: -len(Blender.Get('filename').split('.', -1)[-1]) ] + ext
-
-
-#the chunk class
-class chunk:
-       ID=0
-       size=0
-
-       def __init__(self):
-               self.ID=0
-               self.size=0
-
-       def get_size(self):
-               self.size=6
-
-       def write(self, file):
-               #write header
-               data=struct.pack(\
-               "<HI",\
-               self.ID,\
-               self.size)
-               file.write(data)
-
-       def dump(self):
-               print "ID: ", self.ID
-               print "ID in hex: ", hex(self.ID)
-               print "size: ", self.size
-
-
-
-#may want to add light, camera, keyframe chunks.
-class vert_chunk(chunk):
-       verts=[]
-
-       def __init__(self):
-               self.verts=[]
-               self.ID=OBJECT_VERTICES
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=2 #for the number of verts short
-               temp_size += 12 * len(self.verts)  #3 floats x 4 bytes each
-               self.size+=temp_size
-               #~ print "vert_chunk size: ", self.size
-               return self.size
-       
-       def write(self, file):
-               chunk.write(self, file)
-               #write header
-               data=struct.pack("<H", len(self.verts))
-               file.write(data)
-               #write verts
-               for vert in self.verts:
-                       data=struct.pack("<3f",vert[0],vert[1], vert[2])
-                       file.write(data)
-
-class obj_material_chunk(chunk):
-       name=""
-       faces=[]
-
-       def __init__(self):
-               self.name=""
-               self.faces=[]
-               self.ID=OBJECT_MATERIAL
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=(len(self.name)+1)
-               temp_size+=2
-               for face in self.faces:
-                       temp_size+=2
-               self.size+=temp_size
-               #~ print "obj material chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write name
-               name_length=len(self.name)+1
-               binary_format="<"+str(name_length)+"s"
-               data=struct.pack(binary_format, self.name)
-               file.write(data)
-               binary_format="<H"
-               #~ print "Nr of faces: ", len(self.faces)
-               data=struct.pack(binary_format, len(self.faces))
-               file.write(data)
-               for face in self.faces:
-                       data=struct.pack(binary_format, face)
-                       file.write(data)
-
-class face_chunk(chunk):
-       faces=[]
-       num_faces=0
-       m_chunks=[]
-
-       def __init__(self):
-               self.faces=[]
-               self.ID=OBJECT_FACES
-               self.num_faces=0
-               self.m_chunks=[]
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size = 2 #num faces info
-               temp_size += 8 * len(self.faces)  #4 short ints x 2 bytes each
-               for m in self.m_chunks:
-                       temp_size+=m.get_size()
-               self.size += temp_size
-               #~ print "face_chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               data=struct.pack("<H", len(self.faces))
-               file.write(data)
-               #write faces
-               for face in self.faces:
-                       data=struct.pack("<4H", face[0],face[1], face[2], 0) # The last zero is only used by 3d studio
-                       file.write(data)
-               #write materials
-               for m in self.m_chunks:
-                       m.write(file)
-
-class uv_chunk(chunk):
-       uv=[]
-       num_uv=0
-
-       def __init__(self):
-               self.uv=[]
-               self.ID=OBJECT_UV
-               self.num_uv=0
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=2 #for num UV
-               for this_uv in self.uv:
-                       temp_size+=8  #2 floats at 4 bytes each
-               self.size+=temp_size
-               #~ print "uv chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               
-               #write header
-               data=struct.pack("<H", len(self.uv))
-               file.write(data)
-               
-               #write verts
-               for this_uv in self.uv:
-                       data=struct.pack("<2f", this_uv[0], this_uv[1])
-                       file.write(data)
-
-class mesh_chunk(chunk):
-       v_chunk=vert_chunk()
-       f_chunk=face_chunk()
-       uv_chunk=uv_chunk()
-
-       def __init__(self):
-               self.v_chunk=vert_chunk()
-               self.f_chunk=face_chunk()
-               self.uv_chunk=uv_chunk()
-               self.ID=OBJECT_MESH
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=self.v_chunk.get_size()
-               temp_size+=self.f_chunk.get_size()
-               temp_size+=self.uv_chunk.get_size()
-               self.size+=temp_size
-               #~ print "object mesh chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write stuff
-               self.v_chunk.write(file)
-               self.f_chunk.write(file)
-               self.uv_chunk.write(file)
-
-class object_chunk(chunk):
-       name=""
-       mesh_chunks=[]
-
-       def __init__(self):
-               self.name=""
-               self.mesh_chunks=[]
-               self.ID=OBJECT
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=len(self.name)+1 #+1 for null character
-               for mesh in self.mesh_chunks:
-                       temp_size+=mesh.get_size()
-               self.size+=temp_size
-               #~ print "object chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write name
-               
-               binary_format = "<%ds" % (len(self.name)+1)
-               data=struct.pack(binary_format, self.name)
-               file.write(data)
-               #write stuff
-               for mesh in self.mesh_chunks:
-                       mesh.write(file)
-
-class object_info_chunk(chunk):
-       obj_chunks=[]
-       mat_chunks=[]
-
-       def __init__(self):
-               self.obj_chunks=[]
-               self.mat_chunks=[]
-               self.ID=OBJECTINFO
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=0
-               for mat in self.mat_chunks:
-                       temp_size+=mat.get_size()
-               for obj in self.obj_chunks:
-                       temp_size+=obj.get_size()
-               self.size+=temp_size
-               #~ print "object info size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write all the materials
-               for mat in self.mat_chunks:
-                       mat.write(file)
-               #write all the objects
-               for obj in self.obj_chunks:
-                       obj.write(file)
-
-
-
-class version_chunk(chunk):
-       version=3
-
-       def __init__(self):
-               self.ID=VERSION
-               self.version=3 #that the document that I'm using
-
-       def get_size(self):
-               chunk.get_size(self)
-               self.size += 4 #bytes for the version info
-               #~ print "version chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write header and version
-               data=struct.pack("<I", self.version)
-               file.write(data)
-
-class rgb_chunk(chunk):
-       col=[]
-
-       def __init__(self):
-               self.col=[]
-
-       def get_size(self):
-               chunk.get_size(self)
-               self.size+=3 #color size
-               #~ print "rgb chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write colors
-               for c in self.col:
-                       file.write( struct.pack("<c", chr(int(255*c))) )
-
-
-class rgb1_chunk(rgb_chunk):
-
-       def __init__(self):
-               self.ID=RGB1
-
-class rgb2_chunk(rgb_chunk):
-
-       def __init__(self):
-               self.ID=RGB2
-
-class material_ambient_chunk(chunk):
-       col1=None
-       col2=None
-
-       def __init__(self):
-               self.ID=MATAMBIENT
-               self.col1=rgb1_chunk()
-               self.col2=rgb2_chunk()
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=self.col1.get_size()
-               temp_size+=self.col2.get_size()
-               self.size+=temp_size
-               #~ print "material ambient size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write colors
-               self.col1.write(file)
-               self.col2.write(file)
-
-class material_diffuse_chunk(chunk):
-       col1=None
-       col2=None
-
-       def __init__(self):
-               self.ID=MATDIFFUSE
-               self.col1=rgb1_chunk()
-               self.col2=rgb2_chunk()
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=self.col1.get_size()
-               temp_size+=self.col2.get_size()
-               self.size+=temp_size
-               #~ print "material diffuse size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write colors
-               self.col1.write(file)
-               self.col2.write(file)
-
-class material_specular_chunk(chunk):
-       col1=None
-       col2=None
-
-       def __init__(self):
-               self.ID=MATSPECULAR
-               self.col1=rgb1_chunk()
-               self.col2=rgb2_chunk()
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=self.col1.get_size()
-               temp_size+=self.col2.get_size()
-               self.size+=temp_size
-               #~ print "material specular size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write colors
-               self.col1.write(file)
-               self.col2.write(file)
-
-class material_name_chunk(chunk):
-       name=""
-
-       def __init__(self):
-               self.ID=MATNAME
-               self.name=""
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=(len(self.name)+1)
-               self.size+=temp_size
-               #~ print "material name size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write name
-               name_length=len(self.name)+1
-               binary_format="<"+str(name_length)+"s"
-               data=struct.pack(binary_format, self.name)
-               file.write(data)
-
-class material_chunk(chunk):
-       matname_chunk=None
-       matambient_chunk=None
-       matdiffuse_chunk=None
-       matspecular_chunk=None
-
-       def __init__(self):
-               self.ID=MATERIAL
-               self.matname_chunk=material_name_chunk()
-               self.matambient_chunk=material_ambient_chunk()
-               self.matdiffuse_chunk=material_diffuse_chunk()
-               self.matspecular_chunk=material_specular_chunk()
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=self.matname_chunk.get_size()
-               temp_size+=self.matambient_chunk.get_size()
-               temp_size+=self.matdiffuse_chunk.get_size()
-               temp_size+=self.matspecular_chunk.get_size()
-               self.size+=temp_size
-               #~ print "material chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write name chunk
-               self.matname_chunk.write(file)
-               #write material colors
-               self.matambient_chunk.write(file)
-               self.matdiffuse_chunk.write(file)
-               self.matspecular_chunk.write(file)
-
-class primary_chunk(chunk):
-       version=None
-       obj_info=None
-
-       def __init__(self):
-               self.version=version_chunk()
-               self.obj_info=object_info_chunk()
-               self.ID=PRIMARY
-
-       def get_size(self):
-               chunk.get_size(self)
-               temp_size=self.version.get_size()
-               temp_size+=self.obj_info.get_size()
-               self.size+=temp_size
-               #~ print "primary chunk size: ", self.size
-               return self.size
-
-       def write(self, file):
-               chunk.write(self, file)
-               #write version chunk
-               self.version.write(file)
-               #write object_info chunk
-               self.obj_info.write(file)
-
-def read_chunk(file, chunk):
-               chunk.ID, chunk.size = \
-               struct.unpack(\
-               chunk.binary_format, \
-               file.read(struct.calcsize(chunk.binary_format))  )
-       
-def read_string(file):
-       s=""
-       index=0
-       
-       #read in the characters till we get a null character
-       data=struct.unpack("c", file.read(struct.calcsize("c")))
-       s=s+(data[0])
-       #print "string: ",s
-       while(ord(s[index])!=0):
-               index+=1
-               data=struct.unpack("c", file.read(struct.calcsize("c")))
-               s=s+(data[0])
-               #print "string: ",s
-       return str(s)
-
-######################################################
-# EXPORT
-######################################################
-def save_3ds(filename):
-       # Time the export
-       time1 = Blender.sys.time()
-
-       exported_materials = {}
-
-       #fill the chunks full of data
-       primary=primary_chunk()
-       #get all the objects in this scene
-       object_list = [ ob for ob in Blender.Object.GetSelected() if ob.getType() == 'Mesh' ]
-       #fill up the data structures with objects
-       for obj in object_list:
-               #create a new object chunk
-               primary.obj_info.obj_chunks.append(object_chunk())
-               #get the mesh data
-               blender_mesh = obj.getData()
-               blender_mesh.transform(obj.getMatrix())
-               #set the object name
-               primary.obj_info.obj_chunks[len(primary.obj_info.obj_chunks)-1].name=obj.getName()
-
-               matrix = obj.getMatrix()
-
-               #make a new mesh chunk object
-               mesh=mesh_chunk()
-               
-               mesh.v_chunk.verts = blender_mesh.verts
-               
-               dummy = None # just incase...
-               
-               for m in blender_mesh.materials:
-                       mesh.f_chunk.m_chunks.append(obj_material_chunk())
-                       mesh.f_chunk.m_chunks[len(mesh.f_chunk.m_chunks)-1].name = m.name
-
-                       # materials should only be exported once
-                       try:
-                               dummy = exported_materials[m.name]
-                               
-                               
-                       except KeyError:
-                               material = material_chunk()
-                               material.matname_chunk.name=m.name
-                               material.matambient_chunk.col1.col = m.mirCol
-                               material.matambient_chunk.col2.col = m.mirCol
-                               material.matdiffuse_chunk.col1.col = m.rgbCol
-                               material.matdiffuse_chunk.col2.col = m.rgbCol
-                               material.matspecular_chunk.col1.col = m.specCol
-                               material.matspecular_chunk.col2.col = m.specCol
-                               
-                               primary.obj_info.mat_chunks.append(material)
-                               
-                               exported_materials[m.name] = None
-               
-               del dummy # unpolute the namespace
-               
-               valid_faces = [f for f in blender_mesh.faces if len(f) > 2]
-               facenr=0
-               #fill in faces
-               for face in valid_faces:
-                       
-                       #is this a tri or a quad
-                       num_fv=len(face.v)
-                       
-                       
-                       #it's a tri
-                       if num_fv==3:
-                               mesh.f_chunk.faces.append((face[0].index, face[1].index, face[2].index))
-                               if (face.materialIndex < len(mesh.f_chunk.m_chunks)):
-                                       mesh.f_chunk.m_chunks[face.materialIndex].faces.append(facenr)
-                               facenr+=1
-                       
-                       else: #it's a quad                                      
-                               mesh.f_chunk.faces.append((face[0].index, face[1].index, face[2].index))  # 0,1,2
-                               mesh.f_chunk.faces.append((face[2].index, face[3].index, face[0].index))  # 2,3,0
-                               #first tri
-                               if (face.materialIndex < len(mesh.f_chunk.m_chunks)):
-                                       mesh.f_chunk.m_chunks[face.materialIndex].faces.append(facenr)
-                               facenr+=1
-                               #other tri
-                               if (face.materialIndex < len(mesh.f_chunk.m_chunks)):
-                                       mesh.f_chunk.m_chunks[face.materialIndex].faces.append(facenr)
-                               facenr+=1
-                       
-
-               #fill in the UV info
-               if blender_mesh.hasVertexUV():
-                       for vert in blender_mesh.verts:
-                               mesh.uv_chunk.uv.append((vert.uvco[0], vert.uvco[1]))
-
-               elif blender_mesh.hasFaceUV():
-                       for face in valid_faces:
-                               # Tri or quad.
-                               for uv_coord in face.uv:
-                                       mesh.uv_chunk.uv.append((uv_coord[0], uv_coord[1]))
-
-               #filled in our mesh, lets add it to the file
-               primary.obj_info.obj_chunks[len(primary.obj_info.obj_chunks)-1].mesh_chunks.append(mesh)
-
-       #check the size
-       primary.get_size()
-       #open the files up for writing
-       file = open( filename, "wb" )
-       #recursively write the stuff to file
-       primary.write(file)
-       file.close()
-       print "3ds export time: %.2f" % (Blender.sys.time() - time1)
-       
-
-Blender.Window.FileSelector(save_3ds, "Export 3DS", newFName('3ds'))
diff --git a/release/scripts/3ds_import.py b/release/scripts/3ds_import.py
deleted file mode 100644 (file)
index 6bd81c2..0000000
+++ /dev/null
@@ -1,548 +0,0 @@
-#!BPY
-
-""" 
-Name: '3D Studio (.3ds)...'
-Blender: 237
-Group: 'Import'
-Tooltip: 'Import from 3DS file format (.3ds).'
-"""
-
-__author__ = ["Bob Holcomb", "Richard Lärkäng", "Damien McGinnes", "Campbell Barton"]
-__url__ = ("blender", "elysiun", "http://www.gametutorials.com")
-__version__ = "0.82"
-__bpydoc__ = """\
-
-3ds Importer
-
-This script imports a 3ds file and the materials into blender for editing.
-
-Loader is based on 3ds loader from www.gametutorials.com(Thanks DigiBen).
-
-Changes:<br>
-0.81a (fork- not 0.9) Campbell Barton 2005-06-08<br>
-- Simplified import code<br>
-- Never overwrite data<br>
-- Faster list handling<br>
-- Leaves import selected<br>
-
-0.81 Damien McGinnes 2005-01-09<br>
-- handle missing images better<br>
-    
-0.8 Damien McGinnes 2005-01-08<br>
-- copies sticky UV coords to face ones<br>
-- handles images better<br>
-- Recommend that you run 'RemoveDoubles' on each imported mesh after using this script
-
-"""
-
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# Script copyright (C) Bob Holcomb 
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-# --------------------------------------------------------------------------
-
-# Importing modules
-
-import Blender
-from Blender import NMesh, Scene, Object, Material, Image
-
-import sys, struct, string
-
-import os
-
-#this script imports uvcoords as sticky vertex coords
-#this parameter enables copying these to face uv coords
-#which shold be more useful.
-
-
-#===========================================================================#
-# Returns unique name of object/mesh (stops overwriting existing meshes)    #
-#===========================================================================#
-def getUniqueName(name):
-       newName = name
-       uniqueInt = 0
-       while 1:
-               try:
-                       ob = Object.Get(newName)
-                       # Okay, this is working, so lets make a new name
-                       newName = '%s.%d' % (name, uniqueInt)
-                       uniqueInt +=1
-               except AttributeError:
-                       if newName not in NMesh.GetNames():
-                               return newName
-                       else:
-                               newName = '%s.%d' % (name, uniqueInt)
-                               uniqueInt +=1
-
-
-######################################################
-# Data Structures
-######################################################
-
-#Some of the chunks that we will see
-#----- Primary Chunk, at the beginning of each file
-PRIMARY= long("0x4D4D",16)
-
-#------ Main Chunks
-OBJECTINFO   =      long("0x3D3D",16);      #This gives the version of the mesh and is found right before the material and object information
-VERSION      =      long("0x0002",16);      #This gives the version of the .3ds file
-EDITKEYFRAME=      long("0xB000",16);      #This is the header for all of the key frame info
-
-#------ sub defines of OBJECTINFO
-MATERIAL=45055         #0xAFFF                         // This stored the texture info
-OBJECT=16384           #0x4000                         // This stores the faces, vertices, etc...
-
-#>------ sub defines of MATERIAL
-MATNAME    =      long("0xA000",16);      # This holds the material name
-MATAMBIENT   =      long("0xA010",16);      # Ambient color of the object/material
-MATDIFFUSE   =      long("0xA020",16);      # This holds the color of the object/material
-MATSPECULAR   =      long("0xA030",16);      # SPecular color of the object/material
-MATSHINESS   =      long("0xA040",16);      # ??
-MATMAP       =      long("0xA200",16);      # This is a header for a new material
-MATMAPFILE    =      long("0xA300",16);      # This holds the file name of the texture
-
-#>------ sub defines of OBJECT
-OBJECT_MESH  =      long("0x4100",16);      # This lets us know that we are reading a new object
-OBJECT_LIGHT =      long("0x4600",16);      # This lets un know we are reading a light object
-OBJECT_CAMERA=      long("0x4700",16);      # This lets un know we are reading a camera object
-
-#>------ sub defines of CAMERA
-OBJECT_CAM_RANGES=   long("0x4720",16);      # The camera range values
-
-#>------ sub defines of OBJECT_MESH
-OBJECT_VERTICES =   long("0x4110",16);      # The objects vertices
-OBJECT_FACES    =   long("0x4120",16);      # The objects faces
-OBJECT_MATERIAL =   long("0x4130",16);      # This is found if the object has a material, either texture map or color
-OBJECT_UV       =   long("0x4140",16);      # The UV texture coordinates
-OBJECT_TRANS_MATRIX  =   long("0x4160",16); # The Object Matrix
-
-#the chunk class
-class chunk:
-       ID=0
-       length=0
-       bytes_read=0
-
-       #we don't read in the bytes_read, we compute that
-       binary_format="<HI"
-
-       def __init__(self):
-               self.ID=0
-               self.length=0
-               self.bytes_read=0
-
-       def dump(self):
-               print "ID: ", self.ID
-               print "ID in hex: ", hex(self.ID)
-               print "length: ", self.length
-               print "bytes_read: ", self.bytes_read
-               
-
-def read_chunk(file, chunk):
-               temp_data=file.read(struct.calcsize(chunk.binary_format))
-               data=struct.unpack(chunk.binary_format, temp_data)
-               chunk.ID=data[0]
-               chunk.length=data[1]
-               #update the bytes read function
-               chunk.bytes_read=6
-
-               #if debugging
-               #chunk.dump()
-
-def read_string(file):
-       s=""
-       index=0
-       #print "reading a string"
-       #read in the characters till we get a null character
-       temp_data=file.read(1)
-       data=struct.unpack("c", temp_data)
-       s=s+(data[0])
-       #print "string: ",s
-       while(ord(s[index])!=0):
-               index+=1
-               temp_data=file.read(1)
-               data=struct.unpack("c", temp_data)
-               s=s+(data[0])
-               #print "string: ",s
-       
-       #remove the null character from the string
-       the_string=s[:-1]
-       return str(the_string)
-
-######################################################
-# IMPORT
-######################################################
-def process_next_object_chunk(file, previous_chunk):
-       new_chunk=chunk()
-       temp_chunk=chunk()
-
-       while (previous_chunk.bytes_read<previous_chunk.length):
-               #read the next chunk
-               read_chunk(file, new_chunk)
-
-
-def process_next_chunk(file, previous_chunk, new_object_list):
-       contextObName = None
-       #contextLamp = None
-       contextMaterial = None
-       contextMatrix = Blender.Mathutils.Matrix(); contextMatrix.identity()
-       contextMesh = None
-       
-       TEXDICT={}
-       MATDICT={}
-       
-       objectList = [] # Keep a list of imported objects.
-       
-       # Localspace variable names, faster.
-       STRUCT_SIZE_1CHAR = struct.calcsize("c")
-       STRUCT_SIZE_2FLOAT = struct.calcsize("2f")
-       STRUCT_SIZE_3FLOAT = struct.calcsize("3f")
-       STRUCT_SIZE_UNSIGNED_SHORT = struct.calcsize("H")
-       STRUCT_SIZE_4UNSIGNED_SHORT = struct.calcsize("4H")
-       STRUCT_SIZE_4x3MAT = struct.calcsize("ffffffffffff")
-       
-       
-       def putContextMesh(myContextMesh):
-               INV_MAT = Blender.Mathutils.CopyMat(contextMatrix)
-               INV_MAT.invert()
-               contextMesh.transform(INV_MAT)
-               objectList.append(NMesh.PutRaw(contextMesh))
-               objectList[-1].name = contextObName
-               objectList[-1].setMatrix(contextMatrix)
-       
-       
-       #a spare chunk
-       new_chunk=chunk()
-       temp_chunk=chunk()
-
-       #loop through all the data for this chunk (previous chunk) and see what it is
-       while (previous_chunk.bytes_read<previous_chunk.length):
-               #read the next chunk
-               #print "reading a chunk"
-               read_chunk(file, new_chunk)
-
-               #is it a Version chunk?
-               if (new_chunk.ID==VERSION):
-                       #print "found a VERSION chunk"
-                       #read in the version of the file
-                       #it's an unsigned short (H)
-                       temp_data=file.read(struct.calcsize("I"))
-                       data=struct.unpack("I", temp_data)
-                       version=data[0]
-                       new_chunk.bytes_read+=4 #read the 4 bytes for the version number
-                       #this loader works with version 3 and below, but may not with 4 and above
-                       if (version>3):
-                               print "\tNon-Fatal Error:  Version greater than 3, may not load correctly: ", version
-
-               #is it an object info chunk?
-               elif (new_chunk.ID==OBJECTINFO):
-                       # print "found an OBJECTINFO chunk"
-                       process_next_chunk(file, new_chunk, new_object_list)
-                       
-                       #keep track of how much we read in the main chunk
-                       new_chunk.bytes_read+=temp_chunk.bytes_read
-
-               #is it an object chunk?
-               elif (new_chunk.ID==OBJECT):
-                       # print "found an OBJECT chunk"
-                       tempName = str(read_string(file))
-                       contextObName = getUniqueName( tempName )
-                       new_chunk.bytes_read += (len(tempName)+1)
-               
-               #is it a material chunk?
-               elif (new_chunk.ID==MATERIAL):
-                       # print "found a MATERIAL chunk"
-                       contextMaterial = Material.New()
-               
-               elif (new_chunk.ID==MATNAME):
-                       # print "Found a MATNAME chunk"
-                       material_name=""
-                       material_name=str(read_string(file))
-                       
-                       #plus one for the null character that ended the string
-                       new_chunk.bytes_read+=(len(material_name)+1)
-                       
-                       contextMaterial.setName(material_name)
-                       MATDICT[material_name] = contextMaterial.name
-               
-               elif (new_chunk.ID==MATAMBIENT):
-                       # print "Found a MATAMBIENT chunk"
-
-                       read_chunk(file, temp_chunk)
-                       temp_data=file.read(struct.calcsize("3B"))
-                       data=struct.unpack("3B", temp_data)
-                       temp_chunk.bytes_read+=3
-                       contextMaterial.mirCol = [float(col)/255 for col in data] # data [0,1,2] == rgb
-                       new_chunk.bytes_read+=temp_chunk.bytes_read
-
-               elif (new_chunk.ID==MATDIFFUSE):
-                       # print "Found a MATDIFFUSE chunk"
-
-                       read_chunk(file, temp_chunk)
-                       temp_data=file.read(struct.calcsize("3B"))
-                       data=struct.unpack("3B", temp_data)
-                       temp_chunk.bytes_read+=3
-                       contextMaterial.rgbCol = [float(col)/255 for col in data] # data [0,1,2] == rgb
-                       new_chunk.bytes_read+=temp_chunk.bytes_read
-
-               elif (new_chunk.ID==MATSPECULAR):
-                       # print "Found a MATSPECULAR chunk"
-
-                       read_chunk(file, temp_chunk)
-                       temp_data=file.read(struct.calcsize("3B"))
-                       data=struct.unpack("3B", temp_data)
-                       temp_chunk.bytes_read+=3
-                       
-                       contextMaterial.specCol = [float(col)/255 for col in data] # data [0,1,2] == rgb
-                       new_chunk.bytes_read+=temp_chunk.bytes_read
-
-               elif (new_chunk.ID==MATMAP):
-                       # print "Found a MATMAP chunk"
-                       pass # This chunk has no data
-
-               elif (new_chunk.ID==MATMAPFILE):
-                       # print "Found a MATMAPFILE chunk"
-                       texture_name=""
-                       texture_name=str(read_string(file))
-                       try:
-                               img = Image.Load(texture_name)
-                               TEXDICT[contextMaterial.name]=img
-                       except IOError:
-                               fname = os.path.join( os.path.dirname(FILENAME), texture_name)
-                               try:
-                                       img = Image.Load(fname)
-                                       TEXDICT[contextMaterial.name]=img
-                               except IOError:
-                                       print "\tERROR: failed to load image ",texture_name
-                                       TEXDICT[contextMaterial.name] = None # Dummy
-                                       
-                       #plus one for the null character that gets removed
-                       new_chunk.bytes_read += (len(texture_name)+1)
-
-
-               elif (new_chunk.ID==OBJECT_MESH):
-                       # print "Found an OBJECT_MESH chunk"
-                       if contextMesh != None: # Write context mesh if we have one.
-                               putContextMesh(contextMesh)
-                       
-                       contextMesh = NMesh.New()
-                       
-                       # Reset matrix
-                       contextMatrix = Blender.Mathutils.Matrix(); contextMatrix.identity()
-                       
-               elif (new_chunk.ID==OBJECT_VERTICES):
-                       # print "Found an OBJECT_VERTICES chunk"
-                       #print "object_verts: length: ", new_chunk.length
-                       temp_data=file.read(STRUCT_SIZE_UNSIGNED_SHORT)
-                       data=struct.unpack("H", temp_data)
-                       new_chunk.bytes_read+=2
-                       num_verts=data[0]
-                       # print "number of verts: ", num_verts
-                       for counter in range (num_verts):
-                               temp_data=file.read(STRUCT_SIZE_3FLOAT)
-                               new_chunk.bytes_read += STRUCT_SIZE_3FLOAT #12: 3 floats x 4 bytes each
-                               data=struct.unpack("3f", temp_data)
-                               v=NMesh.Vert(data[0],data[1],data[2])
-                               contextMesh.verts.append(v)
-                       #print "object verts: bytes read: ", new_chunk.bytes_read
-
-               elif (new_chunk.ID==OBJECT_FACES):
-                       # print "Found an OBJECT_FACES chunk"
-                       #print "object faces: length: ", new_chunk.length
-                       temp_data=file.read(STRUCT_SIZE_UNSIGNED_SHORT)
-                       data=struct.unpack("H", temp_data)
-                       new_chunk.bytes_read+=2
-                       num_faces=data[0]
-                       #print "number of faces: ", num_faces
-
-                       for counter in range(num_faces):
-                               temp_data=file.read(STRUCT_SIZE_4UNSIGNED_SHORT)
-                               new_chunk.bytes_read += STRUCT_SIZE_4UNSIGNED_SHORT #4 short ints x 2 bytes each
-                               data=struct.unpack("4H", temp_data)
-                               
-                               #insert the mesh info into the faces, don't worry about data[3] it is a 3D studio thing
-                               f = NMesh.Face( [contextMesh.verts[data[i]] for i in xrange(3) ] )
-                               f.uv = [ tuple(contextMesh.verts[data[i]].uvco[:2]) for  i in xrange(3) ]
-                               contextMesh.faces.append(f)
-                       #print "object faces: bytes read: ", new_chunk.bytes_read
-
-               elif (new_chunk.ID==OBJECT_MATERIAL):
-                       # print "Found an OBJECT_MATERIAL chunk"
-                       material_name=""
-                       material_name=str(read_string(file))
-                       new_chunk.bytes_read += len(material_name)+1 # remove 1 null character.
-
-                       #look up the material in all the materials
-                       material_found=0
-                       for mat in Material.Get():
-                               
-                               #found it, add it to the mesh
-                               if(mat.name==material_name):
-                                       if len(contextMesh.materials) >= 15:
-                                               print "\tCant assign more than 16 materials per mesh, keep going..."
-                                               break
-                                       else:
-                                               meshHasMat = 0
-                                               for myMat in contextMesh.materials:
-                                                       if myMat.name == mat.name:
-                                                               meshHasMat = 1
-                                               
-                                               if meshHasMat == 0:
-                                                       contextMesh.addMaterial(mat)
-                                                       material_found=1
-                                                       
-                                                       #figure out what material index this is for the mesh
-                                                       for mat_counter in range(len(contextMesh.materials)):
-                                                               if contextMesh.materials[mat_counter].name == material_name:
-                                                                       mat_index=mat_counter
-                                                                       #print "material index: ",mat_index
-                                                       
-                                               
-                                               break # get out of this for loop so we don't accidentally set material_found back to 0
-                               else:
-                                       material_found=0
-                                       # print "Not matching: ", mat.name, " and ", material_name
-
-                       if material_found == 1:
-                               contextMaterial = mat
-                               #read the number of faces using this material
-                               temp_data=file.read(STRUCT_SIZE_UNSIGNED_SHORT)
-                               data=struct.unpack("H", temp_data)
-                               new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
-                               num_faces_using_mat=data[0]
-
-                               #list of faces using mat
-                               for face_counter in range(num_faces_using_mat):
-                                       temp_data=file.read(STRUCT_SIZE_UNSIGNED_SHORT)
-                                       new_chunk.bytes_read += STRUCT_SIZE_UNSIGNED_SHORT
-                                       data=struct.unpack("H", temp_data)
-                                       contextMesh.faces[data[0]].materialIndex = mat_index
-                                       
-                                       try:
-                                               mname = MATDICT[contextMaterial.name]
-                                               contextMesh.faces[data[0]].image = TEXDICT[mname]
-                                       except:
-                                               continue
-                       else:
-                               #read past the information about the material you couldn't find
-                               #print "Couldn't find material.  Reading past face material info"
-                               buffer_size=new_chunk.length-new_chunk.bytes_read
-                               binary_format=str(buffer_size)+"c"
-                               temp_data=file.read(struct.calcsize(binary_format))
-                               new_chunk.bytes_read+=buffer_size
-                       
-                       #print "object mat: bytes read: ", new_chunk.bytes_read
-
-               elif (new_chunk.ID == OBJECT_UV):
-                       # print "Found an OBJECT_UV chunk"
-                       temp_data=file.read(STRUCT_SIZE_UNSIGNED_SHORT)
-                       data=struct.unpack("H", temp_data)
-                       new_chunk.bytes_read+=2
-                       num_uv=data[0]
-
-                       for counter in range(num_uv):
-                               temp_data=file.read(STRUCT_SIZE_2FLOAT)
-                               new_chunk.bytes_read += STRUCT_SIZE_2FLOAT #2 float x 4 bytes each
-                               data=struct.unpack("2f", temp_data)
-                               
-                               #insert the insert the UV coords in the vertex data
-                               contextMesh.verts[counter].uvco = data
-               
-               elif (new_chunk.ID == OBJECT_TRANS_MATRIX):
-                       # print "Found an OBJECT_TRANS_MATRIX chunk"
-                       
-                       temp_data=file.read(STRUCT_SIZE_4x3MAT)
-                       data = list( struct.unpack("ffffffffffff", temp_data) )
-                       new_chunk.bytes_read += STRUCT_SIZE_4x3MAT 
-                       
-                       contextMatrix = Blender.Mathutils.Matrix(\
-                        data[:3] + [0],\
-                        data[3:6] + [0],\
-                        data[6:9] + [0],\
-                        data[9:] + [1])
-               
-               
-               
-               else: #(new_chunk.ID!=VERSION or new_chunk.ID!=OBJECTINFO or new_chunk.ID!=OBJECT or new_chunk.ID!=MATERIAL):
-                       # print "skipping to end of this chunk"
-                       buffer_size=new_chunk.length-new_chunk.bytes_read
-                       binary_format=str(buffer_size)+"c"
-                       temp_data=file.read(struct.calcsize(binary_format))
-                       new_chunk.bytes_read+=buffer_size
-
-
-               #update the previous chunk bytes read
-               previous_chunk.bytes_read += new_chunk.bytes_read
-               #print "Bytes left in this chunk: ", previous_chunk.length-previous_chunk.bytes_read
-       
-       # FINISHED LOOP
-       # There will be a number of objects still not added
-       if contextMesh != None:
-               putContextMesh(contextMesh)
-       
-       for ob in objectList:
-               ob.sel = 1
-
-def load_3ds (filename):
-       print 'Importing "%s"' % filename
-       
-       time1 = Blender.sys.time()
-       
-       global FILENAME
-       FILENAME=filename
-       current_chunk=chunk()
-       
-       file=open(filename,"rb")
-       
-       #here we go!
-       # print "reading the first chunk"
-       new_object_list = []
-       read_chunk(file, current_chunk)
-       if (current_chunk.ID!=PRIMARY):
-               print "\tFatal Error:  Not a valid 3ds file: ", filename
-               file.close()
-               return
-
-       process_next_chunk(file, current_chunk, new_object_list)
-       
-       # Select all new objects.
-       for ob in new_object_list: ob.sel = 1
-       
-       print 'finished importing: "%s" in %.4f sec.' % (filename, (Blender.sys.time()-time1))
-       file.close()
-
-#***********************************************
-# MAIN
-#***********************************************
-def my_callback(filename):
-       load_3ds(filename)
-
-Blender.Window.FileSelector(my_callback, "Import 3DS", '*.3ds')
-
-# For testing compatibility
-'''
-TIME = Blender.sys.time()
-import os
-for _3ds in os.listdir('/3ds/'):
-       if _3ds.lower().endswith('3ds'):
-               print _3ds
-               newScn = Scene.New(_3ds)
-               newScn.makeCurrent()
-               my_callback('/3ds/' + _3ds)
-
-print "TOTAL TIME: ", Blender.sys.time() - TIME
-'''
index ea9ba239003614ee022fe14f5ceea054aad7ce42..b9b7b8e5ae6081bc1a12fb516a3f2bfd77a7a936 100644 (file)
@@ -202,8 +202,7 @@ def transform_verts(verts, m):
        vecs = []
        for v in verts:
                vec = Mathutils.Vector([v[0],v[1],v[2], 1])
-               #vecs.append(Mathutils.VecMultMat(vec, m))
-               vecs.append(vec*m)
+               vecs.append(Mathutils.VecMultMat(vec, m))
        return vecs
 
 # ---
index 4dcde65fb4af78a9b17c3abe18d78b89385edba4..d2505022adf88a44af67b28e834cf1f042ff7e9f 100644 (file)
@@ -10,7 +10,7 @@ Tip: 'Import an AC3D (.ac) file.'
 __author__ = "Willian P. Germano"
 __url__ = ("blender", "elysiun", "AC3D's homepage, http://www.ac3d.org",
        "PLib 3d gaming lib, http://plib.sf.net")
-__version__ = "2.36a 2005-12-04"
+__version__ = "2.36 2005-04-14"
 
 __bpydoc__ = """\
 This script imports AC3D models into Blender.
@@ -43,9 +43,9 @@ users can configure (see config options above).
 # $Id$
 #
 # --------------------------------------------------------------------------
-# AC3DImport version 2.36a Dec 04, 2005
+# AC3DImport version 2.36 Apr 14, 2005
 # Program versions: Blender 2.36+ and AC3Db files (means version 0xb)
-# changed: fixed a bug: error on 1 vertex "closed" polylines
+# changed: updated to use the Scripts Config Editor facilities
 # --------------------------------------------------------------------------
 # ***** BEGIN GPL LICENSE BLOCK *****
 #
@@ -366,7 +366,7 @@ class AC3DImport:
                                        faces.append(cut)
                                        face = face[1:]
 
-                               if flaglow == 1 and faces:
+                               if flaglow == 1:
                                        face = [faces[-1][-1], faces[0][0]]
                                        faces.append(face)
 
@@ -498,9 +498,7 @@ class AC3DImport:
                                for vi in range(len(f)):
                                        bface.v.append(mesh.verts[f[vi][0]])
                                        bface.uv.append((f[vi][1][0], f[vi][1][1]))
-                               #mesh.faces.append(bface)
-                               # quick hack, will switch from NMesh to Mesh later:
-                               if len(bface.v) > 1: mesh.addFace(bface)
+                               mesh.faces.append(bface)
 
                        mesh.mode = 0
                        object = Blender.NMesh.PutRaw(mesh)
index 3a0169f2dfb3050af484dedf794a55cbc3e5292c..6025cef7f0e11f1e41da9a25e143542dbb005928 100644 (file)
@@ -123,7 +123,7 @@ def parall_coord(old, dir):
        return (nco,vec)
 
 def get_vert(old, dir):
-       """ Look in NV if a vertex corresponding to the vertex old and the
+       """ Look in NV if a vertice corresponding to the vertex old and the
        direction dir already exists, and create one otherwise""" 
        (nco, vec) = parall_coord(old, dir)
        v = is_in_NV(old,vec)
@@ -315,7 +315,7 @@ def make_corners():
                        is_in_v = lambda x:x in V
                        eed =  [filter(is_in_v, l) for l in q]
                        #
-                       # We will add the edges coming from faces where only one vertex is selected.
+                       # We will add the edges coming from faces where only one vertice is selected.
                        # They are stocked in NC.
                        if v in NC.keys():
                                eed = eed+NC[v]
diff --git a/release/scripts/blenderLipSynchro.py b/release/scripts/blenderLipSynchro.py
deleted file mode 100644 (file)
index 8c66e67..0000000
+++ /dev/null
@@ -1,602 +0,0 @@
-#!BPY
-
-"""
-Name: 'BlenderLipSynchro'
-Blender: 239
-Group: 'Animation'
-Tooltip: 'Import phonemes from Papagayo or JLipSync for lip synchronisation'
-"""
-
-__author__ = "Dienben: Benoit Foucque dienben_mail@yahoo.fr"
-__url__ = ("blenderLipSynchro Blog, http://blenderlipsynchro.blogspot.com/",
-"Papagayo (Python), http://www.lostmarble.com/papagayo/index.shtml",
-"JLipSync (Java), http://jlipsync.sourceforge.net/")
-__version__ = "1.2"
-__bpydoc__ = """\
-Description:
-
-This script imports Voice Export made by Papagayo or JLipSync and maps the export with your shapes.
-
-Usage:
-
-Import a Papagayo or JLipSync voice export file and link it with your shapes.
-
-Note:<br>
-- Naturally, you need files exported from one of the supported lip synching
-programs. Check their sites to learn more and download them.
-
-"""
-
-# --------------------------------------------------------------------------
-# BlenderLipSynchro
-# --------------------------------------------------------------------------
-# ***** BEGIN GPL LICENSE BLOCK *****
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#
-# ***** END GPL LICENCE BLOCK *****
-# -------------------------------------------------------------------------- 
-
-
-
-#il y a 3 etapes
-#la deuxieme on charge le dictionnaire de correspondance
-#la troisieme on fait le choix des correpondance
-#la quatrieme on construit les cles a partir du fichiers frame
-
-#there are 3 stage
-#the second one load the mapping dictionnary 
-#the tird make the mapping
-#the fourth make the key in the IPO Curve
-
-#voici mes differents imports
-#the imports
-import os
-import Blender
-
-from Blender import Ipo
-from Blender.Draw import *
-from Blender.BGL import *
-
-
-
-#ici commencent mes fonctions
-#here begin my functions
-#cette fonction trace l'interface graphique
-#this functions draw the User interface
-def trace():
-    #voici mes variables pouvant etre modifie
-    #my variables
-    global fichier_dico,repertoire_dictionaire,iponame,repertoire_phoneme,fichier_text,nbr_phoneme
-    global let01, let02, let03, let04,let05, let06, let07, let08, let09, let10
-    global let11, let12, let13, let14,let15, let16, let17, let18, let19, let20
-    global let21, let22, let23, let24
-
-    global let01selectkey,let02selectkey,let03selectkey,let04selectkey,let05selectkey
-    global let06selectkey,let07selectkey,let08selectkey,let09selectkey,let10selectkey,let11selectkey
-    global let12selectkey,let13selectkey,let14selectkey,let15selectkey,let16selectkey,let17selectkey
-    global let18selectkey,let19selectkey,let20selectkey,let21selectkey,let22selectkey,let23selectkey
-    global let24selectkey
-    
-    glClearColor(0.4,0.5,0.6 ,0.0)
-    glClear(GL_COLOR_BUFFER_BIT)
-
-    glColor3d(1,1,1)
-    glRasterPos2i(87, 375)
-    Text("Blendersynchro V 1.1")
-    glColor3d(1,1,1)
-    glRasterPos2i(84, 360)
-    Text("Programation: Dienben")
-
-    glColor3d(0,0,0)
-    glRasterPos2i(13, 342)
-    Text("Papagayo File importer")
-    glColor3d(0,0,0)
-    glRasterPos2i(13, 326)
-    Text("Thanks to Chris Clawson and Liubomir Kovatchev")
-
-    glColor3d(1,1,1)
-    glRasterPos2i(5, 320)
-    Text("_______________________________________________________")
-    glColor3d(0,0,0)
-    glRasterPos2i(6, 318)
-    Text("_______________________________________________________")
-
-    
-    if (etape==1):
-        #cette etape permet de choisi la correspondance entre les phonemes et les cles
-        #this stage offer the possibility to choose the mapping between phonems and shapes
-
-        glColor3d(1,1,1)
-        glRasterPos2i(140, 300)
-        Text("Objet: "+Blender.Object.GetSelected()[0].getName() )
-
-        glColor3d(1,1,1)
-        glRasterPos2i(5, 215)
-        Text("Assign phonems to shapes:")
-
-        #on mesure la taille de la liste de phonemes
-        #this is the lenght of the phonem list
-        nbr_phoneme=len(liste_phoneme)
-
-        #on dessine les listes de choix
-        #we draw the choice list
-
-        let01 = String(" ", 4, 5, 185, 30, 16, liste_phoneme[0], 3)
-        glColor3d(0,0,0)
-        glRasterPos2i(40, 188)
-        Text("=")
-        let01selectkey = Menu(key_menu, 50, 50, 185, 70, 16, let01selectkey.val)
-
-
-       let02 = String(" ", 4, 150, 185, 30, 16, liste_phoneme[1], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(185, 188)
-       Text("=")
-       let02selectkey = Menu(key_menu, 51, 195, 185, 70, 16, let02selectkey.val)
-
-
-       let03 = String(" ", 4, 5, 165, 30, 16, liste_phoneme[2], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(40, 168)
-       Text("=")
-       let03selectkey = Menu(key_menu, 52, 50, 165, 70, 16, let03selectkey.val)
-
-
-       let04 = String(" ", 4, 150, 165, 30, 16, liste_phoneme[3], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(185, 168)
-       Text("=")
-       let04selectkey = Menu(key_menu, 53, 195, 165, 70, 16, let04selectkey.val)
-
-
-       let05 = String(" ", 4, 5, 145, 30, 16, liste_phoneme[4], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(40, 148)
-       Text("=")
-       let05selectkey = Menu(key_menu, 54, 50, 145, 70, 16, let05selectkey.val)
-
-
-       let06 = String(" ", 4, 150, 145, 30, 16, liste_phoneme[5], 2)
-       glColor3d(0,0,0)                                
-       glRasterPos2i(185, 148)
-       Text("=")
-       let06selectkey = Menu(key_menu, 55, 195, 145, 70, 16, let06selectkey.val)
-
-
-       let07 = String(" ", 4, 5, 125, 30, 16, liste_phoneme[6], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(40, 128)
-       Text("=")
-       let07selectkey = Menu(key_menu, 56, 50, 125, 70, 16, let07selectkey.val)
-
-       #
-       let08 = String(" ", 4, 150, 125, 30, 16, liste_phoneme[7], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(185, 128)
-       Text("=")
-       let08selectkey = Menu(key_menu, 57, 195, 125, 70, 16,let08selectkey.val)
-
-
-       let09 = String(" ", 4, 5, 105, 30, 16, liste_phoneme[8], 2)
-       glColor3d(0,0,0)
-       glRasterPos2i(40, 108)
-       Text("=")
-       let09selectkey = Menu(key_menu, 58, 50, 105, 70, 16,let09selectkey.val)
-
-
-       let10 = String(" ", 4, 150, 105, 30, 16, liste_phoneme[9], 2)
-       glColor3d(0,0,0)                                
-       glRasterPos2i(185, 108)
-       Text("=")
-       let10selectkey = Menu(key_menu, 59, 195, 105, 70, 16, let10selectkey.val)
-       
-       #soft_type = 0:Papagayo
-       #soft_type = 1:JLipSync
-       if (soft_type==1):
-               let11 = String(" ", 4, 5, 85, 30, 16, liste_phoneme[10], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(40, 88)
-               Text("=")
-               let11selectkey = Menu(key_menu, 60, 50, 85, 70, 16, let11selectkey.val)
-
-               let12 = String(" ", 4, 150, 85, 30, 16, liste_phoneme[11], 2)
-               glColor3d(0,0,0)                                
-               Text("=")
-               let12selectkey = Menu(key_menu, 61, 195, 85, 70, 16, let12selectkey.val)
-       
-               let13 = String(" ", 4, 5, 65, 30, 16, liste_phoneme[12], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(40, 68)
-               Text("=")
-               let13selectkey = Menu(key_menu, 62, 50, 65, 70, 16, let13selectkey.val)
-       
-               let14 = String(" ", 4, 150, 65, 30, 16, liste_phoneme[13], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(185, 68)
-               Text("=")
-               let14selectkey = Menu(key_menu, 63, 195, 65, 70, 16, let14selectkey.val)
-       
-               let15 = String(" ", 4, 5, 45, 30, 16, liste_phoneme[14], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(40, 48)
-               Text("=")
-               let15selectkey = Menu(key_menu, 64, 50, 45, 70, 16, let15selectkey.val)
-       
-               let16 = String(" ", 4, 150, 45, 30, 16, liste_phoneme[15], 2)
-               glColor3d(0,0,0)                                
-               glRasterPos2i(185, 48)
-               Text("=")
-               let16selectkey = Menu(key_menu, 65, 195, 45, 70, 16, let16selectkey.val)
-       
-               let17 = String(" ", 4, 295, 185, 30, 16, liste_phoneme[16], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(330, 188)
-               Text("=")
-               let17selectkey = Menu(key_menu, 66, 340, 185, 70, 16, let17selectkey.val)
-       
-               let18 = String(" ", 4, 440, 185, 70, 16, liste_phoneme[17], 8)
-               glColor3d(0,0,0)
-               glRasterPos2i(515, 188)
-               Text("=")
-               let18selectkey = Menu(key_menu, 67, 525, 185, 70, 16, let18selectkey.val)
-       
-               let19 = String(" ", 4, 295, 165, 30, 16, liste_phoneme[18], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(330, 168)
-               Text("=")
-               let19selectkey = Menu(key_menu, 68, 340, 165, 70, 16, let19selectkey.val)
-       
-               let20 = String(" ", 4, 440, 165, 70, 16, liste_phoneme[19], 8)
-               glColor3d(0,0,0)
-               glRasterPos2i(515, 168)
-               Text("=")
-               let20selectkey = Menu(key_menu, 69, 525, 165, 70, 16, let20selectkey.val)
-       
-               let21 = String(" ", 4, 295, 145, 30, 16, liste_phoneme[20], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(330, 148)
-               Text("=")
-               let21selectkey = Menu(key_menu, 70, 340, 145, 70, 16, let21selectkey.val)
-       
-               let22 = String(" ", 4, 440, 145, 70, 16, liste_phoneme[21], 8)
-               glColor3d(0,0,0)                                
-               glRasterPos2i(515, 148)
-               Text("=")
-               let22selectkey = Menu(key_menu, 71, 525, 145, 70, 16, let22selectkey.val)
-       
-               let23 = String(" ", 4, 295, 125, 30, 16, liste_phoneme[22], 2)
-               glColor3d(0,0,0)
-               glRasterPos2i(330, 128)
-               Text("=")
-               let23selectkey = Menu(key_menu, 72, 340, 125, 70, 16,let23selectkey.val)
-       
-               let24 = String(" ", 4, 440, 125, 70, 16, liste_phoneme[23], 8)
-               glColor3d(0,0,0)
-               glRasterPos2i(515, 128)
-               Text("=")
-               let24selectkey = Menu(key_menu, 73, 525, 125, 70, 16, let24selectkey.val)
-       
-       
-       Button("Import Text", 3, 155, 5, 145, 22)
-       Button("Choose Voice Export", 4, 120, 250, 250, 22)
-
-       
-    if (etape==2):
-        glColor3d(1,1,1)
-        glRasterPos2i(125, 200)
-        Text("Operation Completed")
-        
-    if (etape==0):
-        glColor3d(1,1,1)
-        glRasterPos2i(125, 200)
-        Text("Please select a Mesh'Object and Create all the IPO Curves for your Shapes")
-        
-    if (etape==3):
-       Button("Papagayo", 5, 155, 250, 250, 22)
-       Button("JlipSync", 6, 155, 225, 250, 22)
-
-    glColor3d(1,1,1)
-    glRasterPos2i(6, 40)
-    Text("_______________________________________________________")
-    glColor3d(0,0,0)
-    glRasterPos2i(6, 38)
-    Text("_______________________________________________________")
-       
-    Button("Exit", 1, 305, 5, 80, 22)
-    
-    
-       
-       
-#cette fonction sur evenement quite en cas d'ESC
-#this functions catch the ESC event and quit
-def event(evt,val):
-       if (evt == ESCKEY and not val): Exit()
-
-#cette fonction gere les evenements
-#the event functions
-def bevent(evt):
-       global etape,soft_type,liste_phoneme
-
-       if (evt == 1):
-               Exit()
-       
-               
-        elif (evt == 4):
-            #c'est le choix de l'export pamela
-            #we choose the papagayo export
-            Blender.Window.FileSelector(selectionner_export_papagayo,"Choose Export")
-            
-            
-        elif (evt == 3):
-            #c'est l'import Papagayo
-            #we import 
-            lecture_chaine(mon_fichier_export_pamela,dico_phoneme_export_pamela)
-            construction_dico_correspondance()
-            construction_lipsynchro()
-            #on change d'etape
-            #we change the stage
-            etape=2
-         
-        elif (evt == 5):
-            #we choose papagayo
-            soft_type=0
-            liste_phoneme=liste_phoneme_papagayo
-            etape=1
-         
-        elif (evt == 6):
-            #we choose jlipsync
-            soft_type=1
-            liste_phoneme=liste_phoneme_jlipsinch
-            etape=1
-               
-        Blender.Redraw()
-
-#cette fonction recupere le nom et le chemin du fichier dictionnaire
-#we catch the name and the path of the dictionnary
-def selectionner_export_papagayo(filename):
-    global mon_fichier_export_pamela
-    #debut
-    mon_fichier_export_pamela=filename
-    
-#fonction de lecture de la liste frame phoneme
-#we read the frame and phonems
-def lecture_chaine(fichier,liste):
-    mon_fichier=open(fichier)
-        
-    #je lis la premiere ligne qui contiens la version de moho
-    #first, we read the moho version
-    mon_fichier.readline()
-
-    #je lis jusqu'a la fin
-    #then we read until the end of the file
-    while 1:
-        ma_ligne=mon_fichier.readline()
-        if ma_ligne=='':
-            break
-        decoup=ma_ligne.split()
-        liste[decoup[0]]=decoup[1]
-    print liste
-
-
-
-
-#fonction qui construit la liste dictionnaire simple
-#we make the dictionnary
-def construction_dictionnaire_phoneme():
-    index_liste=0
-     #je transforme mon dictionnaire en list de tulpes
-     #we transform the list in tulpes
-    ma_liste=dico_phoneme.items()
-    #je parcours ma liste a la recherche d'elements non existant
-    #we read the list to find non existing elements
-    print dico_phoneme
-    for index in range(len(ma_liste)):
-        if ma_liste[index][1] not in liste_phoneme:
-            liste_phoneme[index_liste:index_liste]=[ma_liste[index][1]]
-            index_liste=index_liste+1
-    print liste_phoneme
-     
-
-
-#cette fonction recupere les courbes cible 
-#this functon catch the IPO curve
-def recuperation_courbe():
-       global key_menu,dico_key
-
-       #on recupere le nom des shapes
-       #we catch the shapes
-       key=Blender.Object.GetSelected()[0].getData().getKey().getBlocks()
-       for n in range(len(key)):
-               #on vire la première cle (en effet basic n'est pas une cle en tant que telle)
-               #we threw away the basic shapes
-               if (n>0):
-                       key_menu=key_menu+key[n].name + " %x" + str(n-1) + "|"
-                       dico_key[str(n-1)]=Blender.Object.GetSelected()[0].getData().getKey().getIpo().getCurves()[n-1]
-       
-       
-       print "dico_key"
-       print dico_key
-       print 'end dico_key'
-
-#cette fonction construit un dictionnaire de correspondance entre les phonemes prononces et les cles a utiliser
-#we make the dictionnary for the mapping between shapes and phonems
-def construction_dico_correspondance():
-       global dico_correspondance
-       #je parcours les phonemes
-       #we read the phonems
-       dico_correspondance[liste_phoneme[0]]=dico_key[str(let01selectkey.val)]
-       dico_correspondance[liste_phoneme[1]]=dico_key[str(let02selectkey.val)]
-       dico_correspondance[liste_phoneme[2]]=dico_key[str(let03selectkey.val)]
-       dico_correspondance[liste_phoneme[3]]=dico_key[str(let04selectkey.val)]
-       dico_correspondance[liste_phoneme[4]]=dico_key[str(let05selectkey.val)]
-       dico_correspondance[liste_phoneme[5]]=dico_key[str(let06selectkey.val)]
-       dico_correspondance[liste_phoneme[6]]=dico_key[str(let07selectkey.val)]
-       dico_correspondance[liste_phoneme[7]]=dico_key[str(let08selectkey.val)]
-       dico_correspondance[liste_phoneme[8]]=dico_key[str(let09selectkey.val)]
-       dico_correspondance[liste_phoneme[9]]=dico_key[str(let10selectkey.val)]
-       
-       if (soft_type==1):
-               dico_correspondance[liste_phoneme[10]]=dico_key[str(let11selectkey.val)]
-               dico_correspondance[liste_phoneme[11]]=dico_key[str(let12selectkey.val)]
-               dico_correspondance[liste_phoneme[12]]=dico_key[str(let13selectkey.val)]
-               dico_correspondance[liste_phoneme[13]]=dico_key[str(let14selectkey.val)]
-               dico_correspondance[liste_phoneme[14]]=dico_key[str(let15selectkey.val)]
-               dico_correspondance[liste_phoneme[15]]=dico_key[str(let16selectkey.val)]
-               dico_correspondance[liste_phoneme[16]]=dico_key[str(let17selectkey.val)]
-               dico_correspondance[liste_phoneme[17]]=dico_key[str(let18selectkey.val)]
-               dico_correspondance[liste_phoneme[18]]=dico_key[str(let19selectkey.val)]
-               dico_correspondance[liste_phoneme[19]]=dico_key[str(let20selectkey.val)]
-               dico_correspondance[liste_phoneme[20]]=dico_key[str(let21selectkey.val)]
-               dico_correspondance[liste_phoneme[21]]=dico_key[str(let22selectkey.val)]
-               dico_correspondance[liste_phoneme[22]]=dico_key[str(let23selectkey.val)]
-               dico_correspondance[liste_phoneme[23]]=dico_key[str(let24selectkey.val)]
-               
-       print dico_correspondance
-
-
-#cette fonction ajoute un points a la cle donnee a la frame donnee
-#we add a point to the IPO curve Target
-def ajoute_point(cle,frame,valeur):
-    cle.setInterpolation('Linear')
-    cle.addBezier((frame,valeur))
-    cle.Recalc()
-
-#cette fonction parcours le dictionnaire des frame à ajouter et construit les points
-#we add all the point to the IPO Curve
-def construction_lipsynchro():
-    print "je construit"
-    doublet_old=""
-    #construction de la liste des frame
-    cpt=0
-    liste_frame=[]
-    for frame in dico_phoneme_export_pamela:
-        liste_frame.append(int(frame))
-        cpt=cpt+1
-    liste_frame.sort()
-    print "listeframe"
-    print liste_frame
-    print "fini"
-    
-    for doublet in liste_frame:
-        ajoute_point(dico_correspondance[dico_phoneme_export_pamela[str(doublet)]],doublet,1)
-        if (doublet_old==""):
-            ajoute_point(dico_correspondance[dico_phoneme_export_pamela[str(doublet)]],(doublet-2),0)
-        if (doublet_old!=''):
-            if (dico_correspondance[dico_phoneme_export_pamela[str(doublet)]]!=dico_correspondance[dico_phoneme_export_pamela[doublet_old]]):
-                print "doublet:"+str(doublet)
-                print "doublet old:"+doublet_old                
-                ajoute_point(dico_correspondance[dico_phoneme_export_pamela[doublet_old]],(int(doublet_old)+2),0)
-                ajoute_point(dico_correspondance[dico_phoneme_export_pamela[str(doublet)]],(doublet-2),0)
-        doublet_old=str(doublet)
-        
-
-#end of my functions we begin the execution       
-#je commence l execution-----------------------------------------------------------------------------------------------
-#voici mes variables
-
-#declaration et instanciation
-#decleration and instanciation
-#ce sont les repertoires
-repertoire_dictionaire=Create('C:/')
-repertoire_phoneme=Create('c:/')
-
-#ce sont ls fichiers
-fichier_dico=Create("sample.mot")
-fichier_text=Create("")
-
-#voici mon objet de travail
-objet_travail=Create(0)
-
-#my soft type
-soft_type=1
-
-#voici la liste des phoneme effectivement utilise
-#the phonems'list
-liste_phoneme_papagayo=['AI','E','O','U','FV','L','WQ','MBP','etc','rest']
-liste_phoneme_jlipsinch=['A','B','C','Closed','D','E','F','G','I','K','L','M','N','O','P','Q','R','S','SH','T','TH','U','V','W']
-
-liste_phoneme=liste_phoneme_jlipsinch
-#voici mon dictionnaire des frames o
-dico_phoneme_export_pamela = Create(0)
-dico_phoneme_export_pamela={}
-
-
-
-#voici mes cle
-key_menu=""
-dico_key={}
-
-#voici mes ipo
-dico_bloc={}
-iponame = Create(0)
-
-#voici mon dictionnaire de correspondance
-dico_correspondance={}
-
-try:
-       #on verifie est bien une mesh et qu'il a des courbes
-       if ((Blender.Object.GetSelected()[0].getType()=='Mesh')):
-               #on verifie que l'objet a bien toute ses Courbes
-               if (len(Blender.Object.GetSelected()[0].getData().getKey().getBlocks())-1==Blender.Object.GetSelected()[0].getData().getKey().getIpo().getNcurves()):
-                       etape=3
-                       #on lance la creation du dictionnaire
-                       recuperation_courbe()
-               else:
-                       print "not the good number of IPO Curve"
-                       etape = 0
-       else:
-               print "error: bad object Type:"
-               print Blender.Object.GetSelected()[0].getType()
-               etape = 0
-except:
-       print 'error: exception'
-       etape = 0
-
-
-#voici le fichier dictionnaire
-mon_fichier_dico=""
-
-#voici le fichier export pamela
-mon_fichier_export_pamela=""
-
-
-let01selectkey = Create(0)
-let02selectkey = Create(0)
-let03selectkey = Create(0)
-let04selectkey = Create(0)
-let05selectkey = Create(0)
-let06selectkey = Create(0)
-let07selectkey = Create(0)
-let08selectkey = Create(0)
-let09selectkey = Create(0)
-let10selectkey = Create(0)
-let11selectkey = Create(0)
-let12selectkey = Create(0)
-let13selectkey = Create(0)
-let14selectkey = Create(0)
-let15selectkey = Create(0)
-let16selectkey = Create(0)
-let17selectkey = Create(0)
-let18selectkey = Create(0)
-let19selectkey = Create(0)
-let20selectkey = Create(0)
-let21selectkey = Create(0)
-let22selectkey = Create(0)
-let23selectkey = Create(0)
-let24selectkey = Create(0)
-
-
-Register (trace,event,bevent)
index b34be8a82228520b0684aa3856862515d8f59d8c..ec04f59d60f3db74d0458ffed2303a9b965d7b4d 100644 (file)
@@ -1,62 +1,40 @@
 #!BPY
 """
-Name: 'Empties to Armature'
-Blender: 239
+Name: 'BVH Empties to Armature'
+Blender: 237
 Group: 'Animation'
-Tooltip: 'Create Armature from a parented-empties chain'
+Tooltip: 'Create Armature from Empties created by BVH importer'
 """
 __author__ = " Jean-Baptiste PERIN (jb_perin(at)yahoo.fr)"
 __url__ = ("blender", "elysiun",
-"BVH 2 ARMATURE, http://perso.wanadoo.fr/jb.perin/",
+"BVH 2 ARMATURE, http://www.zoo-logique.org/3D.Blender/index.php3?zoo=dld&rep=zip ",
 "Communicate problems and errors, http://www.zoo-logique.org/3D.Blender/newsportal/thread.php?group=3D.Blender") 
 
-__version__ = "2.4"
+__version__ = "2.2"
 
-__bpydoc__ = """ BVH2ARM.py 
+__bpydoc__ = """ BVH2ARM.py v2.2
 
 Script for generating armature on BVH empties.
 
-This script generates an armature upon an empty-made parented chain, 
-and make the armature follow the hip bone of the chain. 
-User only have to set up IKSolver contraints on every end effector bone.
-
+This script generates an armature and make bones
+follow empties created by Blender BVH import script.
 Usage:<br>
  - Import a bvh in Blender (File->Import->BVH);<br>
- - Select the root empty of the hierarchical chain.<br>
- - Launch this script ;<br>
+ - Launch this script (Alt-P);<br>
  - Set up variables:<br>
-   "hipbonename": the name of the main bone (automatically set to the selected empty).<br>
+   "hipbonename": the name of the main bone;<br>
    "startframe":  the first frame of your anim;<br>
    "endframe":  the last frame of your anim;<br>
-   "decimation": the frequency (in number of frame) to which the armature's pos is updated;<br>
-- Press "Create Armature".<br>
-- Set IKSolver for every end effector bone (targeting)
-
-Notes: <br>
-- The start frame configuration is used as the rest pose for the armature.<br>
-- If the armature already exists when script is launched, the current armature is re-used.
+   "decimation": the frequency (in number of frame) to which the armature is updated;<br>
+   "scale" to size the created armature.<br>
+ - Press "Create Armature".
 """
-# -------------------------------------------------------------------------- 
-# BVH2ARM.py 
-# -------------------------------------------------------------------------- 
-# ***** BEGIN GPL LICENSE BLOCK ***** 
-# 
-# This program is free software; you can redistribute it and/or 
-# modify it under the terms of the GNU General Public License 
-# as published by the Free Software Foundation; either version 2 
-# of the License, or (at your option) any later version. 
-# 
-# This program is distributed in the hope that it will be useful, 
-# but WITHOUT ANY WARRANTY; without even the implied warranty of 
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
-# GNU General Public License for more details. 
-# 
-# You should have received a copy of the GNU General Public License 
-# along with this program; if not, write to the Free Software Foundation, 
-# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
-# 
-# ***** END GPL LICENCE BLOCK ***** 
-# -------------------------------------------------------------------------- 
+
+#----------------------------------------------
+# (c) Jean-Baptiste PERIN  june 2005, released under Blender Artistic Licence
+#    for the Blender 2.34-2.36 Python Scripts Bundle.
+#----------------------------------------------
 
 
 
@@ -300,47 +278,30 @@ def computeScaledPos(vec):
 #########
 def createBone (armature, empty, bone, empties):
        children = getChildren(empty, empties)
-       if len(children) != 0:
-         for ch in children:
+       for ch in children:
                if len(children) >= 2:
                        bonename = empty.getName()[1:len(empty.getName())]+'_'+ch.getName()[1:len(ch.getName())]
                else :
                        bonename = empty.getName()[1:len(empty.getName())]
-               print "creating Bone %s"%(bonename)
-               b=Blender.Armature.Editbone()
-               b.head = (computeScaledPos(empty.getMatrix('worldspace').translationPart()))
-               b.tail = (computeScaledPos(ch.getMatrix('worldspace').translationPart()))
-               b.parent = bone
-               # armature.makeEditable()  should already be editable????
-               armature.bones[bonename] = b
-               #armature.update()
-##             #b.setParent(bone)
-##             matrice = empty.getMatrix('worldspace')
-##             invmatrice = empty.getMatrix('worldspace')
-##             invmatrice.invert()
-##             invmatricet=empty.getMatrix('worldspace')
-##             invmatricet.invert()
-##             invmatricet.transpose()
-##             dicEmptiesRestMatrix[empty.getName()] = matrice
-##             dicEmptiesInvRestMatrix[empty.getName()] = invmatrice
-##             #armature.addBone(b)
-##             #????armature.bones[b.name]=b
-##             #invbonerest=b.getRestMatrix()
-##             #invbonerest.invert()
-##             invbonerest=Blender.Mathutils.Matrix(b.matrix)
-##             invbonerest.resize4x4()
-##             invbonerest[3][3]=1.0
-##             invbonerest.invert()
-##
-##             #dicBoneRestMatrix[b.getName()] = b.matrix
-##             tmpmat = b.matrix.resize4x4()
-##             tmpmat[3][3] = 1.0
-##             dicBoneRestMatrix[b.name] = tmpmat
-##             
-##             #dicBoneRestInvEmpRest[b.getName()]=b.getRestMatrix()*invmatrice*invmatricet
-##             dicBoneRestInvEmpRest[b.name]=tmpmat*invmatrice*invmatricet
-##             dicEmpRestInvBoneRest[b.name]=matrice*invbonerest
-##             dicBone[b.name]=b
+               b=Blender.Armature.Bone.New(bonename)
+               b.setHead(computeScaledPos(empty.getMatrix('worldspace').translationPart()))
+               b.setTail(computeScaledPos(ch.getMatrix('worldspace').translationPart()))
+               #b.setParent(bone)
+               matrice = empty.getMatrix('worldspace')
+               invmatrice = empty.getMatrix('worldspace')
+               invmatrice.invert()
+               invmatricet=empty.getMatrix('worldspace')
+               invmatricet.invert()
+               invmatricet.transpose()
+               dicEmptiesRestMatrix[empty.getName()] = matrice
+               dicEmptiesInvRestMatrix[empty.getName()] = invmatrice
+               armature.addBone(b)
+               invbonerest=b.getRestMatrix()
+               invbonerest.invert()
+               dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
+               dicBoneRestInvEmpRest[b.getName()]=b.getRestMatrix()*invmatrice*invmatricet
+               dicEmpRestInvBoneRest[b.getName()]=matrice*invbonerest
+               dicBone[b.getName()]=b
                createBone(armature, ch, b, empties)
 
 #########
@@ -349,12 +310,13 @@ def createBone (armature, empty, bone, empties):
 # out : 
 #########
 def f_createBone (armData, empty, bone, empties):
-       bones = armData.bones.values()
+       bones = armData.getBones()
+
        def getBone(bonename):
                bone = None
                for b in bones:
                        #print b.getName()
-                       if b.name == bonename:
+                       if b.getName() == bonename:
                                bone = b
                return bone
 
@@ -366,35 +328,24 @@ def f_createBone (armData, empty, bone, empties):
                        bonename = empty.getName()[1:len(empty.getName())]
                #b=Blender.Armature.Bone.New(bonename)
                b=getBone(bonename)
-               b.head = (computeScaledPos(empty.getMatrix('worldspace').translationPart()))
-               b.tail = (computeScaledPos(ch.getMatrix('worldspace').translationPart()))
-               b.parent = bone
                #b.setHead(empty.getMatrix('worldspace').translationPart())
                #b.setTail(ch.getMatrix('worldspace').translationPart())
                #b.setParent(bone)
-##             matrice = empty.getMatrix('worldspace')
-##             invmatrice = empty.getMatrix('worldspace')
-##             invmatrice.invert()
-##             invmatricet=empty.getMatrix('worldspace')
-##             invmatricet.invert()
-##             invmatricet.transpose()
-##             dicEmptiesRestMatrix[empty.getName()] = matrice
-##             dicEmptiesInvRestMatrix[empty.getName()] = invmatrice
-##             #armature.addBone(b)
-##             #invbonerest=b.getRestMatrix()
-##             #invbonerest.invert()
-##             invbonerest=Blender.Mathutils.Matrix(b.matrix)
-##             invbonerest.resize4x4()
-##             invbonerest[3][3]=1.0
-##             invbonerest.invert()
-##             #dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
-##             tmpmat = b.matrix.resize4x4()
-##             tmpmat[3][3] = 1.0
-##             dicBoneRestMatrix[b.name] = tmpmat
-##
-##             dicBoneRestInvEmpRest[b.name]=tmpmat*invmatrice*invmatricet
-##             dicEmpRestInvBoneRest[b.name]=matrice*invbonerest
-               dicBone[b.name]=b
+               matrice = empty.getMatrix('worldspace')
+               invmatrice = empty.getMatrix('worldspace')
+               invmatrice.invert()
+               invmatricet=empty.getMatrix('worldspace')
+               invmatricet.invert()
+               invmatricet.transpose()
+               dicEmptiesRestMatrix[empty.getName()] = matrice
+               dicEmptiesInvRestMatrix[empty.getName()] = invmatrice
+               #armature.addBone(b)
+               invbonerest=b.getRestMatrix()
+               invbonerest.invert()
+               dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
+               dicBoneRestInvEmpRest[b.getName()]=b.getRestMatrix()*invmatrice*invmatricet
+               dicEmpRestInvBoneRest[b.getName()]=matrice*invbonerest
+               dicBone[b.getName()]=b
                #print "Ajout de ", b.getName(),"  au dictionnaire"
                f_createBone(armData, ch, b, empties)
        
@@ -404,55 +355,29 @@ def f_createBone (armData, empty, bone, empties):
 # in  : 
 # out : 
 #########
-def createArmature (armObj, rootEmpty, empties):
-       armData=Blender.Armature.Armature('monArmature')
+def createArmature (rootEmpty, empties):
+       armData=Blender.Armature.New('monArmature')
        children = getChildren(rootEmpty, empties)
-       armObj.link(armData)
-       armData.makeEditable()
        for ch in children:
-               b=Blender.Armature.Editbone()
-               bonename = rootEmpty.getName()[1:len(rootEmpty.getName())] + ch.getName()[1:len(ch.getName())]
-               print "creating Bone %s"%(bonename)
-
-               #print b, dir([b])
-               b.head=(computeScaledPos(rootEmpty.getMatrix('worldspace').translationPart()))
-               b.tail=(computeScaledPos(ch.getMatrix('worldspace').translationPart()))
-               armData.bones[bonename] = b
-               #armData.update()
-               #armData.addBone(b)
-               #matrice = ch.getMatrix('worldspace')
-               #print dir (ch.matrix)
-##             matrice = Blender.Mathutils.Matrix(ch.getMatrix('worldspace'))
-##             matrice.resize4x4()
-##             matrice[3][3]=1.0
-##             #print matrice
-##             #eval("invmatrice = Blender.Mathutils.Matrix(ch.getMatrix('worldspace'))" ) #??
-##             invmatrice = Blender.Mathutils.Matrix(ch.getMatrix('worldspace')) #??
-##             invmatrice.invert()
-##             #invmatrice.resize4x4()
-##             invmatricet= Blender.Mathutils.Matrix(ch.getMatrix('worldspace')) #??
-##             invmatricet.invert()
-##             invmatricet.transpose()
-##             #invmatricet.resize4x4()
-##             dicEmptiesRestMatrix[rootEmpty.getName()] = matrice
-##             dicEmptiesInvRestMatrix[rootEmpty.getName()] = invmatrice
-##             #invbonerest=b.getRestMatrix()
-##             invbonerest=Blender.Mathutils.Matrix(b.matrix)
-##             invbonerest.resize4x4()
-##             invbonerest[3][3]=1.0
-##             invbonerest.invert()
-##             #dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
-##             tmpmat = b.matrix.resize4x4()
-##             tmpmat[3][3] = 1.0
-##             dicBoneRestMatrix[b.name] = tmpmat
-##             #print tmpmat
-##             #print invmatrice
-##             #print invmatricet
-##             dicBoneRestInvEmpRest[b.name]=tmpmat*invmatrice*invmatricet
-##             dicEmpRestInvBoneRest[b.name]=matrice*invbonerest
-##             dicBone[b.name]=b
+               b=Blender.Armature.Bone.New(rootEmpty.getName()[1:len(rootEmpty.getName())] + ch.getName()[1:len(ch.getName())])
+               b.setHead(computeScaledPos(rootEmpty.getMatrix('worldspace').translationPart()))
+               b.setTail(computeScaledPos(ch.getMatrix('worldspace').translationPart()))
+               armData.addBone(b)
+               matrice = ch.getMatrix('worldspace')
+               invmatrice = ch.getMatrix('worldspace')
+               invmatrice.invert()
+               invmatricet=ch.getMatrix('worldspace')
+               invmatricet.invert()
+               invmatricet.transpose()
+               dicEmptiesRestMatrix[rootEmpty.getName()] = matrice
+               dicEmptiesInvRestMatrix[rootEmpty.getName()] = invmatrice
+               invbonerest=b.getRestMatrix()
+               invbonerest.invert()
+               dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
+               dicBoneRestInvEmpRest[b.getName()]=b.getRestMatrix()*invmatrice*invmatricet
+               dicEmpRestInvBoneRest[b.getName()]=matrice*invbonerest
+               dicBone[b.getName()]=b
                createBone(armData, ch, b, empties)
-       armData.update()
        return armData
 
 
@@ -463,43 +388,33 @@ def createArmature (armObj, rootEmpty, empties):
 # out : 
 #########
 def f_createArmature (rootEmpty, empties, armData):
-       armData.makeEditable()
-       bones = armData.bones.values()
-       
+       bones = armData.getBones()
 
        def getBone(bonename):
                bone = None
                for b in bones:
                        #print b.getName()
-                       if b.name == bonename:
+                       if b.getName() == bonename:
                                bone = b
                return bone
 
        children = getChildren(rootEmpty, empties)
        for ch in children:
                b=getBone(rootEmpty.getName()[1:len(rootEmpty.getName())] + ch.getName()[1:len(ch.getName())])
-##             matrice = Blender.Mathutils.Matrix(ch.getMatrix('worldspace'))
-##             invmatrice = Blender.Mathutils.Matrix(ch.getMatrix('worldspace'))
-##             invmatrice.invert()
-##             invmatricet=Blender.Mathutils.Matrix(ch.getMatrix('worldspace'))
-##             invmatricet.invert()
-##             invmatricet.transpose()
-##             dicEmptiesRestMatrix[rootEmpty.getName()] = matrice
-##             dicEmptiesInvRestMatrix[rootEmpty.getName()] = invmatrice
-##             print b.matrix
-##             invbonerest=Blender.Mathutils.Matrix(b.matrix)
-##             invbonerest.resize4x4()
-##             invbonerest[3][3] = 1.0
-##             invbonerest.invert()
-##             #dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
-##             #dicBoneRestMatrix[b.name] = b.matrix
-##             tmpmat = b.matrix.resize4x4()
-##             tmpmat[3][3] = 1.0
-##             dicBoneRestMatrix[b.name] = tmpmat
-##             
-##             dicBoneRestInvEmpRest[b.name]=tmpmat*invmatrice*invmatricet
-##             dicEmpRestInvBoneRest[b.name]=matrice*invbonerest
-               dicBone[b.name]=b
+               matrice = ch.getMatrix('worldspace')
+               invmatrice = ch.getMatrix('worldspace')
+               invmatrice.invert()
+               invmatricet=ch.getMatrix('worldspace')
+               invmatricet.invert()
+               invmatricet.transpose()
+               dicEmptiesRestMatrix[rootEmpty.getName()] = matrice
+               dicEmptiesInvRestMatrix[rootEmpty.getName()] = invmatrice
+               invbonerest=b.getRestMatrix()
+               invbonerest.invert()
+               dicBoneRestMatrix[b.getName()] = b.getRestMatrix()
+               dicBoneRestInvEmpRest[b.getName()]=b.getRestMatrix()*invmatrice*invmatricet
+               dicEmpRestInvBoneRest[b.getName()]=matrice*invbonerest
+               dicBone[b.getName()]=b
                #print "Ajout de ", b.getName(),"  au dictionnaire"
                
                f_createBone(armData, ch, b, empties)
@@ -520,8 +435,8 @@ def moveBones(armature, empty, empties):
                        bonename = empty.getName()[1:len(empty.getName())]
                bone = dicBone[bonename]
                #bone.setLoc(computeRootPos(empty,bone))
-               #???? what can replace bone.setLoc(computeRelativePos(empty,bone))
-               #???? what can replace bone.setQuat(computeRootQuat2(empty,bone))
+               bone.setLoc(computeRelativePos(empty,bone))
+               bone.setQuat(computeRootQuat2(empty,bone))
                chch = dicEmptyChild[ch.getName()]
                if len(chch) >= 1:
                        moveBones(armature, ch, empties)
@@ -538,11 +453,20 @@ def moveArmature (armature, empties):
        for ch in children:
                b=dicBone[hipbonename[1:len(hipbonename)] + ch.getName()[1:len(ch.getName())]]
                #b.setLoc(computeRootPos(root, b))
-               #???? what can replace b.setLoc([0.0, 0.0, 0.0])
-               #???? what can replace b.setQuat(computeRootQuat2(root, b))
+               b.setLoc([0.0, 0.0, 0.0])
+               b.setQuat(computeRootQuat2(root, b))
                moveBones(armature, ch, empties)
 
 
+def eraseIPO (objectname):
+       object = Blender.Object.Get(objectname)
+       lIpo = object.getIpo()
+       if lIpo != None:
+               nbCurves = lIpo.getNcurves()
+               for i in range(nbCurves):
+                       nbBezPoints = lIpo.getNBezPoints(i)
+                       for j in range(nbBezPoints):
+                               lIpo.delBezPoint(i)
 
 
 ########################################################################
@@ -588,7 +512,7 @@ def Main():
 
        lesEmpties = getEmpties()
        #print dicEmptyChild    
-       print "creating armature"
+
        #armData = createArmature(em0, lesEmpties)
        objects = Blender.Object.Get()
        if 'OBArmature' in map(names,objects):
@@ -599,15 +523,15 @@ def Main():
                #print armData.getBones()
                f_createArmature(em0, lesEmpties, armData)
        else:
+               armData= createArmature(em0, lesEmpties)
                armObj=Blender.Object.New('Armature', 'OBArmature')
-               armData= createArmature(armObj, em0, lesEmpties)
-               #armObj.link(armData)
+               armObj.link(armData)
                scn = Blender.Scene.getCurrent()
                scn.link (armObj)
 
                print 'OBArmature'+' was created'
        #return myobj
-       armData.drawType = Blender.Armature.STICK 
        ##-----------
        ## Creation de l'ipo de l'armature
        ##-----------
@@ -616,11 +540,7 @@ def Main():
        curvX =  GetOrCreateCurve(lipo, 'LocX')
        curvY =  GetOrCreateCurve(lipo, 'LocY')
        curvZ =  GetOrCreateCurve(lipo, 'LocZ')
-       curvrX =  GetOrCreateCurve(lipo, 'RotX')
-       curvrY =  GetOrCreateCurve(lipo, 'RotY')
-       curvrZ =  GetOrCreateCurve(lipo, 'RotZ')
 
-       print "animating armature"
 
        #armData.drawAxes(1)
        #armData.drawNames(1)
@@ -633,9 +553,9 @@ def Main():
        ## Enregistrement de la position  de l'armature
        ##-----------
 
-       bones = armData.bones.values()
-       #??? for bo in bones:
-       #???    bo.setPose([Blender.Armature.Bone.ROT, Blender.Armature.Bone.LOC]) 
+       bones = armData.getBones()
+       for bo in bones:
+               bo.setPose([Blender.Armature.Bone.ROT, Blender.Armature.Bone.LOC]) 
 
        curvX.addBezier((Blender.Get("curframe"), getEmpty(hipbonename).getMatrix('worldspace').translationPart()[0]*scalef))
        curvY.addBezier((Blender.Get("curframe"), getEmpty(hipbonename).getMatrix('worldspace').translationPart()[1]*scalef))
@@ -646,12 +566,6 @@ def Main():
        curvY.setExtrapolation('Constant')
        curvZ.setInterpolation('Linear')
        curvZ.setExtrapolation('Constant')
-       curvrX.setInterpolation('Linear')
-       curvrX.setExtrapolation('Constant')
-       curvrY.setInterpolation('Linear')
-       curvrY.setExtrapolation('Constant')
-       curvrZ.setInterpolation('Linear')
-       curvrZ.setExtrapolation('Constant')
 
        Blender.Redraw()
 
@@ -662,21 +576,18 @@ def Main():
                ## Positionnement des os
                ##-----------
 
-               #moveArmature(armData, lesEmpties)
+               moveArmature(armData, lesEmpties)
 
 
                ##-----------
                ## Enregistrement de la position  de l'armature
                ##-----------
 
-               # ???? for bo in bones:
-               # ????  bo.setPose([Blender.Armature.Bone.ROT, Blender.Armature.Bone.LOC]) 
+               for bo in bones:
+                       bo.setPose([Blender.Armature.Bone.ROT, Blender.Armature.Bone.LOC]) 
                curvX.addBezier((Blender.Get("curframe"), (getEmpty(hipbonename).getMatrix('worldspace').translationPart()[0])*scalef))
                curvY.addBezier((Blender.Get("curframe"), (getEmpty(hipbonename).getMatrix('worldspace').translationPart()[1])*scalef))
                curvZ.addBezier((Blender.Get("curframe"), (getEmpty(hipbonename).getMatrix('worldspace').translationPart()[2])*scalef))
-               curvrX.addBezier((Blender.Get("curframe"), (getEmpty(hipbonename).getMatrix('worldspace').rotationPart().toEuler()[0])*scalef/10))
-               curvrY.addBezier((Blender.Get("curframe"), (getEmpty(hipbonename).getMatrix('worldspace').rotationPart().toEuler()[1])*scalef/10))
-               curvrZ.addBezier((Blender.Get("curframe"), (getEmpty(hipbonename).getMatrix('worldspace').rotationPart().toEuler()[2])*scalef/10))
 
                ##-----------
                ## Passage a la frame suivante
@@ -685,12 +596,6 @@ def Main():
                print num_frame
                Blender.Set("curframe", num_frame)
 
-       curvX.Recalc()
-       curvY.Recalc()
-       curvZ.Recalc()
-       curvrX.Recalc()
-       curvrY.Recalc()
-       curvrZ.Recalc()
        Blender.Set("curframe",startframe)
        Blender.Redraw()
 
@@ -722,11 +627,11 @@ def button_event(evt):
        global endframe, startframe, insertionframe, hipbonename, framedecimation , scalef
        if evt==1:
                startframe = SFrame2.val
-               insertionframe = 100 #IFrame.val
+               insertionframe = IFrame.val
                endframe =  EFrame.val
                hipbonename = HBName.val
                framedecimation = FrameDecimation.val
-               scalef= 1.0 #eval(str(ScaleF.val))
+               scalef= eval(str(ScaleF.val))
                #print "scalef = ", scalef
                if startframe>=endframe:
                        Msg = 'Start frame must be lower than End frame'
@@ -741,7 +646,6 @@ def button_event(evt):
                                        else:
                                                #Blender.Draw.Exit()
                                                Main()
-                               #Main()
                        else:
                                Msg = 'Empty '+ hipbonename+ ' not found'
                                
@@ -767,18 +671,13 @@ def GUI():
        Blender.BGL.glClear(Blender.BGL.GL_COLOR_BUFFER_BIT)
        Blender.BGL.glColor3f(1,1,1)
        Blender.BGL.glRasterPos2i(20,200)
-       selobj = Blender.Object.GetSelected()
-       if len(selobj) == 1 and type (selobj[0]) == Blender.Types.ObjectType:
-               hipname = selobj[0].getName()
-       else:
-               hipname = '_Hips'
-       Blender.Draw.Text ("BVH 2 ARMATURE v%s by %s"%(__version__, __author__), 'normal')
-       HBName = Blender.Draw.String("HipBoneName: ", 0, 20, 175, 250, 20, hipname, 100)
+       Blender.Draw.Text ("BVH 2 ARMATURE v2.2 by Jean-Baptiste PERIN", 'normal')
+       HBName = Blender.Draw.String("HipBoneName: ", 0, 20, 175, 250, 20, '_Hips', 100)
        SFrame2 = Blender.Draw.Number("Startframe: ", 0, 20, 150, 250, 20, 1, 1,3000,"Start frame of anim")
        EFrame = Blender.Draw.Number("Endframe: ", 0, 20, 125, 250, 20, Blender.Get("endframe"), 1,3000,"Last frame of anim")
        #IFrame = Blender.Draw.Number("Insertionframe: ", 0, 20, 100, 250, 20, Blender.Get("staframe"), 1,3000,"")
-       FrameDecimation = Blender.Draw.Number("FrameDecimation: ", 0, 20, 75, 250, 20,1, 1,10,'number of frame to skip between two action keys')
-#      ScaleF = Blender.Draw.Number("Scale: ", 0, 20, 50, 250, 20, 1.0, 0.0, 10.0,  'Scale Factor')
+       FrameDecimation = Blender.Draw.Number("FrameDecimation: ", 0, 20, 75, 250, 20,5, 1,10,'number of frame to skip between two action keys')
+       ScaleF = Blender.Draw.Number("Scale: ", 0, 20, 50, 250, 20, 1.0, 0.0, 10.0,  'Scale Factor')
        Blender.Draw.Toggle("Create Armature", 1, 20, 10, 100, 20, 0, "Create Armature")
        #Blender.Draw.Toggle("Remove Empties", 2, 200, 10, 100, 20, 0, "Remove Empties")
        Blender.BGL.glRasterPos2i(20,40)
index 7c6ac4c7e3613c53e475c8a04a1259e1a76680a9..84425626cee63eb0fb235436a5f4ed95d267c698 100644 (file)
@@ -9,7 +9,7 @@ Tip: 'Export a (.bvh) motion capture file'
 
 __author__ = "Campbell Barton"
 __url__ = ("blender", "elysiun")
-__version__ = "1.1 12/16/05"
+__version__ = "1.0 03/30/04"
 
 __bpydoc__ = """\
 This script exports animation data to BVH motion capture file format.
@@ -30,11 +30,12 @@ Notes:<br>
 # BVH Export script 1.0 by Campbell Barton      #
 # Copyright MetaVR 30/03/2004,                  #
 # if you have any questions about this script   #
-# email me cbarton@metavr.com                   #
+# email me ideasman@linuxmail.org               #
+#                                               #
 #===============================================#
 
 # -------------------------------------------------------------------------- 
-# BVH Export v1.1 by Campbell Barton (AKA Ideasman) 
+# BVH Export v0.9 by Campbell Barton (AKA Ideasman) 
 # -------------------------------------------------------------------------- 
 # ***** BEGIN GPL LICENSE BLOCK ***** 
 # 
@@ -45,12 +46,12 @@ Notes:<br>
 # 
 # This program is distributed in the hope that it will be useful, 
 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 # GNU General Public License for more details. 
 # 
 # You should have received a copy of the GNU General Public License 
 # along with this program; if not, write to the Free Software Foundation, 
-# Inc., 59 Temple Place - Suite 330, Boston, MA        02111-1307, USA. 
+# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 # 
 # ***** END GPL LICENCE BLOCK ***** 
 # -------------------------------------------------------------------------- 
@@ -58,328 +59,348 @@ Notes:<br>
 import Blender
 from Blender import Scene, Object
 import math
-time = Blender.sys.time
 from math import *
 
 # Get the current scene.
 scn = Scene.GetCurrent()
 context = scn.getRenderingContext()
 
-frameRate = 1.0/context.framesPerSec() # 0.04 = 25fps
-scale = 1.0
+frameRate = 0.3333 # 0.04 = 25fps
+scale = 1
 
-indent = '\t' # 2 space indent per object
+indent = '  ' # 2 space indent per object
 prefixDelimiter = '_'
 
 # Vars used in eular rotation funtcion
 RAD_TO_DEG = 180.0/3.14159265359
-DEG_TO_RAD = math.pi/180.0
+
 
 
 #====================================================#
 # Search for children of this object and return them #
 #====================================================#
 def getChildren(parent):
-       children = [] # We'll assume none.
-       for child in Object.Get():
-               if child.parent == parent:
-                       children.append( child )
-       return children
+  children = [] # We'll assume none.
+  for child in Object.Get():
+    if child.getParent() == Object.Get(parent):
+      children.append( child.getName() )
+  return children
 
 #====================================================#
-# MESSY BUT WORKS: Make a string that shows the                        #
-# hierarchy as a list and then eval it                                                  #
+# MESSY BUT WORKS: Make a string that shows the      #
+# hierarchy as a list and then eval it               #
 #====================================================#
 def getHierarchy(root, hierarchy):
-       hierarchy = '%s["%s",' % (hierarchy, root.name)
-       for child in getChildren(root):
-               hierarchy = getHierarchy(child, hierarchy)
-       hierarchy = '%s],' % hierarchy
-       return hierarchy
+  hierarchy = hierarchy + '["' + root + '",'
+  for child in getChildren(root):
+    hierarchy = getHierarchy(child, hierarchy)
+  hierarchy += '],' 
+  return hierarchy
 
 
 #====================================================#
-# Strips the prefix off the name before writing                        #
+# Strips the prefix off the name before writing      #
 #====================================================#
 def stripName(name): # name is a string
-       
-       # WARNING!!! Special case for a custom RIG for output
-       # for MetaVR's HPX compatable RIG.
-       # print 'stripname', name[0:10]
-       if name.lower().startswith('transform('):
-               name = name[10:].split(prefixDelimiter)[0]
-       return name.split('_')[0]
-       
+  
+  # WARNING!!! Special case for a custom RIG for output
+  # for MetaVR's HPX compatable RIG.
+  print 'stripname', name[0:10]
+  if name[0:10] == 'Transform(':
+    name = name[10:]
+    while name[-1] != ')':
+      name = name[0:-1]
+      print name
+    name = name[:-1]
+  
+  
+  return name[1+name.find(prefixDelimiter): ]
+  
+
+#====================================================#
+# Return a 6 deciaml point floating point value      #
+# as a string that dosent have any python chars      #
+#====================================================#  
+def saneFloat(float):
+  #return '%(float)b' % vars()  # 6 fp as house.hqx
+  return str('%f' % float) + ' '
+
+
 
 #====================================================#
 # Recieves an object name, gets all the data for that#
 # node from blender and returns it for formatting    #
 # and writing to a file.                             #
 #====================================================#
-def getNodeData(nodeOb):       
-       ob = nodeOb
-       obipo = ob.getIpo()
-       # Get real location     
-       offset = [o*scale for o in ob.getLocation()]
-       
-       #=========================#
-       # Test for X/Y/Z IPO's          #
-       #=========================#
-       
-       # IF we dont have an IPO then dont check the curves.
-       # This was added to catch end nodes that never have an IPO, only an offset.
-       
-       # DUMMY channels xloc, yloc, zloc, xrot, yrot, zrot
-       # [<bool>, <bool>, <bool>, <bool>, <bool>, <bool>]
-       channels = [0,0,0,0,0,0] # xloc,yloc,zloc,xrot,yrot,zrot
-       if obipo != None: # Do have an IPO, checkout which curves are in use.
-               # Assume the rot's/loc's dont exist until they proven they do.
-               if obipo.getCurve('LocX') != None:
-                       channels[0] = 1
-               if obipo.getCurve('LocY') != None:
-                       channels[1] = 1
-               if obipo.getCurve('LocZ') != None:
-                       channels[2] = 1
-                       
-               # Now for the rotations, Because of the conversion of rotation coords
-               # if there is one rotation er need to store all 3
-               if obipo.getCurve('RotX') != None or \
-               obipo.getCurve('RotY') != None or \
-               obipo.getCurve('RotZ') != None:
-                       channels[3] = channels[4] = channels[5] = 1
-       #print ob, channels
-       return offset, channels
+def getNodeData(nodeName):  
+  Object.Get(nodeName)
+  # Get real location  
+  offset = Object.Get(nodeName).getLocation()
+  offset = (offset[0]*scale, offset[1]*scale, offset[2]*scale,)
+  
+  #=========================#
+  # Test for X/Y/Z IPO's    #
+  #=========================#
+  obipo = Object.Get(nodeName).getIpo()
+  
+  # IF we dont have an IPO then dont check the curves.
+  # This was added to catch end nodes that never have an IPO, only an offset.
+  if obipo == None: 
+    xloc=yloc=zloc=xrot=yrot=zrot = 0
+  
+  else: # Do have an IPO, checkout which curves are in use.
+    # Assume the rot's/loc's exist until proven they dont
+    xloc=yloc=zloc=xrot=yrot=zrot = 1
+    if obipo.getCurve('LocX') == None:
+      xloc = 0
+    if obipo.getCurve('LocY') == None:
+      yloc = 0
+    if obipo.getCurve('LocZ') == None:
+      zloc = 0
+      
+    # Now for the rotations, Because of the conversion of rotation coords
+    # if there is one rotation er need to store all 3
+    if obipo.getCurve('RotX') == None and \
+    obipo.getCurve('RotY') == None and \
+    obipo.getCurve('RotZ') == None:
+      xrot=yrot=zrot = 0
+  
+  # DUMMY channels xloc, yloc, zloc, xrot, yrot, zrot
+  # [<bool>, <bool>, <bool>, <bool>, <bool>, <bool>]
+  channels = [xloc, yloc, zloc, xrot, yrot, zrot]
+  
+  return offset, channels
 
 
 #====================================================#
-# Writes the BVH hierarchy to a file                 #
+# Return the BVH hierarchy to a file from a list     #
 # hierarchy: is a list of the empty hierarcht        #
+# bvhHierarchy: a string, in the bvh format to write #
 # level: how many levels we are down the tree,       #
 # ...used for indenting                              #
 # Also gathers channelList , so we know the order to #
-# write        the motiondata in                            #
+# write  the motiondata in                           #
 #====================================================#
-def hierarchy2bvh(file, hierarchy, level, channelList, nodeObjectList):
-       nodeName = hierarchy[0]
-       ob = Object.Get(nodeName)
-       '''
-       obipo = ob.getIpo()
-       if obipo != None:
-               obcurves = obipo.getCurves()
-       else:
-               obcurves = None
-       '''
-       #============#
-       # JOINT NAME #
-       #============# 
-       file.write(level * indent)
-       if level == 0:
-               # Add object to nodeObjectList
-               #nodeObjectList.append( (ob, obipo, obcurves) )
-               nodeObjectList.append( ob )
-               file.write( 'ROOT %s\n' % stripName(nodeName) )
-       # If this is the last object in the list then we
-       # dont bother withwriting its real name, use "End Site" instead
-       elif len(hierarchy) == 1:
-               file.write( 'End Site\n' )
-       # Ok This is a normal joint
-       else:
-               # Add object to nodeObjectList
-               #nodeObjectList.append((ob, obipo, obcurves))
-               nodeObjectList.append( ob )
-               file.write( 'JOINT %s\n' % stripName(nodeName) )
-       #================#
-       # END JOINT NAME #
-       #================#
-       
-       # Indent again, this line is just for the brackets
-       file.write( '%s{\n' % (level * indent) )
-
-       # Indent
-       level += 1
-       
-       #================================================#
-       # Data for writing to a file offset and channels #
-       #================================================#
-       offset, channels = getNodeData(ob)
-       
-       #============#
-       # Offset     #
-       #============# 
-       file.write( '%sOFFSET %.6f %.6f %.6f\n' %\
-       (level*indent, scale*offset[0], scale*offset[1], scale*offset[2]) )
-       
-       #============#
-       # Channels   #
-       #============# 
-       if len(hierarchy) != 1:
-               # Channels, remember who is where so when we write motiondata
-               file.write('%sCHANNELS %i ' % (level*indent, len([c for c in channels if c ==1]) ))
-               if channels[0]:
-                       file.write('Xposition ')
-                       channelList.append([len(nodeObjectList)-1, 0])
-               if channels[1]:
-                       file.write('Yposition ')
-                       channelList.append([len(nodeObjectList)-1, 1])
-               if channels[2]:
-                       file.write('Zposition ')
-                       channelList.append([len(nodeObjectList)-1, 2])
-               if channels[5]:
-                       file.write('Zrotation ')
-                       channelList.append([len(nodeObjectList)-1, 5])
-               if channels[3]:
-                       file.write('Xrotation ')
-                       channelList.append([len(nodeObjectList)-1, 3])
-               if channels[4]:
-                       file.write('Yrotation ')
-                       channelList.append([len(nodeObjectList)-1, 4])
-               file.write('\n')
-
-       # Loop through children if any and run this function (recursively)
-       for hierarchyIdx in range(len(hierarchy)-1):
-               level = hierarchy2bvh(file, hierarchy[hierarchyIdx+1], level, channelList, nodeObjectList)
-       # Unindent
-       level -= 1
-       file.write('%s}\n' % (level * indent))
-       
-       return level
+def hierarchy2bvh(hierarchy, bvhHierarchy, level, channelList, nodeObjectList):
+  nodeName = hierarchy[0]
+  
+  # Add object to nodeObjectList
+  nodeObjectList.append(Object.Get(nodeName))
+  
+  #============#
+  # JOINT NAME #
+  #============# 
+  bvhHierarchy += level * indent
+  if level == 0:
+    # Add object to nodeObjectList
+    nodeObjectList.append(Object.Get(nodeName))
+    bvhHierarchy+= 'ROOT '
+    bvhHierarchy += stripName(nodeName) + '\n'
+  # If this is the last object in the list then we
+  # dont bother withwriting its real name, use "End Site" instead
+  elif len(hierarchy) == 1:
+    bvhHierarchy+= 'End Site\n'
+  # Ok This is a normal joint
+  else:
+    # Add object to nodeObjectList
+    nodeObjectList.append(Object.Get(nodeName))
+    bvhHierarchy+= 'JOINT '
+    bvhHierarchy += stripName(nodeName) + '\n'
+  #================#
+  # END JOINT NAME #
+  #================# 
+
+  # Indent again, this line is just for the brackets
+  bvhHierarchy += level * indent + '{' + '\n'
+
+  # Indent
+  level += 1   
+  
+  #================================================#
+  # Data for writing to a file offset and channels #
+  #================================================#
+  offset, channels = getNodeData(nodeName)
+  
+  #============#
+  # Offset     #
+  #============# 
+  bvhHierarchy += level * indent + 'OFFSET ' + saneFloat(scale * offset[0]) + ' '  + saneFloat(scale * offset[1]) + ' ' + saneFloat(scale * offset[2]) + '\n'
+  
+  #============#
+  # Channels   #
+  #============# 
+  if len(hierarchy) != 1:
+    # Channels, remember who is where so when we write motiondata
+    bvhHierarchy += level * indent + 'CHANNELS '
+    # Count the channels
+    chCount = 0
+    for chn in channels:
+      chCount += chn
+    bvhHierarchy += str(chCount) + ' '
+    if channels[0]:
+      bvhHierarchy += 'Xposition '
+      channelList.append([len(nodeObjectList)-1, 0])
+    if channels[1]:
+      bvhHierarchy += 'Yposition '
+      channelList.append([len(nodeObjectList)-1, 1])
+    if channels[2]:
+      bvhHierarchy += 'Zposition '
+      channelList.append([len(nodeObjectList)-1, 2])
+    if channels[5]:
+      bvhHierarchy += 'Zrotation '
+      channelList.append([len(nodeObjectList)-1, 5])
+    if channels[3]:
+      bvhHierarchy += 'Xrotation '
+      channelList.append([len(nodeObjectList)-1, 3])
+    if channels[4]:
+      bvhHierarchy += 'Yrotation '
+      channelList.append([len(nodeObjectList)-1, 4])
+    
+    bvhHierarchy += '\n'
+
+  # Loop through children if any and run this function (recursively)
+  for hierarchyIdx in range(len(hierarchy)-1):
+    bvhHierarchy, level, channelList, nodeObjectList = hierarchy2bvh(hierarchy[hierarchyIdx+1], bvhHierarchy, level, channelList, nodeObjectList)
+  # Unindent
+  level -= 1
+  bvhHierarchy += level * indent + '}' + '\n'
+  
+  return bvhHierarchy, level, channelList, nodeObjectList
 
 # added by Ben Batt 30/3/2004 to make the exported rotations correct
 def ZYXToZXY(x, y, z):
-       '''
-       Converts a set of Euler rotations (x, y, z) (which are intended to be
-       applied in z, y, x order, into a set which are intended to be applied in
-       z, x, y order (the order expected by .bvh files)
-       '''
-       A,B = cos(x),sin(x)
-       C,D = cos(y),sin(y)
-       E,F = cos(z),sin(z)
-
-       x = asin(-B*C)
-       y = atan2(D, A*C)
-       z = atan2(-B*D*E + A*F, B*D*F + A*E)
-
-       # this seems to be necessary - not sure why (right/left-handed coordinates?)
-       # x = -x # x is negative, see below.
-       return -x*RAD_TO_DEG, y*RAD_TO_DEG, z*RAD_TO_DEG
-
-
-''' # UNUSED, JUST GET OBJECT LOC/ROT
-def getIpoLocation(object, obipo, curves, frame):
-       x =     y = z = rx = ry = rz =0
-       if obipo:
-               for i in range(obipo.getNcurves()):
-                       if curves[i].getName() =='LocX':
-                               x = obipo.EvaluateCurveOn(i,frame)
-                       elif curves[i].getName() =='LocY':
-                               y = obipo.EvaluateCurveOn(i,frame)
-                       elif curves[i].getName() =='LocZ':
-                               z = obipo.EvaluateCurveOn(i,frame)
-                       elif curves[i].getName() =='RotX':
-                               rx = obipo.EvaluateCurveOn(i,frame)
-                       elif curves[i].getName() =='RotY':
-                               ry = obipo.EvaluateCurveOn(i,frame)
-                       elif curves[i].getName() =='RotZ':
-                               rz = obipo.EvaluateCurveOn(i,frame)
-       return x, y, z, rx*10*DEG_TO_RAD, ry*10*DEG_TO_RAD, rz*10*DEG_TO_RAD
-'''
+  '''
+  Converts a set of Euler rotations (x, y, z) (which are intended to be
+  applied in z, y, x order) into a set which are intended to be applied in
+  z, x, y order (the order expected by .bvh files)
+  '''
+  A,B = cos(x),sin(x)
+  C,D = cos(y),sin(y)
+  E,F = cos(z),sin(z)
+
+  x = asin(-B*C)
+  y = atan2(D, A*C)
+  z = atan2(-B*D*E + A*F, B*D*F + A*E)
+
+  # this seems to be necessary - not sure why (right/left-handed coordinates?)
+  x = -x
+  return x*RAD_TO_DEG, y*RAD_TO_DEG, z*RAD_TO_DEG
+
+
+
+def getIpoLocation(object, frame):
+  x =  y = z = 0 
+  obipo = object.getIpo()
+  for i in range(object.getIpo().getNcurves()):
+    if obipo.getCurves()[i].getName() =='LocX':
+      x = object.getIpo().EvaluateCurveOn(i,frame)
+    elif obipo.getCurves()[i].getName() =='LocY':
+      y = object.getIpo().EvaluateCurveOn(i,frame)
+    elif obipo.getCurves()[i].getName() =='LocZ':
+      z = object.getIpo().EvaluateCurveOn(i,frame)
+  return x, y, z
+
 
 #====================================================#
 # Return the BVH motion for the spesified frame      #
 # hierarchy: is a list of the empty hierarcht        #
+# bvhHierarchy: a string, in the bvh format to write #
 # level: how many levels we are down the tree,       #
 # ...used for indenting                              #
 #====================================================#
-def motion2bvh(file, frame, chennelList, nodeObjectList):      
-       for chIdx in chennelList:
-               #ob, obipo, obcurves = nodeObjectList[chIdx[0]]
-               ob = nodeObjectList[chIdx[0]]
-               chType = chIdx[1]
-               
-               # Get object rotation
-               x, y, z = ob.getEuler()
-               
-               # Convert the rotation from ZYX order to ZXY order
-               x, y, z = ZYXToZXY(x, y, z)
-               
-               # Location
-               xloc, yloc, zloc = ob.matrixLocal[3][:3]
-               
-               # Using regular Locations stuffs upIPO locations stuffs up
-               # Get IPO locations instead
-               #xloc, yloc, zloc, x, y, z = getIpoLocation(ob, obipo, obcurves, frame)
-               # Convert the rotation from ZYX order to ZXY order
-               #x, y, z = ZYXToZXY(x, y, z)
-               
-               
-               # WARNING non standard Location
-               # xloc, zloc, yloc = -xloc, yloc, zloc
-               
-               if chType == 0:
-                       file.write('%.6f ' % (scale * xloc))
-               if chType == 1:
-                       file.write('%.6f ' % (scale * yloc))
-               if chType == 2:
-                       file.write('%.6f ' % (scale * zloc))
-               if chType == 3:
-                       file.write('%.6f ' % x)
-               if chType == 4:
-                       file.write('%.6f ' % y)
-               if chType == 5:
-                       file.write('%.6f ' % z)
-       file.write('\n')
-       
+def motion2bvh(frame, chennelList, nodeObjectList):
+  
+  motionData = '' # We'll append the frames to the string.
+  
+  for chIdx in chennelList:
+    ob = nodeObjectList[chIdx[0]]
+    chType = chIdx[1]
+    
+    # Get object rotation
+    x, y, z = ob.getEuler()
+    
+    # Convert the rotation from ZYX order to ZXY order
+    x, y, z = ZYXToZXY(x, y, z)
+     
+    
+    # Using regular Locations stuffs upIPO locations stuffs up
+    # Get IPO locations instead
+    xloc, yloc, zloc = getIpoLocation(ob, frame)
+
+    # WARNING non standard Location
+    xloc, zloc, yloc = -xloc, yloc, zloc
+    
+
+    if chType == 0:
+      motionData += saneFloat(scale * (xloc))
+    if chType == 1:
+      motionData += saneFloat(scale * (yloc))
+    if chType == 2:
+      motionData += saneFloat(scale * (zloc))      
+    if chType == 3:
+      motionData += saneFloat(x)
+    if chType == 4:
+      motionData += saneFloat(y)
+    if chType == 5:
+      motionData += saneFloat(z)
+    
+    motionData += ' '
+     
+  motionData += '\n'
+  return motionData
 
 def saveBVH(filename):
-       t = time()
-       if not filename.lower().endswith('.bvh'):
-               filename += '.bvh' # for safety
-       
-       # Here we store a serialized list of blender objects as they appier
-       # in the hierarchy, this is refred to when writing motiondata
-       nodeObjectList = []
-       
-       # In this list we store a 2 values for each node
-       # 1) An index pointing to a blender object
-       # in objectList
-       # 2) The type if channel x/y/z rot:x/y/z - Use 0-5 to indicate this
-       chennelList = []
-       
-       print '\nBVH  1.1 by Campbell Barton (Ideasman) - cbarton@metavr.com'
-       
-       # Get the active object and recursively traverse its kids to build
-       # the BVH hierarchy, then eval the string to make a hierarchy list.
-       hierarchy = eval(getHierarchy(scn.getActiveObject(),''))[0] # somhow this returns a tuple with one list in it.
-       
-       # Put all data in the file we have selected file.
-       file = open(filename, "w")
-       file.write('HIERARCHY\n') # all bvh files have this on the first line
-       
-       # Write the whole hirarchy to a list
-       level = 0 # Indenting level, start with no indent
-       level = hierarchy2bvh(file, hierarchy, level, chennelList, nodeObjectList)
-       
-       #====================================================#
-       # MOTION: Loop through the frames ande write out     #
-       # the motion data for each                           #
-       #====================================================#
-       # Do some basic motion file header stuff
-       file.write( 'MOTION\n' )
-       file.write( 'Frames: %i\n'      % ( 1 + context.endFrame() - context.startFrame() ) )
-       file.write( 'Frame Time: %.6f\n' % frameRate )
-       
-       frames = range(context.startFrame()+1, context.endFrame()+1)
-       print 'exporting %i of motion...' % len(frames)
-       
-       for frame in frames:
-               context.currentFrame(frame)
-               scn.update(1) # Update locations so we can write the new locations. This is the SLOW part.
-               # Blender.Window.RedrawAll() # Debugging.
-               
-               motion2bvh(file, frame, chennelList, nodeObjectList) # Write the motion to a file.
-       
-       file.write('\n') # newline
-       file.close()
-       print '...Done in %.4f seconds.' % (time()-t)
-       
+
+  if filename.find('.bvh', -4) <= 0: filename += '.bvh' # for safety
+
+  # Here we store a serialized list of blender objects as they appier
+  # in the hierarchy, this is refred to when writing motiondata
+  nodeObjectList = []
+  
+  # In this list we store a 2 values for each node
+  # 1) An index pointing to a blender object
+  # in objectList
+  # 2) The type if channel x/y/z rot:x/y/z - Use 0-5 to indicate this
+  chennelList = []
+  
+  print ''
+  print 'BVH  1.0 by Campbell Barton (Ideasman) - ideasman@linuxmail.org'
+  
+  # Get the active object and recursively traverse its kids to build
+  # the BVH hierarchy, then eval the string to make a hierarchy list.
+  hierarchy = eval(getHierarchy(Object.GetSelected()[0].getName(),''))[0] # somhow this returns a tuple with one list in it.
+  
+  # Put all data in the file we have selected file.
+  file = open(filename, "w")
+  file.write('HIERARCHY\n') # all bvh files have this on the first line
+  
+  # Write the whole hirarchy to a list
+  bvhHierarchy, level, chennelList, nodeObjectList = hierarchy2bvh(hierarchy, '', 0, chennelList, nodeObjectList)
+  file.write( bvhHierarchy ) # Rwite the var fileBlock to the output.
+  bvhHierarchy = None # Save a tit bit of memory
+  
+  #====================================================#
+  # MOTION: Loop through the frames ande write out     #
+  # the motion data for each                           #
+  #====================================================#
+  # Do some basic motion file header stuff
+  file.write('MOTION\n')
+  file.write( 'Frames: ' + str(1 + context.endFrame() - context.startFrame()) + '\n'  )
+  file.write( 'Frame Time: ' + saneFloat(frameRate) + '\n'  ) 
+  
+  #print 'WARNING- exact frames might be stuffed up- inclusive whatever, do some tests later on.'
+  frames = range(context.startFrame(), context.endFrame()+1)
+  print 'exporting ' + str(len(frames)) + ' of motion...'
+  
+  for frame in frames:
+    context.currentFrame(frame)
+    scn.update(1) # Update locations so we can write the new locations
+    #Blender.Window.RedrawAll() # causes crash
+    
+    file.write(  motion2bvh(frame, chennelList, nodeObjectList)  )
+     
+  file.write('\n') # newline
+  file.close()
+  print 'done'
+  
 Blender.Window.FileSelector(saveBVH, 'Export BVH')
index 05f40f018dc71af8ba678816eb70908bba8362ab..17ce01c0cabc871001c9d1b19a5c3d736c3601ef 100644 (file)
@@ -2,14 +2,14 @@
 
 """
 Name: 'Motion Capture (.bvh)...'
-Blender: 239
+Blender: 236
 Group: 'Import'
 Tip: 'Import a (.bvh) motion capture file'
 """
 
 __author__ = "Campbell Barton"
-__url__ = ("blender", "elysiun")
-__version__ = "1.0.4 05/12/04"
+__url__ = ("blender", "elysiun", "http://jmsoler.free.fr/util/blenderfile/py/bvh_import.py")
+__version__ = "1.0.2 04/12/28"
 
 __bpydoc__ = """\
 This script imports BVH motion capture data to Blender.
@@ -21,52 +21,32 @@ Missing:<br>
 Known issues:<br>
 
 Notes:<br>
-        Jean-Michel Soler improved importer to support Poser 3.01 files;<br>
-        Jean-Baptiste Perin wrote a script to create an armature out of the
+   Jean-Michel Soler improved importer to support Poser 3.01 files;<br>
+   Jean-Baptiste Perin wrote a script to create an armature out of the
 Empties created by this importer, it's in the Scripts window -> Scripts -> Animation menu.
 """
 
 # $Id$
 #
 
-#===============================================#
-# BVH Import script 1.05 patched by Campbell    #
-# Modified to use Mathutils for matrix math,    #
-# Fixed possible joint naming bug,              #
-# Imports BVH's with bad EOF gracefully         #
-# Fixed duplicate joint names, make them unique #
-# Use \r as well as \n for newlines             #
-# Added suppot for nodes with 0 motion channels #
-# Rotation IPOs never cross more then 180d      #
-#    fixes sub frame tweening and time scaling  #
-# 5x overall speedup.                           #
-# 06/12/2005,                                   #      
-#===============================================#
-
-#===============================================#
-# BVH Import script 1.04 patched by jms         #
-# Small modif for blender 2.40                  #
-# 04/12/2005,                                   #      
-#===============================================#
-
 #===============================================#
 # BVH Import script 1.03 patched by Campbell    #
 # Small optimizations and scale input           #
-# 01/01/2005,                                   #      
+# 01/01/2005,                                   #  
 #===============================================#
 
 #===============================================#
 # BVH Import script 1.02 patched by Jm Soler    #
-# to the Poser 3.01 bvh file                    #
-# 28/12/2004,                                   #      
+# to the Poser 3.01 bvh file                    # 
+# 28/12/2004,                                   #  
 #===============================================#
 
 #===============================================#
 # BVH Import script 1.0 by Campbell Barton      #
 # 25/03/2004, euler rotation code taken from    #
 # Reevan Mckay's BVH import script v1.1         #
-# if you have any questions about this scrip.   #
-# email me cbarton@metavr.com                   #
+# if you have any questions about this script   #
+# email me ideasman@linuxmail.org               #
 #===============================================#
 
 #===============================================#
@@ -77,7 +57,7 @@ Empties created by this importer, it's in the Scripts window -> Scripts -> Anima
 #===============================================#
 
 # -------------------------------------------------------------------------- 
-# BVH Import v1.05 by Campbell Barton (AKA Ideasman) 
+# BVH Import v0.9 by Campbell Barton (AKA Ideasman) 
 # -------------------------------------------------------------------------- 
 # ***** BEGIN GPL LICENSE BLOCK ***** 
 # 
@@ -88,410 +68,457 @@ Empties created by this importer, it's in the Scripts window -> Scripts -> Anima
 # 
 # This program is distributed in the hope that it will be useful, 
 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 # GNU General Public License for more details. 
 # 
 # You should have received a copy of the GNU General Public License 
 # along with this program; if not, write to the Free Software Foundation, 
-# Inc., 59 Temple Place - Suite 330, Boston, MA        02111-1307, USA. 
+# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 # 
 # ***** END GPL LICENCE BLOCK ***** 
 # -------------------------------------------------------------------------- 
 
+
+import string
+import math
 import Blender
 from Blender import Window, Object, Scene, Ipo, Draw
 from Blender.Scene import Render
 
 
-# Attempt to load psyco, speed things up
-try:
-       import psyco
-       psyco.full()    
-       print 'using psyco to speed up BVH importing'
-except:
-       #print 'psyco is not present on this system'
-       pass
-
-
-
-def main():
-       global scale
-       scale = None
-       
-       # Update as we load?
-       debug = 0
-       
-       def getScale():
-               return Draw.PupFloatInput('BVH Scale: ', 0.01, 0.001, 10.0, 0.1, 3)
-       
-       
-       #===============================================#
-       # MAIN FUNCTION - All things are done from here #
-       #===============================================#
-       def loadBVH(filename):
-               global scale
-               print '\nBVH Importer 1.05 by Campbell Barton (Ideasman) - cbarton@metavr.com'
-               
-               objectCurveMapping = {}
-               objectNameMapping = {}
-               objectMotiondataMapping = {}
-               
-               # Here we store the Ipo curves in the order they load.
-               channelCurves = []
-               
-               # Object list
-               # We need this so we can loop through the objects and edit there IPO's 
-               # Chenging there rotation to EULER rotation
-               objectList = []
-               
-               if scale == None:
-                       tempscale = getScale()
-                       if tempscale:
-                               scale = tempscale
-                       else:
-                               scale = 0.01
-               
-               Window.WaitCursor(1)
-               # Unique names, dont reuse any of these names.
-               uniqueObNames = [ob.name for ob in Object.Get()]
-               
-               
-               # FUNCTIONS ====================================#
-               def getUniqueObName(name):
-                       i = 0
-                       newname = name[:min(len(name), 12)] # Concatinate to 12 chars
-                       while newname in uniqueObNames:
-                               newname = name + str(i)
-                               i+=1
-                       return newname
-                       
-               # Change the order rotation is applied.
-               RotationMatrix = Blender.Mathutils.RotationMatrix
-               MATRIX_IDENTITY_3x3 = Blender.Mathutils.Matrix([1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0])
-               def eulerRotate(x,y,z): 
-                       x,y,z = x%360,y%360,z%360 # Clamp all values between 0 and 360, values outside this raise an error.
-                       xmat = RotationMatrix(x,3,'x')
-                       ymat = RotationMatrix(y,3,'y')
-                       zmat = RotationMatrix(z,3,'z')
-                       # Standard BVH multiplication order, apply the rotation in the order Z,X,Y
-                       return (ymat*(xmat * (zmat * MATRIX_IDENTITY_3x3))).toEuler()
-               
-
-               currentFrame = 1 # Set the initial frame to import all data to.
-               
-               #===============================================#
-               # makeJoint: Here we use the node data          #
-               # from the BVA file to create an empty          #
-               #===============================================#
-               BVH2BLEND_TX_NAME = {'Xposition':'LocX','Yposition':'LocY','Zposition':'LocZ','Xrotation':'RotX','Yrotation':'RotY','Zrotation':'RotZ'}
-               def makeJoint(name, parent, offset, channels):
-                       ob = Object.New('Empty', name) # New object, ob is shorter and nicer to use.
-                       
-                       objectNameMapping[name] = ob
-                       scn.link(ob) # place the object in the current scene
-                       ob.sel = 1
-                       
-                       # Make me a child of another empty.
-                       # Vale of None will make the empty a root node (no parent)
-                       if parent[-1]: # != None
-                               obParent = objectNameMapping[parent[-1]] # We use this a bit so refrence it here.
-                               obParent.makeParent([ob], 1, 0) #ojbs, noninverse, 1 = not fast.
-               
-                       # Offset Empty from BVH's initial joint location.
-                       ob.setLocation(offset[0]*scale, offset[1]*scale, offset[2]*scale)
-               
-                       # Add Ipo's for necessary channels
-                       newIpo = Ipo.New('Object', name)
-                       ob.setIpo(newIpo)
-                       obname = ob.name
-                       for channelType in channels:
-                               channelType = BVH2BLEND_TX_NAME[channelType]
-                               curve = newIpo.addCurve(channelType)
-                               curve.setInterpolation('Linear')
-                               objectCurveMapping[(obname, channelType)] = curve
-               
-                       # Add to object list
-                       objectList.append(ob)
-                       
-                       # Redraw if debugging
-                       if debug: Blender.Redraw()
-                       
-                       
-               #===============================================#
-               # makeEnd: Here we make an end node             #
-               # This is needed when adding the last bone      #
-               #===============================================#
-               def makeEnd(parent, offset):
-                       new_name = parent[-1] + '_end'
-                       ob = Object.New('Empty', new_name) # New object, ob is shorter and nicer to use.
-                       objectNameMapping[new_name] = ob
-                       scn.link(ob)
-                       ob.sel = 1
-                       
-                       # Dont check for a parent, an end node MUST have a parent
-                       obParent = objectNameMapping[parent[-1]] # We use this a bit so refrence it here.
-                       obParent.makeParent([ob], 1, 0) #ojbs, noninverse, 1 = not fast.
-               
-                       # Offset Empty
-                       ob.setLocation(offset[0]*scale, offset[1]*scale, offset[2]*scale) 
-                       
-                       # Redraw if debugging
-                       if debug: Blender.Redraw()
-               # END FUNCTION DEFINITIONS ====================================#
-                       
-               
-               
-               
-               time1 = Blender.sys.time()
-               
-               # Get the current scene.
-               scn = Scene.GetCurrent()
-               #context = scn.getRenderingContext()
-               
-               # DeSelect All
-               for ob in scn.getChildren():
-                       ob.sel = 0
-               
-               # File loading stuff
-               # Open the file for importing
-               file = open(filename, 'r')      
-               
-               # Seperate into a list of lists, each line a list of words.
-               lines = file.readlines()
-               # Non standard carrage returns?
-               if len(lines) == 1:
-                       lines = lines[0].split('\r')
-               
-               # Split by whitespace.
-               lines =[ll for ll in [ [w for w in l.split() if w != '\n' ] for l in lines] if ll]
-               # End file loading code
-       
-               
-               
-               # Create Hirachy as empties
-               if lines[0][0] == 'HIERARCHY':
-                       print 'Importing the BVH Hierarchy for:', filename
-               else:
-                       return 'ERROR: This is not a BVH file'
-               
-               # A liniar list of ancestors to keep track of a single objects heratage
-               # at any one time, this is appended and removed, dosent store tree- just a liniar list.
-               # ZERO is a place holder that means we are a root node. (no parents)
-               parent = [None] 
-               
-               #channelList, sync with objectList:  [[channelType1, channelType2...],  [channelType1, channelType2...)]
-               channelList = []
-               channelIndex = -1
-               
-               lineIdx = 0 # An index for the file.
-               while lineIdx < len(lines) -1:
-                       #...
-                       if lines[lineIdx][0] == 'ROOT' or lines[lineIdx][0] == 'JOINT':
-                               
-                               # Join spaces into 1 word with underscores joining it.
-                               if len(lines[lineIdx]) > 2:
-                                       lines[lineIdx][1] = '_'.join(lines[lineIdx][1:])
-                                       lines[lineIdx] = lines[lineIdx][:2]
-                               
-                               # MAY NEED TO SUPPORT MULTIPLE ROOT's HERE!!!, Still unsure weather multiple roots are possible.??
-                               
-                               # Make sure the names are unique- Object names will match joint names exactly and both will be unique.
-                               name = getUniqueObName(lines[lineIdx][1])
-                               uniqueObNames.append(name)
-                               
-                               print '%snode: %s, parent: %s' % (len(parent) * '  ', name,  parent[-1])
-                               
-                               lineIdx += 2 # Incriment to the next line (Offset)
-                               offset = ( float(lines[lineIdx][1]), float(lines[lineIdx][2]), float(lines[lineIdx][3]) )
-                               lineIdx += 1 # Incriment to the next line (Channels)
-                               
-                               # newChannel[Xposition, Yposition, Zposition, Xrotation, Yrotation, Zrotation]
-                               # newChannel references indecies to the motiondata,
-                               # if not assigned then -1 refers to the last value that will be added on loading at a value of zero, this is appended 
-                               # We'll add a zero value onto the end of the MotionDATA so this is always refers to a value.
-                               newChannel = [-1, -1, -1, -1, -1, -1] 
-                               for channel in lines[lineIdx][2:]:
-                                       channelIndex += 1 # So the index points to the right channel
-                                       if channel == 'Xposition':
-                                               newChannel[0] = channelIndex
-                                       elif channel == 'Yposition':
-                                               newChannel[1] = channelIndex
-                                       elif channel == 'Zposition':
-                                               newChannel[2] = channelIndex
-                                       elif channel == 'Xrotation':
-                                               newChannel[3] = channelIndex
-                                       elif channel == 'Yrotation':
-                                               newChannel[4] = channelIndex
-                                       elif channel == 'Zrotation':
-                                               newChannel[5] = channelIndex
-                               
-                               channelList.append(newChannel)
-                               
-                               channels = lines[lineIdx][2:]
-                               
-                               # Call funtion that uses the gatrhered data to make an empty.
-                               makeJoint(name, parent, offset, channels)
-                               
-                               # If we have another child then we can call ourselves a parent, else 
-                               parent.append(name)
-       
-                       # Account for an end node
-                       if lines[lineIdx][0] == 'End' and lines[lineIdx][1] == 'Site': # There is somtimes a name after 'End Site' but we will ignore it.
-                               lineIdx += 2 # Incriment to the next line (Offset)
-                               offset = ( float(lines[lineIdx][1]), float(lines[lineIdx][2]), float(lines[lineIdx][3]) )
-                               makeEnd(parent, offset)
-                               
-                               # Just so we can remove the Parents in a uniform way- End end never has kids
-                               # so this is a placeholder
-                               parent.append(None)
-                       
-                       if len(lines[lineIdx]) == 1 and lines[lineIdx][0] == '}': # == ['}']
-                               parent.pop() # Remove the last item
-                       
-                       #=============================================#
-                       # BVH Structure loaded, Now import motion     #
-                       #=============================================#         
-                       if len(lines[lineIdx]) == 1 and lines[lineIdx][0] == 'MOTION':
-                               print '\nImporting motion data'
-                               lineIdx += 3 # Set the cursor to the first frame
-                               
-                               #=============================================#
-                               # Add a ZERO keyframe, this keeps the rig     #
-                               # so when we export we know where all the     #
-                               # joints start from                           #
-                               #=============================================#
-                               
-                               for obIdx, ob in enumerate(objectList):
-                                       obname = ob.name
-                                       if channelList[obIdx][0] != -1:
-                                               objectCurveMapping[obname, 'LocX'].addBezier((currentFrame,0))
-                                               objectMotiondataMapping[obname, 'LocX'] = []
-                                       if channelList[obIdx][1] != -1:
-                                               objectCurveMapping[obname, 'LocY'].addBezier((currentFrame,0))
-                                               objectMotiondataMapping[obname, 'LocY'] = []
-                                       if channelList[obIdx][2] != -1:
-                                               objectCurveMapping[obname, 'LocZ'].addBezier((currentFrame,0))
-                                               objectMotiondataMapping[obname, 'LocZ'] = []
-                                       if\
-                                       channelList[obIdx][3] != -1 or\
-                                       channelList[obIdx][4] != -1 or\
-                                       channelList[obIdx][5] != -1:
-                                               objectMotiondataMapping[obname, 'RotX'] = []
-                                               objectMotiondataMapping[obname, 'RotY'] = []
-                                               objectMotiondataMapping[obname, 'RotZ'] = []
-                               
-                               #=============================================#
-                               # Loop through frames, each line a frame      #
-                               #=============================================#                 
-                               MOTION_DATA_LINE_LEN = len(lines[lineIdx])
-                               while lineIdx < len(lines):
-                                       line = lines[lineIdx]
-                                       if MOTION_DATA_LINE_LEN != len(line):
-                                               print 'ERROR: Incomplete motion data on line %i, finishing import.' % lineIdx
-                                               break
-                                               
-                                       # Exit loop if we are past the motiondata.
-                                       # Some BVH's have extra tags like 'CONSTRAINTS and MOTIONTAGS'
-                                       # I dont know what they do and I dont care, they'll be ignored here.
-                                       if len(