Merge from trunk: 15912:16031
authorIan Thompson <quornian@googlemail.com>
Sat, 9 Aug 2008 10:12:59 +0000 (10:12 +0000)
committerIan Thompson <quornian@googlemail.com>
Sat, 9 Aug 2008 10:12:59 +0000 (10:12 +0000)
76 files changed:
CMakeLists.txt
SConstruct
config/linux2-config.py
intern/boolop/SConscript
intern/boolop/intern/BOP_Interface.cpp
intern/boolop/make/msvc_7_0/boolop.vcproj
intern/bsp/SConscript
projectfiles_vc7/blender/BPY_python/BPY_python.vcproj
projectfiles_vc7/blender/blender.sln
projectfiles_vc7/blender/blenkernel/BKE_blenkernel.vcproj
projectfiles_vc7/gameengine/ketsji/KX_ketsji.vcproj
projectfiles_vc7/gameengine/physics/PHY_Physics/PHY_Sumo/PHY_Sumo.vcproj
release/scripts/flt_export.py
release/scripts/flt_palettemanager.py
release/scripts/import_dxf.py
release/scripts/weightpaint_clean.py
source/blender/blenkernel/BKE_bvhutils.h [new file with mode: 0644]
source/blender/blenkernel/BKE_texture.h
source/blender/blenkernel/bad_level_call_stubs/stubs.c
source/blender/blenkernel/intern/anim.c
source/blender/blenkernel/intern/bvhutils.c [new file with mode: 0644]
source/blender/blenkernel/intern/collision.c
source/blender/blenkernel/intern/customdata.c
source/blender/blenkernel/intern/modifier.c
source/blender/blenkernel/intern/particle.c
source/blender/blenkernel/intern/particle_system.c
source/blender/blenkernel/intern/texture.c
source/blender/blenlib/BLI_kdopbvh.h
source/blender/blenlib/intern/BLI_kdopbvh.c
source/blender/blenlib/intern/boxpack2d.c
source/blender/imbuf/intern/anim.c
source/blender/include/BIF_editarmature.h
source/blender/include/BIF_editmesh.h
source/blender/include/BIF_poseobject.h
source/blender/include/butspace.h
source/blender/python/BPY_interface.c
source/blender/python/api2_2x/Blender.c
source/blender/python/api2_2x/Constraint.c
source/blender/python/api2_2x/Material.c
source/blender/python/api2_2x/Mathutils.c
source/blender/python/api2_2x/Mathutils.h
source/blender/python/api2_2x/doc/Render.py
source/blender/render/intern/source/convertblender.c
source/blender/src/buttons_editing.c
source/blender/src/buttons_object.c
source/blender/src/buttons_scene.c
source/blender/src/drawgpencil.c
source/blender/src/drawseq.c
source/blender/src/editarmature.c
source/blender/src/editimasel.c
source/blender/src/editmesh_mods.c
source/blender/src/editseq.c
source/blender/src/header_info.c
source/blender/src/header_view3d.c
source/blender/src/poselib.c
source/blender/src/poseobject.c
source/blender/src/space.c
source/blender/src/toolbox.c
source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
source/gameengine/Converter/BL_BlenderDataConversion.cpp
source/gameengine/Converter/KX_IpoConvert.cpp
source/gameengine/GamePlayer/common/windows/GPW_Canvas.h
source/gameengine/GamePlayer/ghost/GPG_Application.cpp
source/gameengine/Ketsji/CMakeLists.txt
source/gameengine/Ketsji/KX_GameObject.cpp
source/gameengine/Ketsji/KX_GameObject.h
source/gameengine/Ketsji/KX_PythonInit.cpp
source/gameengine/Ketsji/KX_PythonInit.h
source/gameengine/Ketsji/KX_RadarSensor.cpp
source/gameengine/Ketsji/KX_TouchEventManager.cpp
source/gameengine/Ketsji/SConscript
source/gameengine/Physics/Bullet/CcdPhysicsController.cpp
source/gameengine/Physics/Bullet/CcdPhysicsController.h
source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp
source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h
source/gameengine/PyDoc/KX_GameObject.py

index 5a23e77d9f81fa04100e840f1bab164e442a317f..0ea26750ec1c75aa03c40b02972b068cdbfaaeb0 100644 (file)
@@ -183,9 +183,9 @@ IF(UNIX)
   SET(LLIBS "-lXi -lutil -lc -lm -lpthread -lstdc++")
 
   IF(WITH_OPENMP)
-    SET(LLIBS "${LLIBS} -lgomp ")
-    SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fopenmp ")
-    SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp ")
+    SET(LLIBS "${LLIBS} -lgomp")
+    SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fopenmp")
+    SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp")
   ENDIF(WITH_OPENMP)
 
 
index 869ba6454c81394fa515a6209c92a63f43b1499a..4c3bbf8fad7179b85152d47b24fcbbecf8b129fc 100644 (file)
@@ -184,15 +184,16 @@ if env['WITH_BF_OPENMP'] == 1:
                 env['CPPFLAGS'].append('/openmp')
                 env['CXXFLAGS'].append('/openmp')
         else:
-            if env['CC'] == 'icc':
+            if env['CC'][-3:] == 'icc': # to be able to handle CC=/opt/bla/icc case
                 env.Append(LINKFLAGS=['-openmp', '-static-intel'])
                 env['CCFLAGS'].append('-openmp')
                 env['CPPFLAGS'].append('-openmp')
                 env['CXXFLAGS'].append('-openmp')
             else:
-                env['CCFLAGS'].append('-fopenmp')
-                env['CPPFLAGS'].append('-fopenmp')
-                env['CXXFLAGS'].append('-fopenmp')
+                env.Append(CCFLAGS=['-fopenmp']) 
+                env.Append(CPPFLAGS=['-fopenmp'])
+                env.Append(CXXFLAGS=['-fopenmp'])
+                # env.Append(LINKFLAGS=['-fprofile-generate'])
 
 #check for additional debug libnames
 
index 6bde0664fe598475cc2e4f3a984037a1f9f3c577..fe4325361a83b4874abda7fedc749fae31fbdb1e 100644 (file)
@@ -139,7 +139,7 @@ BF_OPENJPEG_LIB = ''
 BF_OPENJPEG_INC = '${BF_OPENJPEG}/include'
 BF_OPENJPEG_LIBPATH='${BF_OPENJPEG}/lib'
 
-WITH_BF_REDCODE = 'true'  
+WITH_BF_REDCODE = 'false'  
 BF_REDCODE = '#extern/libredcode'
 BF_REDCODE_LIB = ''
 # Uncomment the following two lines to use system's ffmpeg
index a3f3c0b6433bb4d1e4e3dc34d8bdbb0db5901b65..bec263f251f0be419f1fef36e383e57b7f157101 100644 (file)
@@ -8,7 +8,7 @@ incs += ' ../../source/blender/makesdna ../../intern/guardedalloc'
 incs += ' ../../source/blender/blenlib'
 
 if (env['OURPLATFORM'] == 'win32-mingw'):
-    env.BlenderLib ('blender_bop', sources, Split(incs) , [], libtype=['common','intern'], priority = [5,50] )
+    env.BlenderLib ('blender_bop', sources, Split(incs) , [], libtype=['common','intern'], priority = [30,85] )
 else:
     env.BlenderLib ('blender_bop', sources, Split(incs) , [], libtype='common', priority = 5 )
 
index 898ca708204168a097b1a4015fef5f34edda25af..c6bcb4a74ce3e2418c6e9f7858e340b27cddb4f6 100644 (file)
@@ -37,7 +37,7 @@
 #include "BOP_Chrono.h"
 
 #if defined(BOP_ORIG_MERGE) && defined(BOP_NEW_MERGE) 
-#include "../../source/blender/blenkernel/BKE_global.h"
+#include "../../../source/blender/blenkernel/BKE_global.h"
 #endif
 
 BoolOpState BOP_intersectionBoolOp(BOP_Mesh*  meshC,
index 7ae417e42d51f21e8ee72da0d140fd452b70510a..6e6d6abeb43676cfaffc9c84161c518a586b6b22 100644 (file)
@@ -278,6 +278,9 @@ ECHO Done
                                <File
                                        RelativePath="..\..\intern\BOP_Merge.cpp">
                                </File>
+                               <File
+                                       RelativePath="..\..\intern\BOP_Merge2.cpp">
+                               </File>
                                <File
                                        RelativePath="..\..\intern\BOP_Mesh.cpp">
                                </File>
@@ -330,9 +333,15 @@ ECHO Done
                                <File
                                        RelativePath="..\..\intern\BOP_Merge.h">
                                </File>
+                               <File
+                                       RelativePath="..\..\intern\BOP_Merge2.h">
+                               </File>
                                <File
                                        RelativePath="..\..\intern\BOP_Mesh.h">
                                </File>
+                               <File
+                                       RelativePath="..\..\intern\BOP_Misc.h">
+                               </File>
                                <File
                                        RelativePath="..\..\intern\BOP_Segment.h">
                                </File>
index 88d2529ae59eefa764165c44ff6f9fe7acbb4b7a..39f278625a95772e6d5961856caeda09f458421e 100644 (file)
@@ -6,7 +6,7 @@ sources = env.Glob('intern/*.cpp')
 incs = 'intern ../container ../moto/include ../memutil'
 
 if (env['OURPLATFORM'] == 'win32-mingw'):
-    env.BlenderLib ('blender_BSP', sources, Split(incs), [], libtype=['common','intern'], priority=[26,26] )
+    env.BlenderLib ('blender_BSP', sources, Split(incs), [], libtype=['common','intern'], priority=[26,69] )
 else:
     env.BlenderLib ('blender_BSP', sources, Split(incs), [], libtype='core', priority=26 )
 
index a31b9130db358e5824a2e84b0e8b4bd9fd41aa7a..97f70a26db4ffdbafaed1bd9cbadd3fa8431ab2e 100644 (file)
                        <Tool
                                Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
                </Configuration>
+               <Configuration
+                       Name="BlenderPlayer Debug|Win32"
+                       OutputDirectory="$(ConfigurationName)"
+                       IntermediateDirectory="$(ConfigurationName)"
+                       ConfigurationType="4"
+                       UseOfMFC="0"
+                       ATLMinimizesCRunTimeLibraryUsage="FALSE"
+                       CharacterSet="2">
+                       <Tool
+                               Name="VCCLCompilerTool"
+                               Optimization="0"
+                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\bsp\include;..\..\..\..\build\msvc_7\intern\bmfont\include;..\..\..\..\build\msvc_7\intern\iksolver\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\..\lib\windows\ffmpeg\include;..\..\..\source\blender;..\..\..\source\blender\avi;..\..\..\source\blender\img;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\include;..\..\..\source\blender\blenkernel;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenloader;..\..\..\source\blender\renderconverter;..\..\..\source\blender\render\extern\include;..\..\..\source\blender\radiosity\extern\include;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\SoundSystem"
+                               PreprocessorDefinitions="_DEBUG,WIN32,_LIB;WITH_FFMPEG"
+                               BasicRuntimeChecks="3"
+                               RuntimeLibrary="1"
+                               DisableLanguageExtensions="FALSE"
+                               DefaultCharIsUnsigned="TRUE"
+                               UsePrecompiledHeader="2"
+                               PrecompiledHeaderFile="..\..\..\..\build\msvc_7\source\blender\python\debug\BPY_python.pch"
+                               AssemblerListingLocation="..\..\..\..\build\msvc_7\source\blender\python\debug\"
+                               ObjectFile="..\..\..\..\build\msvc_7\source\blender\python\debug\"
+                               ProgramDataBaseFileName="..\..\..\..\build\msvc_7\source\blender\python\debug\"
+                               WarningLevel="4"
+                               SuppressStartupBanner="TRUE"
+                               Detect64BitPortabilityProblems="FALSE"
+                               DebugInformationFormat="3"
+                               CompileAs="0"
+                               DisableSpecificWarnings="4100"/>
+                       <Tool
+                               Name="VCCustomBuildTool"/>
+                       <Tool
+                               Name="VCLibrarianTool"
+                               OutputFile="..\..\..\..\build\msvc_7\libs\debug\BPY_python.lib"
+                               SuppressStartupBanner="TRUE"/>
+                       <Tool
+                               Name="VCMIDLTool"/>
+                       <Tool
+                               Name="VCPostBuildEventTool"/>
+                       <Tool
+                               Name="VCPreBuildEventTool"/>
+                       <Tool
+                               Name="VCPreLinkEventTool"/>
+                       <Tool
+                               Name="VCResourceCompilerTool"
+                               Culture="1033"/>
+                       <Tool
+                               Name="VCWebServiceProxyGeneratorTool"/>
+                       <Tool
+                               Name="VCXMLDataGeneratorTool"/>
+                       <Tool
+                               Name="VCManagedWrapperGeneratorTool"/>
+                       <Tool
+                               Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+               </Configuration>
+               <Configuration
+                       Name="BlenderPlayer Release|Win32"
+                       OutputDirectory="$(ConfigurationName)"
+                       IntermediateDirectory="$(ConfigurationName)"
+                       ConfigurationType="4"
+                       UseOfMFC="0"
+                       ATLMinimizesCRunTimeLibraryUsage="FALSE"
+                       CharacterSet="2">
+                       <Tool
+                               Name="VCCLCompilerTool"
+                               InlineFunctionExpansion="1"
+                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\bsp\include;..\..\..\..\build\msvc_7\intern\bmfont\include;..\..\..\..\build\msvc_7\intern\iksolver\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender;..\..\..\source\blender\avi;..\..\..\source\blender\img;..\..\..\source\blender\imbuf;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\include;..\..\..\source\blender\blenkernel;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenloader;..\..\..\source\blender\renderconverter;..\..\..\source\blender\render\extern\include;..\..\..\source\blender\radiosity\extern\include;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\SoundSystem;..\..\..\..\lib\windows\ffmpeg\include"
+                               PreprocessorDefinitions="WIN32,NDEBUG,_LIB"
+                               StringPooling="TRUE"
+                               RuntimeLibrary="0"
+                               EnableFunctionLevelLinking="TRUE"
+                               DefaultCharIsUnsigned="TRUE"
+                               UsePrecompiledHeader="2"
+                               PrecompiledHeaderFile="..\..\..\..\build\msvc_7\source\blender\python\BPY_python.pch"
+                               AssemblerListingLocation="..\..\..\..\build\msvc_7\source\blender\python\"
+                               ObjectFile="..\..\..\..\build\msvc_7\source\blender\python\"
+                               ProgramDataBaseFileName="..\..\..\..\build\msvc_7\source\blender\python\"
+                               WarningLevel="3"
+                               SuppressStartupBanner="TRUE"
+                               Detect64BitPortabilityProblems="FALSE"
+                               CompileAs="0"
+                               DisableSpecificWarnings="4100"/>
+                       <Tool
+                               Name="VCCustomBuildTool"/>
+                       <Tool
+                               Name="VCLibrarianTool"
+                               OutputFile="..\..\..\..\build\msvc_7\libs\BPY_python.lib"
+                               SuppressStartupBanner="TRUE"/>
+                       <Tool
+                               Name="VCMIDLTool"/>
+                       <Tool
+                               Name="VCPostBuildEventTool"/>
+                       <Tool
+                               Name="VCPreBuildEventTool"/>
+                       <Tool
+                               Name="VCPreLinkEventTool"/>
+                       <Tool
+                               Name="VCResourceCompilerTool"
+                               PreprocessorDefinitions="NDEBUG"
+                               Culture="1033"/>
+                       <Tool
+                               Name="VCWebServiceProxyGeneratorTool"/>
+                       <Tool
+                               Name="VCXMLDataGeneratorTool"/>
+                       <Tool
+                               Name="VCManagedWrapperGeneratorTool"/>
+                       <Tool
+                               Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
+               </Configuration>
        </Configurations>
        <References>
        </References>
index 60c2d8f2d4c821e30cbdfe8399a2e19243d84316..1b069fa46773cd6f9774d8b338ecd33e6a6d433e 100644 (file)
@@ -152,6 +152,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GP_ghost", "..\gameengine\g
                {E109F1A5-FDD3-4F56-A1C4-96867EEA4C5B} = {E109F1A5-FDD3-4F56-A1C4-96867EEA4C5B}
                {727F90AC-ABE6-40BF-8937-C2F2F1D13DEA} = {727F90AC-ABE6-40BF-8937-C2F2F1D13DEA}
                {E90C7BC2-CF30-4A60-A8F2-0050D592E358} = {E90C7BC2-CF30-4A60-A8F2-0050D592E358}
+               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA} = {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}
                {32CC75E2-EE85-45E6-8E3D-513F58464F43} = {32CC75E2-EE85-45E6-8E3D-513F58464F43}
                {9A307EE5-CD77-47BC-BD87-62508C7E19D8} = {9A307EE5-CD77-47BC-BD87-62508C7E19D8}
                {AB590CED-F71F-4A17-A89B-18583ECD633D} = {AB590CED-F71F-4A17-A89B-18583ECD633D}
@@ -248,6 +249,8 @@ Global
                Debug = Debug
                Release = Release
        EndGlobalSection
+       GlobalSection(ProjectDependencies) = postSolution
+       EndGlobalSection
        GlobalSection(ProjectConfiguration) = postSolution
                {F78B7FC9-DE32-465E-9F26-BB0B6B7A2EAF}.3D Plugin Debug.ActiveCfg = Blender Debug|Win32
                {F78B7FC9-DE32-465E-9F26-BB0B6B7A2EAF}.3D Plugin Release.ActiveCfg = Blender Release|Win32
@@ -387,8 +390,10 @@ Global
                {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.Blender Debug.Build.0 = Blender Debug|Win32
                {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.Blender Release.ActiveCfg = Blender Release|Win32
                {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.Blender Release.Build.0 = Blender Release|Win32
-               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.BlenderPlayer Debug.ActiveCfg = Blender Debug|Win32
-               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.BlenderPlayer Release.ActiveCfg = Blender Release|Win32
+               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.BlenderPlayer Debug.ActiveCfg = BlenderPlayer Debug|Win32
+               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.BlenderPlayer Debug.Build.0 = BlenderPlayer Debug|Win32
+               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.BlenderPlayer Release.ActiveCfg = BlenderPlayer Release|Win32
+               {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.BlenderPlayer Release.Build.0 = BlenderPlayer Release|Win32
                {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.Debug.ActiveCfg = Blender Debug|Win32
                {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.Debug.Build.0 = Blender Debug|Win32
                {5A2EA6DC-1A53-4E87-9166-52870CE3B4EA}.Release.ActiveCfg = Blender Release|Win32
index 8efff1742b074f7732c1ead055d5e44bc5268489..0ea3503a289f2cd6a2ac849dd40b91dea88faf81 100644 (file)
                        <File
                                RelativePath="..\..\..\source\blender\blenkernel\intern\brush.c">
                        </File>
+                       <File
+                               RelativePath="..\..\..\source\blender\blenkernel\intern\bvhutils.c">
+                       </File>
                        <File
                                RelativePath="..\..\..\source\blender\blenkernel\intern\CCGSubSurf.c">
                        </File>
                        <File
                                RelativePath="..\..\..\source\blender\blenkernel\BKE_brush.h">
                        </File>
+                       <File
+                               RelativePath="..\..\..\source\blender\blenkernel\BKE_bvhutils.h">
+                       </File>
                        <File
                                RelativePath="..\..\..\source\blender\blenkernel\BKE_cdderivedmesh.h">
                        </File>
index 9d5a9f55074877e6aef998625fcd89a6d01b0e93..c046d434cb34c14a93134a7e54ad05f1dfb8fad8 100644 (file)
                        <Tool
                                Name="VCCLCompilerTool"
                                Optimization="0"
-                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet"
+                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet;..\..\..\source\blender\python\api2_2x"
                                PreprocessorDefinitions="JANCODEPANCO;WIN32;_LIB;EXP_PYTHON_EMBEDDING;_DEBUG;USE_SUMO_SOLID;WITH_GLEXT"
                                BasicRuntimeChecks="3"
                                RuntimeLibrary="1"
                        <Tool
                                Name="VCCLCompilerTool"
                                InlineFunctionExpansion="1"
-                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet"
+                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet;..\..\..\source\blender\python\api2_2x"
                                PreprocessorDefinitions="NDEBUG;WIN32;_LIB;USE_SUMO_SOLID;WITH_GLEXT"
                                StringPooling="TRUE"
                                RuntimeLibrary="0"
                        <Tool
                                Name="VCCLCompilerTool"
                                Optimization="0"
-                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet"
+                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet;..\..\..\source\blender\python\api2_2x"
                                PreprocessorDefinitions="JANCODEPANCO;WIN32;_LIB;EXP_PYTHON_EMBEDDING;_DEBUG;USE_SUMO_SOLID;WITH_GLEXT"
                                BasicRuntimeChecks="3"
                                RuntimeLibrary="1"
                                DefaultCharIsUnsigned="TRUE"
+                               RuntimeTypeInfo="TRUE"
                                UsePrecompiledHeader="2"
                                PrecompiledHeaderFile="..\..\..\..\build\msvc_7\source\gameengine\ketsji\debug\KX_ketsji.pch"
                                AssemblerListingLocation="..\..\..\..\build\msvc_7\source\gameengine\ketsji\debug\"
                        <Tool
                                Name="VCCLCompilerTool"
                                InlineFunctionExpansion="1"
-                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet"
+                               AdditionalIncludeDirectories="..\..\..\..\build\msvc_7\intern\string\include;..\..\..\..\build\msvc_7\intern\moto\include;..\..\..\..\build\msvc_7\intern\soundsystem\include;..\..\..\..\build\msvc_7\intern\guardedalloc\include;..\..\..\..\build\msvc_7\extern\bullet\include;..\..\..\..\build\msvc_7\extern\solid\include;..\..\..\..\build\msvc_7\extern\glew\include;..\..\..\..\lib\windows\python\include\python2.5;..\..\..\source\blender\imbuf;..\..\..\source\blender\include;..\..\..\source\blender\blenlib;..\..\..\source\blender\python;..\..\..\source\blender\makesdna;..\..\..\source\blender\blenkernel;..\..\..\source\kernel\gen_system;..\..\..\source\gameengine\physics;..\..\..\source\gameengine\rasterizer;..\..\..\source\gameengine\network;..\..\..\source\gameengine\Converter;..\..\..\source\gameengine\gamelogic;..\..\..\source\gameengine\scenegraph;..\..\..\source\gameengine\expressions;..\..\..\source\gameengine\physics\sumo;..\..\..\source\gameengine\physics\dummy;..\..\..\source\gameengine\physics\BlOde;..\..\..\source\gameengine\ketsji\kxnetwork;..\..\..\source\gameengine\physics\common;..\..\..\source\gameengine\physics\sumo\include;..\..\..\source\gameengine\physics\common\dummy;..\..\..\source\gameengine\Rasterizer\RAS_OpenGLRasterizer;..\..\..\source\gameengine\physics\sumo\fuzzics\include;..\..\..\source\sumo\include;..\..\..\source\sumo\fuzzics\include;..\..\..\source\gameengine\physics\bullet;..\..\..\source\blender\python\api2_2x"
                                PreprocessorDefinitions="NDEBUG;WIN32;_LIB;USE_SUMO_SOLID;WITH_GLEXT"
                                StringPooling="TRUE"
                                RuntimeLibrary="0"
index a8d6e77cd58f9cf61b861c0dba9d6909ec49a072..33806e32d65593f130a199e7818bbb8b04b8a0b3 100644 (file)
                                MinimalRebuild="TRUE"
                                BasicRuntimeChecks="3"
                                RuntimeLibrary="1"
+                               RuntimeTypeInfo="TRUE"
                                UsePrecompiledHeader="2"
                                PrecompiledHeaderFile="..\..\..\..\..\..\build\msvc_7\source\gameengine\physics\sumo\debug\PHY_Sumo.pch"
                                AssemblerListingLocation="..\..\..\..\..\..\build\msvc_7\source\gameengine\physics\sumo\debug\"
index 2b9db74c77076a38d5c9642f879259fb9e3fdbb5..c099c8e62d165dab42b555bba98e33d1e4979113 100644 (file)
@@ -525,8 +525,8 @@ class FaceDesc:
        def __init__(self):
                self.vertex_index_lst = []
                self.mface = None
-               self.texture_index = -1
-               self.material_index = -1
+               self.texture_index = 65535
+               self.material_index = 65535
                self.color_index = 127
                self.renderstyle = 0
                self.twoside = 0
@@ -979,8 +979,14 @@ class FLTNode(Node):
                        self.header.fw.write_char(0)                                    # Reserved
                        self.header.fw.write_char(alpha)                                    # Template
                        self.header.fw.write_short(-1)                                  # Detail tex pat index
-                       self.header.fw.write_short(face_desc.texture_index)             # Tex pattern index
-                       self.header.fw.write_short(face_desc.material_index)            # material index
+                       if face_desc.texture_index == -1:
+                               self.header.fw.write_ushort(65535)
+                       else:
+                               self.header.fw.write_ushort(face_desc.texture_index)    # Tex pattern index
+                       if face_desc.material_index == -1:
+                               self.header.fw.write_ushort(65535)
+                       else:
+                               self.header.fw.write_ushort(face_desc.material_index)           # material index
                        self.header.fw.write_short(0)                                   # SMC code
                        self.header.fw.write_short(0)                                   # Feature                                       code
                        self.header.fw.write_int(0)                                     # IR material code
@@ -1015,7 +1021,10 @@ class FLTNode(Node):
                                self.header.fw.write_ushort(8 + (mtex * 8))             # Length
                                self.header.fw.write_uint(uvmask)                                                               # UV mask
                                for i in xrange(mtex):
-                                       self.header.fw.write_ushort(face_desc.images[i])                        # Tex pattern index
+                                       if face_desc.images[i] == -1:
+                                               self.header.fw.write_ushort(65535)
+                                       else:
+                                               self.header.fw.write_ushort(face_desc.images[i])                        # Tex pattern index
                                        self.header.fw.write_ushort(0)                                                          # Tex effect
                                        self.header.fw.write_ushort(0)                                                          # Tex Mapping index
                                        self.header.fw.write_ushort(0)                                                          # Tex data. User defined
@@ -1070,7 +1079,7 @@ class FLTNode(Node):
 
                 if self.opcode == 63 and options.state['externalspath']:
                                try:
-                                       exportdict['3t200!filename'] = os.path.join(options.state['externalspath'],self.object.DupGroup.name+'.flt')
+                                       exportdict['3t200!filename'] = os.path.join(options.state['externalspath'],self.object.DupGroup.name+'.flt').replace("\\", "/")
                                        self.header.xrefnames.append(self.object.DupGroup.name)
                                except:
                                        pass
@@ -1092,7 +1101,7 @@ class FLTNode(Node):
                                write_prop(self.header.fw,ftype,self.object.properties['FLT']['EXT'][propname],length)
                        #write extension data
                        for i in xrange(datalen):
-                               self.header.fw.write_char(self.object.properties['FLT']['EXT']['data'][i])
+                               self.header.fw.write_uchar(struct.unpack('>B', struct.pack('>B', self.object.properties['FLT']['EXT']['data'][i]))[0])
                        self.write_pop_extension()
 
 
@@ -1180,8 +1189,8 @@ class Database(Node):
                        desc = self.GRR.request_vertex_desc(i)
                        self.fw.write_short(70)                         # Vertex with color normal and uv opcode.
                        self.fw.write_ushort(64)                        # Length of record
-                       self.fw.write_ushort(0)                                                 # Color name index
-                       self.fw.write_short(0x20000000)                                 # Flags
+                       self.fw.write_ushort(0)                         # Color name index
+                       self.fw.write_short(1 << 14)                    # Frozen Normal
                        self.fw.write_double(desc.x)
                        self.fw.write_double(desc.y)
                        self.fw.write_double(desc.z)
@@ -1245,7 +1254,7 @@ class Database(Node):
                        cpalette = defaultp.pal
                count = len(cpalette)
                for i in xrange(count):
-                       color = struct.unpack('>BBBB',struct.pack('>I',cpalette[i]))
+                       color = struct.unpack('>BBBB',struct.pack('>i',cpalette[i]))
                        self.fw.write_uchar(color[3])               # alpha
                        self.fw.write_uchar(color[2])               # b
                        self.fw.write_uchar(color[1])               # g
index 6edaf2974ab04c3227e9d949163e509a5715884a..c2f1380a6fa1b388c8cf457ce8dd36701df9d5d2 100644 (file)
@@ -25,7 +25,7 @@ http://wiki.blender.org/index.php/Scripts/Manual/FLTools
 """
 
 # --------------------------------------------------------------------------
-# flt_palettemanager.py version 0.1 2005/04/08
+# flt_palettemanager.py version 1.0 2005/04/08
 # --------------------------------------------------------------------------
 # ***** BEGIN GPL LICENSE BLOCK *****
 #
@@ -55,6 +55,75 @@ import flt_properties
 import flt_defaultp as defaultp
 from flt_properties import *
 
+def RGBtoHSV( r, g, b):
+       minc = min( r, g, b )
+       maxc = max( r, g, b )
+       v = maxc                                
+
+       delta = maxc - minc
+
+       if( max != 0 ):
+               s = delta / maxc                
+       else:
+               s = 0
+               h = -1
+               return (h,s,v)
+
+       if( r == maxc ):
+               h = ( g - b ) / delta           
+       elif( g == maxc ):
+               h = 2 + ( b - r ) / delta
+       else:
+               h = 4 + ( r - g ) / delta
+
+       h *= 60
+       if( h < 0 ):
+               h += 360
+
+       return(h,s,v)
+
+def HSVtoRGB(h,s,v):
+
+       if( s == 0 ):
+               return (v,v,v)
+       
+
+       h /= 60
+       i = math.floor( h)
+       f = h - i
+       p = v * ( 1 - s )
+       q = v * ( 1 - s * f )
+       t = v * ( 1 - s * ( 1 - f ) )
+
+       if i == 0:
+               r = v
+               g = t
+               b = p
+       elif i == 1:
+               r = q
+               g = v
+               b = p
+
+       elif i== 2:
+               r = p
+               g = v
+               b = t
+       elif i==3:
+               r = p
+               g = q
+               b = v
+       elif i==4:
+               r = t
+               g = p
+               b = v
+
+       else:
+               r = v
+               g = p
+               b = q
+       
+       return(r,g,b)
+
 
 palette_size = 12
 palette_x = 0
@@ -68,6 +137,14 @@ cinc = 1.0 / 1024.0
 cstep = 0.0
 picker = None
 ptt = ""
+
+
+ts1=None
+ts2=None
+ts3=None
+ts4=None
+ts5=None
+
 for i in xrange(1024):
        colors.append([cstep,cstep,cstep])
        cstep = cstep + cinc
@@ -128,7 +205,7 @@ def event(evt,val):
                         Draw.Redraw(1)
        
        #copy current color and intensity to selected faces.
-       elif evt == Draw.CKEY:
+       elif evt == Draw.VKEY:
                
                if Blender.Window.EditMode():
                        Blender.Window.EditMode(0)
@@ -136,7 +213,7 @@ def event(evt,val):
                state = update_state()
                
                #retrieve color from palette
-               color = struct.unpack('>BBBB',struct.pack('>I',colors[curswatch]))
+               color = struct.unpack('>BBBB',struct.pack('>i',colors[curswatch]))
                actmesh = state["activeMesh"]
                if actmesh: 
                        if(Blender.Window.GetKeyQualifiers() != Blender.Window.Qual["CTRL"]):
@@ -182,7 +259,7 @@ def event(evt,val):
                        Blender.Window.RedrawAll()
        
        #grab color and intensity from active face
-       elif evt == Draw.VKEY:
+       elif evt == Draw.CKEY:
                if Blender.Window.EditMode():
                        Blender.Window.EditMode(0)
                        editmode = 1
@@ -211,6 +288,23 @@ def event(evt,val):
                        Blender.Window.EditMode(1)
                
                Blender.Window.RedrawAll()
+               
+       elif evt == Draw.GKEY:
+               if Blender.Window.EditMode():
+                       Blender.Window.EditMode(0)
+                       editmode =1
+               state = update_state()
+               
+               actmesh = state["activeMesh"]
+               activeFace = state["activeFace"]
+               
+               if activeFace and "FLT_COL" in actmesh.faces.properties:
+                       (index,intensity) = unpack_face_index(activeFace.getProperty("FLT_COL"))
+                       for face in actmesh.faces:
+                               (index2, intensity2) = unpack_face_index(face.getProperty("FLT_COL"))
+                               if index == index2:
+                                       face.sel = 1
+                               
                        
        elif evt == Draw.ESCKEY:
                Draw.Exit()
@@ -225,11 +319,11 @@ def update_all():
        for object in state["activeScene"].objects:
                if object.type == "Mesh":
                        mesh = object.getData(mesh=True)
-                       if 'FLT_COL' in mesh.faces.properties:
+                       if 'FLT_COL' in mesh.faces.properties and "FLT_Fcol" in mesh.getColorLayerNames():
                                mesh.activeColorLayer = "FLT_Fcol"
                                for face in mesh.faces:
                                        (index,intensity) = unpack_face_index(face.getProperty('FLT_COL'))
-                                       color = struct.unpack('>BBBB',struct.pack('>I',colors[index]))
+                                       color = struct.unpack('>BBBB',struct.pack('>i',colors[index]))
                                        #update the vertex colors for this face
                                        for col in face.col:
                                                col.r = int(color[0] * intensity)
@@ -284,8 +378,13 @@ def draw_palette():
        global colors
        global curint
        global curswatch
-        global picker
-
+       global picker
+       global ts1
+       global ts2
+       global ts3
+       global ts4
+       global ts5
+       
        state = update_state()
        init_pal()
 
@@ -297,7 +396,7 @@ def draw_palette():
        for x in xrange(32):
                ypos = palette_y
                for y in xrange(32):
-                       color = struct.unpack('>BBBB',struct.pack('>I',colors[cid]))
+                       color = struct.unpack('>BBBB',struct.pack('>i',colors[cid]))
                        glColor3f(color[0]/255.0,color[1]/255.0,color[2]/255.0)
                        glBegin(GL_POLYGON)
                        glVertex2i(xpos,ypos)
@@ -328,7 +427,7 @@ def draw_palette():
                xpos = xpos + ssize
        
        #draw intensity gradient
-       color = struct.unpack('>BBBB',struct.pack('>I',colors[curswatch]))
+       color = struct.unpack('>BBBB',struct.pack('>i',colors[curswatch]))
        color = [color[0]/255.0,color[1]/255.0,color[2]/255.0]
        colsteps = [color[0]/255.0,color[1]/255.0,color[2]/255.0]
        stripwidth = (palette_size * 32.0) / 256
@@ -355,15 +454,15 @@ def draw_palette():
        xpos = ((palette_size*32) * (1.0 - curint)) + palette_x
        glColor3f(1.0,1.0,1.0)
        glBegin(GL_LINE_LOOP)
-       glVertex2i(xpos-6,grady-1)
-       glVertex2i(xpos+6,grady-1)
-       glVertex2i(xpos+6,grady+palette_size+1)
-       glVertex2i(xpos-6,grady+palette_size+1)
+       glVertex2i(int(xpos-6),int(grady-1))
+       glVertex2i(int(xpos+6),int(grady-1))
+       glVertex2i(int(xpos+6),int(grady+palette_size+1))
+       glVertex2i(int(xpos-6),int(grady+palette_size+1))
        #glVertex2i(xpos-6,grady+7)
        glEnd()
 
        #draw color picker
-       color = struct.unpack('>BBBB',struct.pack('>I',colors[curswatch]))
+       color = struct.unpack('>BBBB',struct.pack('>i',colors[curswatch]))
        pickcol = (color[0]/255.0,color[1]/255.0,color[2]/255.0)
        picker = Blender.Draw.ColorPicker(1,highlight[0][0]+1,highlight[0][1]+1,ssize-2,ssize-2,pickcol,ptt)
 
@@ -377,6 +476,24 @@ def draw_palette():
        glVertex2i(highlight[0][0],highlight[0][1])
        glEnd()                 
 
+       #draw text string explanations
+       xpos = palette_size*32+20
+       ypos = palette_size*32+10
+       glRasterPos2d(xpos,ypos)
+       ts1     = Blender.Draw.Text("FLT Palette Manager V 1.0")
+       ypos = ypos - 20
+       glRasterPos2d(xpos,ypos)
+       ts3 = Blender.Draw.Text("CKEY - Copy Active Face Color*")
+       ypos = ypos - 20
+       glRasterPos2d(xpos,ypos)
+       ts2 = Blender.Draw.Text("VKEY - Paste Color to Selected Faces")
+       ypos = ypos - 20
+       glRasterPos2d(xpos,ypos)
+       ts4 = Blender.Draw.Text("GKEY - Select Faces With Same Color")
+       ypos = ypos - 15
+       glRasterPos2d(xpos,ypos)
+       ts5 = Blender.Draw.Text("(*Requires mesh with UV coordinates)", 'small')
+
 def gui():
        glClearColor(0.5,0.5,0.5,1.0)
        glClear(GL_COLOR_BUFFER_BIT)
@@ -385,4 +502,4 @@ def gui():
 
 init_pal()
 Draw.Register(gui,event,but_event)
-       
+       
\ No newline at end of file
index ce7df610d9853f47647e6fb9e8f86ca6f9c10494..bb0119a9a813596dfddda1ed91bb6676b34a79b6 100644 (file)
@@ -2,15 +2,15 @@
 
 """
 Name: 'Autodesk DXF (.dxf)'
-Blender: 244
+Blender: 246
 Group: 'Import'
 Tooltip: 'Import for DXF geometry data (Drawing eXchange Format).'
 """
 __author__ = 'Kitsu(Ed Blake) & migius(Remigiusz Fiedler)'
-__version__ = '1.0.12 - 2008.06.05 by migius'
+__version__ = '1.12 - 2008.08.03 by migius'
 __url__ = ["http://blenderartists.org/forum/showthread.php?t=84319",
         "http://wiki.blender.org/index.php/Scripts/Manual/Import/DXF-3D"]
-__email__ = ["Kitsune_e(at)yahoo.com", "migius(at)4d-vectors.de"]
+__email__ = ["migius(at)4d-vectors.de","Kitsune_e(at)yahoo.com"]
 __bpydoc__ = """\
 This script imports objects from DXF (2d/3d) into Blender.
 
@@ -19,7 +19,7 @@ Supported DXF format versions: from (r2.5) r12 up to 2008.
 Enhanced features are:
 - configurable object filtering and geometry manipulation,
 - configurable material pre-processing,
-- DXF-data analyze and raporting.
+- DXF-code analyze and reporting.
 
 Supported DXF r12 objects:
 LINE,
@@ -41,10 +41,10 @@ XREF (External Reference).
 
 Supported DXF>r12 objects:
 ELLIPSE,
-LWPOLYLINE (LightWeight Polylines),
-(wip v1.0.12) SPLINE,
-(wip v1.0.13) MLINE,
-(wip v1.0.13) MTEXT
+LWPOLYLINE (LightWeight Polyline),
+SPLINE,
+(wip v1.13) MLINE,
+(wip v1.13) MTEXT
 
 Unsupported objects:
 DXF r12: DIMENSION.
@@ -60,7 +60,7 @@ Supported layout modes:
 Supported scene definition objescts produced with AVE_RENDER:
 scene: selection of lights assigned to the camera,
 lights: DIRECT, OVERHEAD, SH_SPOT,
-(wip v1.0.13 import of AVE_RENDER material definitions)
+(wip v1.13 import of AVE_RENDER material definitions)
 
 Hierarchy:
 Entire DXF BLOCK hierarchy is preserved after import into Blender
@@ -73,7 +73,7 @@ thickness,
 width,
 color,
 layer,
-(wip v1.0.12: XDATA, grouped status)
+(wip v1.13: XDATA, grouped status)
 It is recommended to use DXF-object properties for assign Blender materials.
 
 Notes:
@@ -88,7 +88,7 @@ in creating new objects in scene database - probably a database management probl
 
 """
 History:
- v1.0 - 2008.01. by migius
+ v1.0 - 2007/2008 by migius
  planned tasks:
  -- (to see more, search for "--todo--" in script code)
  -- command-line-mode/batch-mode
@@ -109,9 +109,22 @@ History:
  -- bug: Registry recall from hd_cache ?? only win32 bug??
  -- support DXF-definitions of scene, lights and cameras
  -- support ortho mode for VIEWs and VPORTs as cameras 
- -- add support for SPLINEs
 
- v1.0.12: 2008.06.05 by migius
+
+ v1.12 - 2008.08.03 by migius
+ c2 warningfix: relocating of globals: layersmap, oblist 
+ c2 modif UI: buttons newScene+targetLayer moved to start panel
+ v1.12 - 2008.07.04 by migius
+ c1 added control Curve's OrderU parameter
+ c1 modif UI: preset buttons X-2D-3D moved to start panel
+ b6 added handling exception of not registered LAYERs (Hammer-HL-editor DXF output)
+ b5 rebuild UI: global preset 2D for Curve-Import
+ b5 added UI-options: PL-MESH N+N plmesh_flip and normals_out 
+ b5 added support for SPLINEs, added control OrderU parameter
+ b5 rewrote draw module for NURBS_curve and Bezier_curve
+ v1.12 - 2008.06.22 by migius
+ b4 change versioning system 1.0.12 -> 1.12
+ b4 print at start version-info to console
  b3 bugfix: ob.name conflict with existing meshes (different ob.name/mesh.name)
  v1.0.12: 2008.05.24 by migius
  b2 added support for LWPOLYLINEs
@@ -310,16 +323,16 @@ except ImportError:
        #print 'psyco not imported'
        pass
 
-print '\n\n\n\n'
-print 'DXF-Importer  *** start ***'   #---------------------
+#try: Curve.orderU
+
+print '\n\n\n'
+print 'DXF-Importer v%s *** start ***' %(__version__)   #---------------------
 
 SCENE = None
 WORLDX = Mathutils.Vector((1,0,0))
 WORLDY = Mathutils.Vector((1,1,0))
 WORLDZ = Mathutils.Vector((0,0,1))
 
-oblist = [] #to be sure, it is an empty list
-
 G_SCALE = 1.0     #(0.0001-1000) global scaling factor for all dxf data
 G_ORIGIN_X = 0.0   #global translation-vector (x,y,z) in DXF units
 G_ORIGIN_Y = 0.0
@@ -335,12 +348,15 @@ MIN_WIDTH = MIN_DIST * 10.0  #minimal width by forced width
 TRIM_LIMIT = 3.0        #limit for triming of polylines-wide-segments (values:0.0 - 5.0)
 ELEVATION = 0.0 #standard elevation = coordinate Z
 
-TARGET_LAYER = 3       #target blender_layer
-GROUP_BYLAYER = 0   #(0/1) all entities from same layer import into one blender-group
-cur_COUNTER = 0  #counter for progress_bar
-M_OBJ = False
 BYBLOCK = 0
 BYLAYER = 256
+TARGET_LAYER = 3       #target blender_layer
+GROUP_BYLAYER = 0   #(0/1) all entities from same layer import into one blender-group
+LAYER_DEF_NAME = 'AAAA' #default layer name
+LAYER_DEF_COLOR = 4 #default layer color
+E_M = 0
+LAB = "*) parts under construction"
+M_OBJ = 0
 
 FILENAME_MAX = 180     #max length of path+file_name string  (FILE_MAXDIR + FILE_MAXFILE)
 MAX_NAMELENGTH = 17   #max_effective_obnamelength in blender =21=17+(.001)
@@ -366,27 +382,27 @@ class View:  #-----------------------------------------------------------------
 
                self.type = obj.type
                self.name = obj.get_type(2)[0]
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
 
-               self.centerX = getit(obj.data, 10, 0.0) #view center pointX (in DCS)
-               self.centerY = getit(obj.data, 20, 0.0) #view center pointY (in DCS)
+               self.centerX = getit(obj, 10, 0.0) #view center pointX (in DCS)
+               self.centerY = getit(obj, 20, 0.0) #view center pointY (in DCS)
                self.height = obj.get_type(40)[0] #view height (in DCS)
                self.width = obj.get_type(41)[0] #view width (in DCS)
 
                self.dir = [0,0,0]
-               self.dir[0] = getit(obj.data, 11, 0.0) #view directionX from target (in WCS)
-               self.dir[1] = getit(obj.data, 21, 0.0) #
-               self.dir[2] = getit(obj.data, 31, 0.0) #
+               self.dir[0] = getit(obj, 11, 0.0) #view directionX from target (in WCS)
+               self.dir[1] = getit(obj, 21, 0.0) #
+               self.dir[2] = getit(obj, 31, 0.0) #
 
                self.target = [0,0,0]
-               self.target[0] = getit(obj.data, 12, 0.0) #target pointX(in WCS)
-               self.target[1] = getit(obj.data, 22, 0.0) #
-               self.target[2] = getit(obj.data, 32, 0.0) #
+               self.target[0] = getit(obj, 12, 0.0) #target pointX(in WCS)
+               self.target[1] = getit(obj, 22, 0.0) #
+               self.target[2] = getit(obj, 32, 0.0) #
 
                self.length = obj.get_type(42)[0] #Lens length
-               self.clip_front = getit(obj.data, 43) #Front clipping plane (offset from target point)
-               self.clip_back = getit(obj.data, 44) #Back clipping plane (offset from target point)
+               self.clip_front = getit(obj, 43) #Front clipping plane (offset from target point)
+               self.clip_back = getit(obj, 44) #Back clipping plane (offset from target point)
                self.twist  = obj.get_type(50)[0] #view twist angle in degrees
 
                self.flags = getit(obj, 70, 0)
@@ -450,28 +466,28 @@ class Vport:  #-----------------------------------------------------------------
 
                self.type = obj.type
                self.name = obj.get_type(2)[0]
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
                #print 'deb:vport name, data:', self.name #-------
                #print 'deb:vport data:', self.data #-------
 
                self.height = obj.get_type(40)[0] #vport height (in DCS)
-               self.centerX = getit(obj.data, 12, 0.0) #vport center pointX (in DCS)
-               self.centerY = getit(obj.data, 22, 0.0) #vport center pointY (in DCS)
+               self.centerX = getit(obj, 12, 0.0) #vport center pointX (in DCS)
+               self.centerY = getit(obj, 22, 0.0) #vport center pointY (in DCS)
                self.width = self.height * obj.get_type(41)[0] #vport aspect ratio - width (in DCS)
 
                self.dir = [0,0,0]
-               self.dir[0] = getit(obj.data, 16, 0.0) #vport directionX from target (in WCS)
-               self.dir[1] = getit(obj.data, 26, 0.0) #
-               self.dir[2] = getit(obj.data, 36, 0.0) #
+               self.dir[0] = getit(obj, 16, 0.0) #vport directionX from target (in WCS)
+               self.dir[1] = getit(obj, 26, 0.0) #
+               self.dir[2] = getit(obj, 36, 0.0) #
 
                self.target = [0,0,0]
-               self.target[0] = getit(obj.data, 17, 0.0) #target pointX(in WCS)
-               self.target[1] = getit(obj.data, 27, 0.0) #
-               self.target[2] = getit(obj.data, 37, 0.0) #
+               self.target[0] = getit(obj, 17, 0.0) #target pointX(in WCS)
+               self.target[1] = getit(obj, 27, 0.0) #
+               self.target[2] = getit(obj, 37, 0.0) #
 
                self.length = obj.get_type(42)[0] #Lens length
-               self.clip_front = getit(obj.data, 43) #Front clipping plane (offset from target point)
-               self.clip_back = getit(obj.data, 44) #Back clipping plane (offset from target point)
+               self.clip_front = getit(obj, 43) #Front clipping plane (offset from target point)
+               self.clip_back = getit(obj, 44) #Back clipping plane (offset from target point)
                self.twist  = obj.get_type(51)[0] #view twist angle
 
                self.flags = getit(obj, 70, 0)
@@ -528,29 +544,36 @@ class Layer:  #-----------------------------------------------------------------
        """Class for objects representing dxf LAYERs.
        """
        def __init__(self, obj, name=None, color=None, frozen=None):
-               """Expects an object of type layer as input.
+               """Expects an dxfobject of type layer as input.
+                       if no dxfobject - creates surogate layer with default parameters
                """
-               self.type = obj.type
-               self.data = obj.data[:]
-
-               if name:
-                       self.name = name
-                       #self.bfname = name  #--todo---see layernamesmap in f_getLayersmap ---
-               else:
-                       self.name = obj.get_type(2)[0] #layer name of object
-
-               if color:
-                       self.color = color
-               else:
-                       self.color = obj.get_type(62)[0]  #color of object
-
-               if frozen:
-                       self.frozen = frozen
-               else:
-                       self.flags = obj.get_type(70)[0]
-                       self.frozen = self.flags & 1
-
 
+               if obj==None:
+                       self.type = 'layer'
+                       if name: self.name = name
+                       else: self.name = LAYER_DEF_NAME
+
+                       if color: self.color = color
+                       else: self.color = LAYER_DEF_COLOR
+
+                       if frozen!=None: self.frozen = frozen
+                       else: self.frozen = 0
+               else:   
+                       if obj.type=='layer':
+                               self.type = obj.type
+                               #self.data = obj.data[:]
+                               if name: self.name = name
+                                       #self.bfname = name  #--todo---see layernamesmap in f_getLayersmap ---
+                               else: self.name = obj.get_type(2)[0] #layer name of object
+               
+                               if color: self.color = color
+                               else: self.color = obj.get_type(62)[0]  #color of object
+               
+                               if frozen!=None: self.frozen = frozen
+                               else:
+                                       self.flags = obj.get_type(70)[0]
+                                       self.frozen = self.flags & 1
+       
        def __repr__(self):
                return "%s: name - %s, color - %s" %(self.__class__.__name__, self.name, self.color)
 
@@ -615,15 +638,15 @@ class Solid:  #-----------------------------------------------------------------
                        raise TypeError, "Wrong type \'%s\' for solid/trace object!" %obj.type
 
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                self.space = getit(obj, 67, 0)
                self.thic =  getit(obj, 39, 0)
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.extrusion = get_extrusion(obj.data)
-               self.points = self.get_points(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.extrusion = get_extrusion(obj)
+               self.points = self.get_points(obj)
 
 
 
@@ -736,16 +759,16 @@ class Line:  #-----------------------------------------------------------------
                if not obj.type == 'line':
                        raise TypeError, "Wrong type \'%s\' for line object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                self.space = getit(obj, 67, 0)
                self.thic =  getit(obj, 39, 0)
                #print 'deb:self.thic: ', self.thic #---------------------
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.extrusion = get_extrusion(obj.data)
-               self.points = self.get_points(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.extrusion = get_extrusion(obj)
+               self.points = self.get_points(obj)
 
 
        def get_points(self, data):
@@ -883,16 +906,16 @@ class Point:  #-----------------------------------------------------------------
                if not obj.type == 'point':
                        raise TypeError, "Wrong type %s for point object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                self.space = getit(obj, 67, 0)
                self.thic =  getit(obj, 39, 0)
                #print 'deb:self.thic: ', self.thic #---------------------
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.extrusion = get_extrusion(obj.data)
-               self.points = self.get_points(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.extrusion = get_extrusion(obj)
+               self.points = self.get_points(obj)
 
 
        def get_points(self, data):
@@ -922,7 +945,7 @@ class Point:  #-----------------------------------------------------------------
                thic = settings.var['thick_min']
                if thic < settings.var['dist_min']: thic = settings.var['dist_min']
 
-               if True: #--todo--  points_as in [1,3,4,5]:
+               if points_as in [1,3,4,5]:
                        if True: # points_as in [1,5]: # as 'empty'
                                c = 'Empty'
                        elif points_as == 3: # as 'thin sphere'
@@ -969,11 +992,8 @@ class Polyline:  #--------------------------------------------------------------
                if not obj.type == 'polyline':
                        raise TypeError, "Wrong type %s for polyline object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
-               #print 'deb:polyline.obj.data[:]:\n', obj.data[:] #------------------------
-               self.points = []
+#              self.data = obj.data[:]
 
-               # optional data (with defaults)
                self.space = getit(obj, 67, 0)
                self.elevation =  getit(obj, 30, 0)
                #print 'deb:elevation: ', self.elevation #---------------
@@ -983,7 +1003,7 @@ class Polyline:  #--------------------------------------------------------------
                self.flags = getit(obj, 70, 0)
                self.closed = self.flags & 1   # closed in the M direction
                self.curved = self.flags & 2   # Bezier-curve-fit vertices have been added
-               self.spline = self.flags & 4   # Bspline-fit vertices have been added
+               self.spline = self.flags & 4   # NURBS-curve-fit vertices have been added
                self.poly3d = self.flags & 8   # 3D-polyline
                self.plmesh = self.flags & 16  # 3D-polygon mesh
                self.closeN = self.flags & 32  # closed in the N direction
@@ -1002,18 +1022,18 @@ class Polyline:  #--------------------------------------------------------------
                self.vectorsN =  getit(obj, 72, None) # PolyMesh: expansion in M-direction / PolyFace: number of faces
                #self.resolM =  getit(obj, 73, None) # resolution of surface in M direction
                #self.resolN =  getit(obj, 74, None) # resolution of surface in N direction
-               self.curvetyp =  getit(obj, 75, 0) # type of curve/surface: 0=None/5=Quadric/6=Cubic/8=Bezier
-               self.curvNormal = False
-               self.curvQBspline = False
-               self.curvCBspline = False
+               self.curvNoFitted = False
+               self.curvQuadrati = False
+               self.curvCubicBsp = False
                self.curvBezier = False
-               if   self.curvetyp == 0: self.curvNormal = True
-               elif self.curvetyp == 5: self.curvQBspline = True
-               elif self.curvetyp == 6: self.curvCBspline = True
-               elif self.curvetyp == 8: self.curvBezier = True
+               curvetype =  getit(obj, 75, 0) # type of curve/surface: 0=None/5=Quadric/6=Cubic/8=Bezier
+               if   curvetype == 0: self.curvNoFitted = True
+               elif curvetype == 5: self.curvQuadrati = True
+               elif curvetype == 6: self.curvCubicBsp = True
+               elif curvetype == 8: self.curvBezier = True
 
-               self.layer = getit(obj.data, 8, None)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.extrusion = get_extrusion(obj)
 
                self.points = []  #list with vertices coordinats
                self.faces  = []  #list with vertices assigment to faces
@@ -1026,9 +1046,65 @@ class Polyline:  #--------------------------------------------------------------
 
 
 
+       def doubles_out(self, settings, d_points):
+               """routine to sort out of double.vertices-----------------------------
+               """
+               minimal_dist =  settings.var['dist_min'] * 0.1
+               dv_count = 0
+               temp_points = []
+               for i in xrange(len(d_points)-1):
+                       point = d_points[i]
+                       point2 = d_points[i+1]
+                       #print 'deb:double.vertex p1,p2', point, point2 #------------------------
+                       delta = Mathutils.Vector(point2.loc) - Mathutils.Vector(point.loc)
+                       if delta.length > minimal_dist:
+                                temp_points.append(point)
+                       else:
+                               dv_count+=1
+               #print 'deb:drawPoly2d double.vertex sort out! count=', dv_count #------------------------
+               temp_points.append(d_points[-1])  #------ incl. last vertex -------------
+               #if self.closed: temp_points.append(d_points[1])  #------ loop start vertex -------------
+               d_points = temp_points   #-----vertex.list without "double.vertices"
+               #print 'deb:drawPoly2d d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
+               return d_points
+
+
+       def tribles_out(self, settings, d_points):
+               """routine to sort out of three_in_place.vertices-----------------------------
+               """
+               minimal_dist = settings.var['dist_min'] * 0.1
+               dv_count = 0
+               temp_points = []
+               for i in xrange(len(d_points)-2):
+                       point1 = d_points[i]
+                       point2 = d_points[i+1]
+                       point3 = d_points[i+2]
+                       #print 'deb:double.vertex p1,p2', point, point2 #------------------------
+                       delta12 = Mathutils.Vector(point2.loc) - Mathutils.Vector(point1.loc)
+                       delta23 = Mathutils.Vector(point3.loc) - Mathutils.Vector(point2.loc)
+                       if delta12.length < minimal_dist and delta23.length < minimal_dist:
+                               dv_count+=1
+                       else:
+                               temp_points.append(point1)
+               #print 'deb:drawPoly2d double.vertex sort out! count=', dv_count #------------------------
+               point1 = d_points[-2]
+               point2 = d_points[-1]
+               delta12 = Mathutils.Vector(point2.loc) - Mathutils.Vector(point1.loc)
+               if delta12.length > minimal_dist:
+                       temp_points.append(d_points[-2])  #------ incl. 2last vertex -------------
+               temp_points.append(d_points[-1])  #------ incl. 1last vertex -------------
+               #if self.closed: temp_points.append(d_points[1])  #------ loop start vertex -------------
+               d_points = temp_points   #-----vertex.list without "double.vertices"
+               #print 'deb:drawPoly2d d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
+               return d_points
+
+
        def draw(self, settings):   #-------------%%%% DRAW POLYLINE %%%---------------
                """for POLYLINE: generate Blender_geometry.
                """
+               #print 'deb:drawPOLYLINE.START:----------------' #------------------------
+               #print 'deb:POLYLINEdraw self.pltype:', self.pltype #------------------------
+               #print 'deb:POLYLINEdraw self.points:\n', self.points #------------------------
                ob = []
                #---- 3dPolyFace - mesh with free topology
                if self.pltype=='plface' and settings.drawTypes['plmesh']:
@@ -1036,20 +1112,28 @@ class Polyline:  #--------------------------------------------------------------
                #---- 3dPolyMesh - mesh with ortogonal topology
                elif self.pltype=='plmesh' and settings.drawTypes['plmesh']:
                        ob = self.drawPlMesh(settings)
+
                #---- 2dPolyline - plane polyline with arc/wide/thic segments
                elif self.pltype=='poly2d' and settings.drawTypes['polyline']:
-                       if settings.var['plines_as'] == 5: # and self.spline:
+                       if settings.var['plines_as'] in [5,6]: # and self.spline:
                                ob = self.drawPolyCurve(settings)
                        else:
                                ob = self.drawPoly2d(settings)
+
                #---- 3dPolyline - non-plane polyline (thin segments = without arc/wide/thic)
                elif self.pltype=='poly3d' and settings.drawTypes['pline3']:
-                       if settings.var['plines3_as'] == 5: # and self.spline:
+                       if settings.var['plines3_as'] in [5,6]: # and self.spline:
                                ob = self.drawPolyCurve(settings)
                        else:
                                ob = self.drawPoly2d(settings)
-               return ob
 
+               #---- Spline - curved polyline (thin segments = without arc/wide/thic)
+               elif self.pltype=='spline' and settings.drawTypes['spline']:
+                       if settings.var['splines_as'] in [5,6]:
+                               ob = self.drawPolyCurve(settings)
+                       else:
+                               ob = self.drawPoly2d(settings)
+               return ob
 
 
        def drawPlFace(self, settings):  #---- 3dPolyFace - mesh with free topology
@@ -1065,6 +1149,10 @@ class Polyline:  #--------------------------------------------------------------
                        else:
                                points.append(point.loc)
 
+               if settings.var['plmesh_flip']:  # ----------------------
+                       for face in faces:
+                               face.reverse()
+                               face = [face[-1]] + face[:-1]
 
                #print 'deb:drawPlFace: len of points_list:\n', len(points)  #-----------------------
                #print 'deb:drawPlFace: len of faces_list:\n', len(faces)  #-----------------------
@@ -1076,6 +1164,10 @@ class Polyline:  #--------------------------------------------------------------
                ob = SCENE.objects.new(me) # create a new mesh_object
                me.verts.extend(points) # add vertices to mesh
                me.faces.extend(faces)   # add faces to the mesh
+               if settings.var['normals_out']:  # ----------------------
+                       #me.flipNormals()
+                       me.recalcNormals(0)
+                       #me.update()
                #print 'deb:drawPlFace: len of me.faces:\n', len(me.faces)  #-----------------------
 
                if settings.var['meshSmooth_on']:  # ----------------------
@@ -1123,7 +1215,10 @@ class Polyline:  #--------------------------------------------------------------
                ob = SCENE.objects.new(me) # create a new mesh_object
                me.verts.extend([point.loc for point in self.points]) # add vertices to mesh
                me.faces.extend(faces)   # add faces to the mesh
-
+               if settings.var['normals_out']:  # ----------------------
+                       #me.flipNormals()
+                       me.recalcNormals(0)
+                       #me.update()
                if settings.var['meshSmooth_on']:  # ----------------------
                        for i in xrange(len(faces)):
                                me.faces[i].smooth = True
@@ -1142,9 +1237,9 @@ class Polyline:  #--------------------------------------------------------------
                        #print 'deb:drawPoly2d exit, cause POLYLINE has less than 2 vertices' #---------
                        return
 
-               if self.spline: pline_typ = 'ps'        # Polyline-nurbSpline
-               elif self.curved: pline_typ = 'pc'  # Polyline-bezierCurve
-               else: pline_typ = 'pl'                    # Polyline
+               if self.spline: pline_typ = 'ps'        # Polyline-NURBSpline
+               elif self.curved: pline_typ = 'pc'      # Polyline-BezierCurve
+               else: pline_typ = 'pl'                          # Polyline classic
                obname = '%s_%s' %(pline_typ, self.layer)  # create object_name from layer name
                obname = obname[:MAX_NAMELENGTH]
                d_points = []
@@ -1160,6 +1255,10 @@ class Polyline:  #--------------------------------------------------------------
                                        point.loc[2] = self.elevation
                                d_points.append(point)
 
+               #d_points = self.tribles_out(settings, d_points)
+               #d_points = self.doubles_out(settings, d_points)
+               #print 'deb:drawPolyCurve d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
+
                thic = set_thick(self.thic, settings)
                if thic != 0.0:   #hack: Blender<2.45 curve-extrusion
                        LocZ = d_points[0].loc[2]
@@ -1173,12 +1272,14 @@ class Polyline:  #--------------------------------------------------------------
                pline = Curve.New(obname)   # create new curve data
                #pline.setResolu(24) #--todo-----                                               
 
-               if self.spline:  # NURBSplines-----OK-----
+               if False: #old self.spline:  # NURBSplines-----OK-----
                        #print 'deb:polyline2dCurve.draw self.spline!' #---------------
                        weight1 = 0.5
                        weight2 = 1.0
-                       # generate middlepoints except start/end-segments ---
-                       if self.curvQBspline:
+                       if self.curvQuadrati:
+                               # Bezier-curve form simulated in NURBS-curve
+                               # generate middlepoints except start/end-segments ---
+                               #print 'deb:polyline2dCurve.draw extraQBspline!' #---------------
                                temp_points = []
                                point = d_points[0].loc
                                point.append(weight1)
@@ -1231,7 +1332,27 @@ class Polyline:  #--------------------------------------------------------------
                        else:
                                curve.flagU = 0 # Set curve not cyclic=open
 
-               elif  self.curved:  #--Bezier-curves---OK-------
+               if self.spline:  # NURBSplines-----OK-----
+                       #print 'deb:polyline2dCurve.draw self.spline!' #---------------
+                       nurbs_points = []
+                       for d in d_points:
+                               pkt = d.loc
+                               pkt.append(d.weight)
+                               nurbs_points.append(pkt)
+                       firstpoint = nurbs_points[0]
+                       curve = pline.appendNurb(firstpoint)
+                       curve.setType(4) # set curvetype NURBS
+                       for point in nurbs_points[1:]:
+                               curve.append(point)
+                       if self.closed:
+                               curve.flagU = 1+0 # Set curve cyclic=close and uni
+                       else:
+                               curve.flagU = 0+2 # Set curve not cyclic=open
+                       try: curve.orderU = 5 # works only with >2.46svn080625
+                       except AttributeError: pass
+                       #print 'deb: dir(curve):', dir(curve) #----------------
+
+               elif  False: #orig self.curved:  #--Bezier-curves---OK-------
                        #print 'deb:polyline2dCurve.draw self.curved!' #---------------
                        curve = pline.appendNurb(BezTriple.New(d_points[0]))
                        for p in d_points[1:]:
@@ -1245,7 +1366,45 @@ class Polyline:  #--------------------------------------------------------------
                                curve[0].handleTypes = [FREE, ALIGN]   #remi--todo-----
                                curve[-1].handleTypes = [ALIGN, FREE]   #remi--todo-----
 
-               else:   #--straight line- and arc-segments----OK------
+               elif  self.curved:  #--SPLINE as Bezier-curves---wip------
+                       #print 'deb:polyline2dCurve.draw self.curved!' #---------------
+                       begtangent, endtangent = None, None
+                       if d_points[0].tangent:
+                               begtangent = d_points[0]
+                               d_points = d_points[1:]
+                       if d_points[-1].tangent:
+                               endtangent = d_points[-1]
+                               d_points = d_points[:-1]
+                       curve = pline.appendNurb(BezTriple.New(d_points[0]))
+                       for p in d_points[1:]:
+                               curve.append(BezTriple.New(p))
+                       for point in curve:
+                               point.handleTypes = [AUTO, AUTO]
+                       #curve.setType(1) #Bezier curve
+                       if self.closed:
+                               curve.flagU = 5 #1 # Set curve cyclic=close
+                       else:
+                               curve.flagU = 4 #0 # Set curve not cyclic=open
+                               if begtangent:
+                                       #print 'deb:polyline2dCurve.draw curve[0].vec:', curve[0].vec #-----
+                                       #print 'deb:polyline2dCurve.draw begtangent:', begtangent #-----
+                                       p0h1,p0,p0h2 = curve[0].vec 
+                                       p0h1 = [p0h1[i]+begtangent[i] for i in range(3)]
+                                       curve.__setitem__(0,BezTriple.New(p0h1+p0+p0h2))
+                               curve[0].handleTypes = [FREE, ALIGN]   #remi--todo-----
+                               if endtangent:
+                                       #print 'deb:polyline2dCurve.draw curve[-1].vec:', curve[-1].vec #-----
+                                       #print 'deb:polyline2dCurve.draw endtangent:', endtangent #-----
+                                       p0h1,p0,p0h2 = curve[-1].vec 
+                                       p0h2 = [p0h2[i]+endtangent[i] for i in range(3)]
+                                       #print 'deb:drawPlineCurve: p0h2:', p0h2 #----------
+                                       curve.__setitem__(-1,BezTriple.New(p0h1+p0+p0h2))
+                                       #print 'deb:polyline2dCurve.draw curve[-1].vec:', curve[-1].vec #-----
+                               curve[-1].handleTypes = [ALIGN, FREE]   #remi--todo-----
+
+
+
+               else:   #-- only straight line- and arc-segments----OK------
                        #print 'deb:polyline2dCurve.draw curve:', curve #-----
                        points = []
                        arc_res = settings.var['curve_arc']
@@ -1403,8 +1562,10 @@ class Polyline:  #--------------------------------------------------------------
                #print 'deb:drawPoly2d len of d_pointsList ====== ', len(d_points) #------------------------
                #print 'deb:drawPoly2d d_pointsList ======:\n ', d_points #------------------------
 
+               d_points = self.doubles_out(settings, d_points)
+               #print 'deb:drawPolyCurve d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
 
-               # routine to sort out of "double.vertices" ------------------------------------
+               """# routine to sort out of "double.vertices" ------------------------------------
                minimal_dist =  settings.var['dist_min'] * 0.1
                temp_points = []
                for i in xrange(len(d_points)-1):
@@ -1419,6 +1580,7 @@ class Polyline:  #--------------------------------------------------------------
                #if self.closed: temp_points.append(d_points[1])  #------ loop start vertex -------------
                d_points = temp_points   #-----vertex.list without "double.vertices"
                #print 'deb:drawPoly2d d_pointsList =after DV-outsorting=====:\n ', d_points #------------------------
+               """
 
                #print 'deb:drawPoly2d len of d_pointsList ====== ', len(d_points) #------------------------
                if len(d_points) < 2:  #if too few vertex, then return
@@ -1836,12 +1998,16 @@ class Vertex(object):  #--------------------------------------------------------
                self.swidth = None #0
                self.ewidth = None #0
                self.bulge = 0
+               self.tangent = False
+               self.weight =  1.0
                if obj is not None:
                        if not obj.type == 'vertex':
                                raise TypeError, "Wrong type %s for vertex object!" %obj.type
                        self.type = obj.type
-                       self.data = obj.data[:]
-                       self.get_props(obj.data)
+#                      self.data = obj.data[:]
+                       self.get_props(obj)
+               else:
+                       pass
                #print 'deb:Vertex.init.END:----------------' #------------------------
 
 
@@ -1862,18 +2028,22 @@ class Vertex(object):  #--------------------------------------------------------
 
                self.flags  = getit(data, 70, 0) # flags
                self.curved = self.flags&1   # Bezier-curve-fit:additional-vertex
-               self.curv_t = self.flags&2   # Bezier-curve-fit:tangent exists
-               self.spline = self.flags&8   # Bspline-fit:additional-vertex
-               self.splin2 = self.flags&16  # Bspline-fit:control-vertex
+               self.curved_t = self.flags&2   # Bezier-curve-fit:tangent exists
+               self.spline = self.flags&8   # NURBSpline-fit:additional-vertex
+               self.spline_c = self.flags&16  # NURBSpline-fit:control-vertex
                self.poly3d = self.flags&32  # polyline3d:control-vertex
                self.plmesh = self.flags&64  # polymesh3d:control-vertex
                self.plface = self.flags&128 # polyface
 
                # if PolyFace.Vertex with Face_definition
-               if self.curv_t:
-                       self.curv_tangent =  getit(data, 50, None) # curve_tangent
-
-               if self.plface and not self.plmesh:
+               if self.curved_t:
+                       self.curve_tangent =  getit(data, 50, None) # curve_tangent
+                       if not self.curve_tangent==None:
+                               self.tangent = True
+               #elif self.spline_c: # NURBSpline:control-vertex
+               #       self.weight =  getit(data, 41, 1.0) # weight od control point
+
+               elif self.plface and not self.plmesh:
                        v1 = getit(data, 71, 0) # polyface:Face.vertex 1.
                        v2 = getit(data, 72, 0) # polyface:Face.vertex 2.
                        v3 = getit(data, 73, 0) # polyface:Face.vertex 3.
@@ -1938,8 +2108,7 @@ class Vertex(object):  #--------------------------------------------------------
 class Spline(Polyline):  #-----------------------------------------------------------------
        """Class for objects representing dxf SPLINEs.
        """
-       def __init__(self, obj):
-               """Expects an entity object of type spline as input.
+       """Expects an entity object of type spline as input.
 100 - Subclass marker (AcDbSpline)
 210,220, 230  - Normal vector (omitted if the spline is nonplanar) X,Y,Z values of normal vector
 70 - Spline flag (bit coded):
@@ -1963,12 +2132,13 @@ class Spline(Polyline):  #------------------------------------------------------
 DXF: X value; APP: 3D point, Y and Z values of control points (in WCS) (one entry per control point)
 11,21, 31 - Fit points (in WCS) one entry per fit point.
  X,Y,Z values of fit points (in WCS) (one entry per fit point)
-               """
+       """
+       def __init__(self, obj):
                #print 'deb:Spline.START:----------------' #------------------------
                if not obj.type == 'spline':
                        raise TypeError, "Wrong type %s for spline object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.num_points = obj.get_type(73)[0]
@@ -1992,30 +2162,42 @@ DXF: X value; APP: 3D point, Y and Z values of control points (in WCS) (one entr
                self.planar = self.flags & 8   # Planar
                self.linear = self.flags & 16  # Linear (and Planar)
 
-               self.degree = getit(obj, 71, 0) # Degree of the spline curve
-               self.curvNormal = False
-               self.curvQBspline = False
-               self.curvCBspline = False
+               self.curvNoFitted = False
+               self.curvQuadrati = False
+               self.curvCubicBsp = False
                self.curvBezier = False
-               if   self.degree == 0: self.curvNormal = True
-               elif self.degree == 1: self.curvQBspline = True
-               elif self.degree == 2: self.curvCBspline = True
+               self.degree = getit(obj, 71, 0) # Degree of the spline curve
+               if   self.degree == 0: self.curvNoFitted = True
+               elif self.degree == 1: self.curvQuadrati = True
+               elif self.degree == 2: self.curvCubicBsp = True
                #elif self.degree == 3: self.curvBezier = True
-               elif self.degree == 3: self.spline = True
+               #elif self.degree == 3: self.spline = True
        
-               self.num_knots = getit(obj, 72, 0) # Number of knots
-               self.num_contr = getit(obj, 73, 0) # Number of control points
-               self.num_fitpk = getit(obj, 74, 0) # Number of fit points (if any)
+               self.knotpk_len = getit(obj, 72, 0) # Number of knots
+               self.ctrlpk_len = getit(obj, 73, 0) # Number of control points
+               self.fit_pk_len = getit(obj, 74, 0) # Number of fit points (if any)
+
+               #print 'deb:Spline self.fit_pk_len=', self.fit_pk_len #------------------------
+               #self.fit_pk_len = 0 # temp for debug
+               if self.fit_pk_len and 'spline_as'==5:
+                       self.spline = False
+                       self.curved = True
+               else:
+                       self.spline = True
+                       self.curved = False
 
-               self.layer = getit(obj.data, 8, None)
-               self.extrusion = get_extrusion(obj.data)
+               self.knotpk_tol = getit(obj, 42, 0.0000001) # Knot tolerance (default = 0.0000001)
+               self.ctrlpk_tol = getit(obj, 43, 0.0000001) # Control-point tolerance (default = 0.0000001)
+               self.fit_pk_tol = getit(obj, 44, 0.0000000001) # Fit tolerance (default = 0.0000000001)
 
-               self.points = self.get_points(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.extrusion = get_extrusion(obj)
 
-               if self.planar: self.pltype = 'poly2d'
-               else: self.pltype = 'poly3d'
-               self.curved = False
-               #self.curved = False
+               self.pltype = 'spline'   # spline is a 2D- or 3D-polyline
+
+               self.points = self.get_points(obj.data)
+               #self.knots_val = self.get_knots_val(obj.data) # 40 - Knot value (one entry per knot)
+               #self.knots_wgh = self.get_knots_wgh(obj.data) # 41 - Weight (default 1)
 
                #print 'deb:Spline obj.data:\n', obj.data #------------------------
                #print 'deb:Spline self.points:\n', self.points #------------------------
@@ -2032,61 +2214,70 @@ DXF: X value; APP: 3D point, Y and Z values of control points (in WCS) (one entr
                20:yvalue
                for each vert
                """
-               num = self.num_contr
                point = None
                points = []
+               pointend = None
                #point = Vertex()
-               for item in data:
-                       #print 'deb:Spline item:', item #------------------------
-                       if item[0] == 10:   # control point
-                               if point: points.append(point)
-                               point = Vertex()
-                               point.curved = True
-                               point.x = item[1]
-                       elif item[0] == 20: # 20 = y
-                               point.y = item[1]
-                       elif item[0] == 30: # 30 = z
-                               point.z = item[1]
-
-                       elif item[0] == 11:   # fit point
-                               if point: points.append(point)
-                               point = Vertex()
-                               point.curved = True
-                               point.x = item[1]
-                       elif item[0] == 21: # 20 = y
-                               point.y = item[1]
-                       elif item[0] == 31: # 30 = z
-                               point.z = item[1]
-
-                       elif item[0] == 12:   # start tangent
-                               if point: points.append(point)
-                               point = Vertex()
-                               point.curved = True
-                               point.x = item[1]
-                       elif item[0] == 22: # = y
-                               point.y = item[1]
-                       elif item[0] == 32: # = z
-                               point.z = item[1]
-
-                       elif item[0] == 13:   # end tangent
-                               if point: points.append(point)
-                               point = Vertex()
-                               point.curved = True
-                               point.x = item[1]
-                       elif item[0] == 23: # 20 = y
-                               point.y = item[1]
-                       elif item[0] == 33: # 30 = z
-                               point.z = item[1]
+               if self.spline: # NURBSpline definition
+                       for item in data:
+                               #print 'deb:Spline.get_points spilne_item:', item #------------------------
+                               if item[0] == 10:   # control point
+                                       if point: points.append(point)
+                                       point = Vertex()
+                                       point.curved = True
+                                       point.x = item[1]
+                               elif item[0] == 20: # 20 = y
+                                       point.y = item[1]
+                               elif item[0] == 30: # 30 = z
+                                       point.z = item[1]
+                               elif item[0] == 41: # 41 = weight
+                                       point.weight = item[1]
+                                       #print 'deb:Spline.get_points control point:', point #------------------------
+
+               elif self.curved: # Bezier definition
+                       for item in data:
+                               #print 'deb:Spline.get_points curved_item:', item #------------------------
+                               if item[0] == 11:   # fit point
+                                       if point: points.append(point)
+                                       point = Vertex()
+                                       point.tangent = False
+                                       point.x = item[1]
+                               elif item[0] == 21: # 20 = y
+                                       point.y = item[1]
+                               elif item[0] == 31: # 30 = z
+                                       point.z = item[1]
+                                       #print 'deb:Spline.get_points fit point:', point #------------------------
+
+                               elif item[0] == 12:   # start tangent
+                                       if point: points.append(point)
+                                       point = Vertex()
+                                       point.tangent = True
+                                       point.x = item[1]
+                               elif item[0] == 22: # = y
+                                       point.y = item[1]
+                               elif item[0] == 32: # = z
+                                       point.z = item[1]
+                                       #print 'deb:Spline.get_points fit begtangent:', point #------------------------
+
+                               elif item[0] == 13:   # end tangent
+                                       if point: points.append(point)
+                                       pointend = Vertex()
+                                       pointend.tangent = True
+                                       pointend.x = item[1]
+                               elif item[0] == 23: # 20 = y
+                                       pointend.y = item[1]
+                               elif item[0] == 33: # 30 = z
+                                       pointend.z = item[1]
+                                       #print 'deb:Spline.get_points fit endtangent:', pointend #------------------------
                points.append(point)
+               if self.curved and pointend:
+                       points.append(pointend)
                #print 'deb:Spline points:\n', points #------------------------
                return points
 
-
-
        def __repr__(self):
                return "%s: layer - %s, points - %s" %(self.__class__.__name__, self.layer, self.points)
 
-
        
 
 class LWpolyline(Polyline):  #-------------------------------------------------------------
@@ -2099,7 +2290,7 @@ class LWpolyline(Polyline):  #--------------------------------------------------
                if not obj.type == 'lwpolyline':
                        raise TypeError, "Wrong type %s for polyline object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.num_points = obj.get_type(90)[0]
@@ -2118,8 +2309,8 @@ class LWpolyline(Polyline):  #--------------------------------------------------
                self.flags = getit(obj, 70, 0)
                self.closed = self.flags&1 # byte coded, 1 = closed, 128 = plinegen
 
-               self.layer = getit(obj.data, 8, None)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.extrusion = get_extrusion(obj)
 
                self.points = self.get_points(obj.data)
 
@@ -2167,72 +2358,10 @@ class LWpolyline(Polyline):  #--------------------------------------------------
                return points
 
 
-
        def __repr__(self):
                return "%s: layer - %s, points - %s" %(self.__class__.__name__, self.layer, self.points)
 
 
-       def draw_old(self, settings):
-               """for LWPOLYLINE: generate Blender_geometry.
-               """
-               #print 'deb:LWpolyline.draw.START:----------------' #------------------------
-               points = []
-               obname = 'lw_%s' %self.layer  # create object name from layer name
-               obname = obname[:MAX_NAMELENGTH]
-               #settings.var['curves_on'] == True
-               #print 'deb:index_len: ', len(self.points) #------------------
-               for i, point in enumerate(self.points):
-                       #print 'deb:index: ', i #------------------
-                       if not point.bulge:
-                               points.append(point.loc)
-                       elif point.bulge and not self.closed and i == len(self.points)-1:
-                               points.append(point.loc)
-                       elif point.bulge:        #
-                               if i == len(self.points)-1:
-                                       point2 = self.points[0]
-                               else:
-                                       point2 = self.points[i+1]
-                               arc_res = settings.var['arc_res']/sqrt(settings.var['arc_rad'])
-                               verts, center = calcBulge(point, point2, arc_res)
-#                         if i == len(self.points)-1:
-#                                 if self.closed:
-#                                         verts.pop() #remove last(=first) vertex
-#                         else:
-#                                 verts.pop() #remove last vertex, because this point will be writen as the next vertex
-                               points.extend(verts)
-
-               thic = self.thic
-               if settings.var['thick_force'] and thic == 0: thic = settings.var['thick_min']
-               if settings.var['thick_on'] and thic != 0:
-                       len1 = len(points)
-                       points.extend([[point[0], point[1], point[2]+thic] for point in points])
-                       faces = []
-                       #print 'deb:len1:', len1  #-----------------------
-                       faces = [[num, num+1, num+len1+1, num+len1] for num in xrange(len1 - 1)]
-                       if self.closed:
-                               faces.append([len1-1, 0, len1, 2*len1-1])
-                       #print 'deb:faces_list:\n', faces  #-----------------------
-                       me = Mesh.New(obname)             # create a new mesh
-                       ob = SCENE.objects.new(me) # create a new mesh_object
-                       me.verts.extend(points) # add vertices to mesh
-                       me.faces.extend(faces)   # add faces to the mesh
-               else:
-                       edges = [[num, num+1] for num in xrange(len(points)-1)]
-                       if self.closed:
-                               edges.append([len(points)-1, 0])
-                       #print 'deb:edges_list:\n', edges  #-----------------------
-                       me = Mesh.New(obname)             # create a new mesh
-                       ob = SCENE.objects.new(me) # create a new mesh_object
-                       me.verts.extend(points) # add vertices to mesh
-                       me.edges.extend(edges)   # add edges to the mesh
-
-               ob.LocZ = self.elevation
-               transform(self.extrusion, 0, ob)
-
-               #print 'deb:LWpolyline.draw.END:----------------' #------------------------
-               return ob
-
-
 class Text:  #-----------------------------------------------------------------
        """Class for objects representing dxf TEXT.
        """
@@ -2242,7 +2371,7 @@ class Text:  #-----------------------------------------------------------------
                if not obj.type == 'text':
                        raise TypeError, "Wrong type %s for text object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.height = 1.7 * obj.get_type(40)[0]  #text.height
@@ -2274,14 +2403,13 @@ class Text:  #-----------------------------------------------------------------
                #3=aligned, 4=middle, 5=fit
                self.halignment = getit(obj, 72, 0)
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc1, self.loc2 = self.get_loc(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc1, self.loc2 = self.get_loc(obj)
                if self.loc2[0] != None and self.halignment != 5: 
                        self.loc = self.loc2
                else:
                        self.loc = self.loc1
-               self.extrusion = get_extrusion(obj.data)
-
+               self.extrusion = get_extrusion(obj)
 
 
        def get_loc(self, data):
@@ -2390,13 +2518,13 @@ class Mtext:  #-----------------------------------------------------------------
                if not obj.type == 'mtext':
                        raise TypeError, "Wrong type %s for mtext object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.height = obj.get_type(40)[0]
                self.width = obj.get_type(41)[0]
                self.alignment = obj.get_type(71)[0] # alignment 1=TL, 2=TC, 3=TR, 4=ML, 5=MC, 6=MR, 7=BL, 8=BC, 9=BR
-               self.value = self.get_text(obj.data) # The text string value
+               self.value = self.get_text(obj) # The text string value
 
                # optional data (with defaults)
                self.space = getit(obj, 67, 0)
@@ -2406,9 +2534,9 @@ class Mtext:  #-----------------------------------------------------------------
                self.width_factor = getit(obj, 42, 1) # Scaling factor along local x axis
                self.line_space = getit(obj, 44, 1) # percentage of default
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc = self.get_loc(obj.data)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc = self.get_loc(obj)
+               self.extrusion = get_extrusion(obj)
 
 
        def get_text(self, data):
@@ -2487,7 +2615,7 @@ class Circle:  #----------------------------------------------------------------
                if not obj.type == 'circle':
                        raise TypeError, "Wrong type %s for circle object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.radius = obj.get_type(40)[0]
@@ -2497,9 +2625,9 @@ class Circle:  #----------------------------------------------------------------
                self.thic =  getit(obj, 39, 0)
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc = self.get_loc(obj.data)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc = self.get_loc(obj)
+               self.extrusion = get_extrusion(obj)
 
 
 
@@ -2700,7 +2828,7 @@ class Arc:  #-----------------------------------------------------------------
                if not obj.type == 'arc':
                        raise TypeError, "Wrong type %s for arc object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.radius = obj.get_type(40)[0]
@@ -2712,9 +2840,9 @@ class Arc:  #-----------------------------------------------------------------
                self.thic =  getit(obj, 39, 0)
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc = self.get_loc(obj.data)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc = self.get_loc(obj)
+               self.extrusion = get_extrusion(obj)
                #print 'deb:Arc__init__: center, radius, start, end:\n', self.loc, self.radius, self.start_angle, self.end_angle  #---------
 
 
@@ -2898,7 +3026,7 @@ class BlockRecord:  #-----------------------------------------------------------
                if not obj.type == 'block_record':
                        raise TypeError, "Wrong type %s for block_record object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.name =  getit(obj, 2, None)
@@ -2954,8 +3082,8 @@ class Block:  #-----------------------------------------------------------------
                self.entities = dxfObject('block_contents') #creates empty entities_container for this block
                self.entities.data = objectify([ent for ent in obj.data if type(ent) != list])
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc = self.get_loc(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc = self.get_loc(obj)
 
                #print 'deb:Block %s data:\n%s' %(self.name, self.data) #------------
                #print 'deb:Block %s self.entities.data:\n%s' %(self.name, self.entities.data) #------------
@@ -2999,11 +3127,11 @@ class Insert:  #----------------------------------------------------------------
                self.space = getit(obj, 67, 0)
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc = self.get_loc(obj.data)
-               self.scale = self.get_scale(obj.data)
-               self.rows, self.columns = self.get_array(obj.data)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc = self.get_loc(obj)
+               self.scale = self.get_scale(obj)
+               self.rows, self.columns = self.get_array(obj)
+               self.extrusion = get_extrusion(obj)
 
                #self.flags = getit(obj.data, 66, 0) #
                #self.attrib = self.flags & 1
@@ -3205,7 +3333,7 @@ class Ellipse:  #---------------------------------------------------------------
                if not obj.type == 'ellipse':
                        raise TypeError, "Wrong type %s for ellipse object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # required data
                self.ratio = obj.get_type(40)[0] # Ratio of minor axis to major axis
@@ -3217,10 +3345,10 @@ class Ellipse:  #---------------------------------------------------------------
                self.thic =  getit(obj, 39, 0.0)
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.loc = self.get_loc(obj.data)
-               self.major = self.get_major(obj.data)
-               self.extrusion = get_extrusion(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.loc = self.get_loc(obj)
+               self.major = self.get_major(obj)
+               self.extrusion = get_extrusion(obj)
 
 
        def get_loc(self, data):
@@ -3468,14 +3596,14 @@ class Face:  #-----------------------------------------------------------------
                if not obj.type == '3dface':
                        raise TypeError, "Wrong type %s for 3dface object!" %obj.type
                self.type = obj.type
-               self.data = obj.data[:]
+#              self.data = obj.data[:]
 
                # optional data (with defaults)
                self.space = getit(obj, 67, 0)
                self.color_index = getit(obj, 62, BYLAYER)
 
-               self.layer = getit(obj.data, 8, None)
-               self.points = self.get_points(obj.data)
+               self.layer = getit(obj, 8, None)
+               self.points = self.get_points(obj)
 
 
        def get_points(self, data):
@@ -3582,11 +3710,11 @@ type_map = {
        'point':Point,
        '3dface':Face,
        'line':Line,
-#   'mline':MLine,
+#      'mline':MLine,
        'polyline':Polyline,
        'lwpolyline':LWpolyline,
        'spline':Spline,
-#   'region':Region,
+#      'region':Region,
        'trace':Solid,
        'solid':Solid,
        'text':Text,
@@ -3623,12 +3751,12 @@ def objectify(data):  #---------------------------------------------------------
                                if item.type == 'vertex':
                                        #print 'deb:objectify gosub Vertex--------' #-------------
                                        v = Vertex(item)
-                                       if pline.spline: # if Bspline-curve
+                                       if pline.spline: # if NURBSpline-curve
                                                # then for Blender-mesh  filter only additional_vertices
                                                # OR
                                                # then for Blender-curve filter only spline_control_vertices
-                                               if (v.spline and not curves_on) or (curves_on and v.splin2): #correct for real NURBS-import
-                                               #if (v.spline and not curves_on) or (curves_on and not v.splin2): #fake for Bezier-emulation of NURBS-import
+                                               if (v.spline and not curves_on) or (curves_on and v.spline_c): #correct for real NURBS-import
+                                               #if (v.spline and not curves_on) or (curves_on and not v.spline_c): #fake for Bezier-emulation of NURBS-import
                                                        pline.points.append(v)
                                        elif pline.curved:  # if Bezier-curve
                                                # then for Blender-mesh filter only curve_additional_vertices
@@ -3685,7 +3813,7 @@ class MatColors:  #-------------------------------------------------------------
        the material.
        """
 
-       def __init__(self, layersmap):
+       def __init__(self):
                """Expects a map - a dictionary mapping layer names to layers.
                """
                #self.layersmap = layersmap  # a dictionary of layername:layerobject
@@ -3709,8 +3837,9 @@ class MatColors:  #-------------------------------------------------------------
                                #layer = Layer(name=color, color=256, frozen=False)
                                #layersmap[color] = layer
                                #color = 0
-                       if layersmap: color = layersmap[color].color
-               if color == 256:  # color 0 = BYLAYER
+                       if color in layersmap.keys():
+                               color = layersmap[color].color
+               if color == 256:  # color 256 = BYLAYER
                        #--todo-- should looking for color of LAYER
                        #if layersmap: color = layersmap[color].color
                        color = 3
@@ -3749,7 +3878,7 @@ class MatLayers:  #-------------------------------------------------------------
        the material.
        """
 
-       def __init__(self, layersmap):
+       def __init__(self):
                """Expects a map - a dictionary mapping layer names to layers.
                """
                #self.layersmap = layersmap  # a dictionary of layername:layer
@@ -3896,6 +4025,11 @@ class Settings:  #--------------------------------------------------------------
                                                   '0'
                                                  ]
 
+               self.var['groupFilter_on'] = False   #deb:remi------------
+               self.acceptedLayers = ['3',
+                                                  '0'
+                                                 ]
+
                #self.var['blockFilter_on'] = 0   #deb:remi------------
                self.acceptedBlocks = ['WALL_1871',
                                                   'BOX02'
@@ -3953,8 +4087,8 @@ class Settings:  #--------------------------------------------------------------
                if self.var['optimization'] == 0: self.var['one_mesh_on'] = 0
                # The section:tables may be partialy or completely missing.
                self.layersTable = False
-               self.colMaterials = MatColors({}) #A container for dxf-color based materials
-               self.layMaterials = MatLayers({}) #A container for dxf-layer based materials
+               self.colMaterials = MatColors() #A container for dxf-color based materials
+               self.layMaterials = MatLayers() #A container for dxf-layer based materials
                #self.collayMaterials = MatColLayers({}) #A container for dxf-color+layer based materials
                global layersmap, layernamesmap
                layersmap, layernamesmap = {}, {}
@@ -3974,8 +4108,8 @@ class Settings:  #--------------------------------------------------------------
                        if layers: #----------------------------------
                                # Read the layers table and get the layer colors
                                layersmap, layernamesmap = getLayersmap(layers)
-                               self.colMaterials = MatColors(layersmap)
-                               self.layMaterials = MatLayers(layersmap)
+                               #self.colMaterials = MatColors()
+                               #self.layMaterials = MatLayers()
                        else:
                                self.write("File contains no table:layers!")
 
@@ -4441,19 +4575,20 @@ def rotXY_Vec(rotation, vec):  #------------------------------------------------
 
 
 
-def getLayersmap(layers):  #------------------------------------------------------
+def getLayersmap(dxflayers):  #------------------------------------------------------
        """Build two dictionaries: 1.layername:layer object, and 2.layername:layername_short
+       gets set of layers from TABLES SECTION LAYERS
        """
        layersmap = {}
        layernamesmap = {}
-       for item in layers.data:
+       for item in dxflayers.data:
                if type(item) != list and item.type == 'layer':
                        layersmap[item.name] = item
                        layername_short = item.name[:MAX_NAMELENGTH-1]
                        i = 0  #sufix for layernames cause Blender-objectnames-limits
                        while layername_short in layernamesmap.keys():
                                i += 1
-                               suffix = str(i)
+                               suffix = str(i) #--todo--set zero-leading number format
                                layername_short = layername_short[:-2] + suffix
                        layernamesmap[item.name] = layername_short
 
@@ -4546,6 +4681,7 @@ def drawer(_type, entities, settings, block_def):  #----------------------------
 
        If 'block_def': the entities are to be added to the Blender 'group'.
        """
+       global layersmap, layersmapshort
        #print 'deb:drawer _type, entities:\n ', _type, entities  #-----------------------
 
        if entities:
@@ -4579,6 +4715,21 @@ def drawer(_type, entities, settings, block_def):  #----------------------------
                        #entities = [entity for entity in entities if entity.layer[0] in ['M','3','0'] and not entity.layer.endswith('H')]
                        entities = [entity for entity in entities if entity.layer in settings.acceptedLayers]
 
+               # patch for incomplete layer table in HL2-DXF-files 
+               if layersmap:
+                       for entity in entities:
+                               oblayer = entity.layer
+                               if oblayer not in layersmap.keys():
+                                       layer_obj = Layer(None, name=oblayer)
+                                       layersmap[oblayer] = layer_obj
+                                       layername_short = oblayer[:MAX_NAMELENGTH-1]
+                                       i = 0  #sufix for layernames cause Blender-objectnames-limits
+                                       while layername_short in layernamesmap.keys():
+                                               i += 1
+                                               suffix = str(i) #--todo--set zero-leading number format
+                                               layername_short = layername_short[:-2] + suffix
+                                       layernamesmap[oblayer] = layername_short
+
                # filtering only objects on not-frozen layers
                if layersmap and not settings.var['layFrozen_on']:
                        entities = [entity for entity in entities if not layersmap[entity.layer].frozen]
@@ -4785,7 +4936,7 @@ def setMaterial_from(entity, ob, settings, block_def):  #-----------------------
                        mat = settings.colMaterials(entity.color_index)
 
        elif settings.var['material_from'] == 2: # 2= material from layer_name
-               mat = settings.layMaterials(layername = entity.layer)
+               mat = settings.layMaterials(layername=entity.layer)
 
        elif settings.var['material_from'] == 3: # 3= material from layer+color
                mat = settings.layMaterials(layername=entity.layer, color=entity.color_index)
@@ -5104,7 +5255,7 @@ EVENT_HELP = 9
 EVENT_PRESETCURV = 10
 EVENT_PRESETS = 11
 EVENT_DXF_DIR = 12
-EVENT_DXF_NAME = 13
+#         = 13
 EVENT_LIST = 14
 EVENT_ORIGIN = 15
 EVENT_SCALE = 16
@@ -5119,12 +5270,12 @@ GUI_B = {}  # GUI-buttons dictionary for drawingTypes
 # settings default, initialize ------------------------
 
 points_as_menu  = "convert to: %t|empty %x1|mesh.vertex %x2|thin sphere %x3|thin box %x4|*curve.vertex %x5"
-lines_as_menu   = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|thin box %x4|curve %x5"
+lines_as_menu   = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
 mlines_as_menu  = "convert to: %t|*edge %x1|*mesh %x2|*thin cylinder %x3|*thin box %x|*curve %x5"
-plines_as_menu  = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|curve %x5"
-splines_as_menu  = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|curve %x5"
-plines3_as_menu = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|curve %x5"
-plmesh_as_menu  = "convert to: %t|*edge %x1|mesh %x2"
+plines_as_menu  = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
+splines_as_menu = "convert to: %t|mesh %x2|*thin cylinder %x3|*thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
+plines3_as_menu = "convert to: %t|*edge %x1|mesh %x2|*thin cylinder %x3|*thin box %x4|Bezier-curve %x5|NURBS-curve %x6"
+plmesh_as_menu  = "convert to: %t|*edge %x1|mesh %x2|NURBS-surface %x6"
 solids_as_menu  = "convert to: %t|*edge %x1|mesh %x2"
 blocks_as_menu  = "convert to: %t|dupliGroup %x1|*real.Group %x2|*exploded %x3"
 texts_as_menu   = "convert to: %t|text %x1|*mesh %x2|*curve %x5"
@@ -5166,6 +5317,9 @@ keywords_org = {
        'xref_on' : 1,
        'block_nn': 0,
        'blockFilter_on': 0,
+       'layerFilter_on': 0,
+       'colorFilter_on': 0,
+       'groupFilter_on': 0,
        'newScene_on' : 1,
        'target_layer' : TARGET_LAYER,
        'group_bylayer_on' : GROUP_BYLAYER,
@@ -5187,7 +5341,6 @@ keywords_org = {
        'dist_force': 0,
        'material_on': 1,
        'material_from': 2,
-       'pl_3d'  : 1,
        'fill_on'       : 1,
        'meshSmooth_on': 1,
        'curve_res' : CURV_RESOLUTION,
@@ -5197,6 +5350,8 @@ keywords_org = {
        'thin_res'  : THIN_RESOLUTION,
        'pl_trim_max' : TRIM_LIMIT,
        'pl_trim_on': 1,
+       'plmesh_flip': 0,
+       'normals_out': 0,
        'paper_space_on': 0,
        'layFrozen_on': 0,
        'Z_force_on': 0,
@@ -5205,7 +5360,7 @@ keywords_org = {
        'lines_as'  : 2,
        'mlines_as' : 2,
        'plines_as' : 2,
-       'splines_as' : 2,
+       'splines_as' : 5,
        'plines3_as': 2,
        'plmesh_as' : 2,
        'solids_as' : 2,
@@ -5221,7 +5376,7 @@ drawTypes_org = {
        'ellipse': 1,
        'mline' : 0,
        'polyline': 1,
-       'spline': 0,
+       'spline': 1,
        'plmesh': 1,
        'pline3': 1,
        'lwpolyline': 1,
@@ -5244,6 +5399,9 @@ for k, v in drawTypes_org.iteritems():
        GUI_B[k] = Draw.Create(v)
 #print 'deb:init GUI_A: ', GUI_A #---------------
 #print 'deb:init GUI_B: ', GUI_B #---------------
+
+model_space_on = Draw.Create(1)
+
 # initialize settings-object controls how dxf entities are drawn
 settings = Settings(keywords_org, drawTypes_org)
 
@@ -5397,12 +5555,13 @@ def resetDefaultConfig():  #-----------------------------------------------
        updateConfig(keywords_org, drawTypes_org)
 
 
-def presetConfig_curv():  #-----------------------------------------------
+def presetConfig_curv(activate):  #-----------------------------------------------
        """Sets settings/config/materials for curve representation.
 
        """
        global GUI_A
-       if GUI_A['curves_on'].val == 1:
+       if activate:
+               GUI_A['curves_on'].val = 1
                GUI_A['points_as'].val = 5
                GUI_A['lines_as'].val  = 5
                GUI_A['mlines_as'].val = 5
@@ -5410,11 +5569,12 @@ def presetConfig_curv():  #-----------------------------------------------
                GUI_A['splines_as'].val = 5
                GUI_A['plines3_as'].val = 5
        else:
+               GUI_A['curves_on'].val = 0
                GUI_A['points_as'].val = 2
                GUI_A['lines_as'].val  = 2
                GUI_A['mlines_as'].val = 2
                GUI_A['plines_as'].val = 2
-               GUI_A['splines_as'].val = 2
+               GUI_A['splines_as'].val = 6
                GUI_A['plines3_as'].val = 2
 
        
@@ -5422,7 +5582,7 @@ def resetDefaultConfig_2D():  #-----------------------------------------------
        """Sets settings/config/materials to defaults 2D.
 
        """
-#      presetConfig_curv()
+       presetConfig_curv(1)
        keywords2d = {
                'views_on' : 0,
                'cams_on'  : 0,
@@ -5434,7 +5594,6 @@ def resetDefaultConfig_2D():  #-----------------------------------------------
                'width_force': 0,
                'dist_on'   : 1,
                'dist_force': 0,
-               'pl_3d'  : 0,
                'fill_on'       : 0,
                'pl_trim_on': 1,
                'Z_force_on': 0,
@@ -5452,9 +5611,9 @@ def resetDefaultConfig_2D():  #-----------------------------------------------
                'ellipse': 1,
                'mline' : 0,
                'polyline': 1,
-               'spline': 0,
+               'spline': 1,
                'plmesh': 0,
-               'pline3': 0,
+               'pline3': 1,
                'lwpolyline': 1,
                'text'  : 1,
                'mtext' : 0,
@@ -5472,8 +5631,11 @@ def resetDefaultConfig_3D():  #-----------------------------------------------
        """Sets settings/config/materials to defaults 3D.
 
        """
-#      presetConfig_curv()
+       presetConfig_curv(0)
        keywords3d = {
+#              'views_on' : 1,
+#              'cams_on'  : 1,
+#              'lights_on' : 1,
                'vGroup_on' : 1,
                'thick_on'  : 1,
                'thick_force': 0,
@@ -5481,7 +5643,6 @@ def resetDefaultConfig_3D():  #-----------------------------------------------
                'width_force': 0,
                'dist_on'   : 1,
                'dist_force': 0,
-               'pl_3d'  : 0,
                'fill_on'       : 1,
                'pl_trim_on': 1,
                'Z_force_on': 0,
@@ -5499,11 +5660,11 @@ def resetDefaultConfig_3D():  #-----------------------------------------------
                'ellipse': 1,
                'mline' : 0,
                'polyline': 1,
-               'spline': 0,
+               'spline': 1,
                'plmesh': 1,
                'pline3': 1,
                'lwpolyline': 1,
-               'text'  : 1,
+               'text'  : 0,
                'mtext' : 0,
                'block' : 1,
                'insert': 1,
@@ -5557,6 +5718,7 @@ def draw_UI():  #---------------------------------------------------------------
        """
        global GUI_A, GUI_B #__version__
        global user_preset, iniFileName, dxfFileName, config_UI, g_scale_as
+       global model_space_on
 
        # This is for easy layout changes
        but_0c = 70  #button 1.column width
@@ -5567,8 +5729,8 @@ def draw_UI():  #---------------------------------------------------------------
        butt_margin = 10
        menu_w = (3 * butt_margin) + but_0c + but_1c + but_2c + but_3c  #menu width
 
-       simple_menu_h = 80
-       extend_menu_h = 370
+       simple_menu_h = 100
+       extend_menu_h = 350
        y = simple_menu_h                # y is menu upper.y
        if config_UI.val: y += extend_menu_h
        x = 20 #menu left.x
@@ -5584,7 +5746,7 @@ def draw_UI():  #---------------------------------------------------------------
 
        y += 30
        colorbox(x, y+20, x+menu_w+menu_margin*2, menu_margin)
-       Draw.Label("DXF-Importer  ver." + __version__, but0c, y, menu_w, 20)
+       Draw.Label("DXF-Importer  v" + __version__, but0c, y, menu_w, 20)
 
        if config_UI.val:
                b0, b0_ = but0c, but_0c + butt_margin
@@ -5645,25 +5807,23 @@ def draw_UI():  #---------------------------------------------------------------
                y -= 10
                y -= 20
                Draw.BeginAlign()
-               GUI_B['plmesh'] = Draw.Toggle('POLY-MESH/FACE', EVENT_NONE, b0, y, b0_+b1_, 20, GUI_B['plmesh'].val, "support dxf-POLYMESH/POLYFACE on/off")
+               GUI_B['plmesh'] = Draw.Toggle('PL-MESH/FACE', EVENT_NONE, b0, y, b0_+b1_-40, 20, GUI_B['plmesh'].val, "support dxf-POLYMESH/POLYFACE on/off")
 #              GUI_A['plmesh_as'] = Draw.Menu(plmesh_as_menu, EVENT_NONE, but1c, y, but_1c, 20, GUI_A['plmesh_as'].val, "select target Blender-object")
+               GUI_A['plmesh_flip'] = Draw.Toggle('N', EVENT_NONE, b1+b1_-40, y, 20, 20, GUI_A['plmesh_flip'].val, "flip DXF normals on/off")
+               GUI_A['normals_out'] = Draw.Toggle('N', EVENT_NONE, b1+b1_-20, y, 20, 20, GUI_A['normals_out'].val, "force Blender normals to outside on/off")
                Draw.EndAlign()
 
                y -= 20
-               Draw.BeginAlign()
                GUI_B['solid'] = Draw.Toggle('SOLID', EVENT_NONE, b0, y, b0_, 20, GUI_B['solid'].val, "support dxf-SOLID and TRACE on/off")
                GUI_B['face'] = Draw.Toggle('3DFACE', EVENT_NONE, b1, y, b1_, 20, GUI_B['face'].val, "support dxf-3DFACE on/off")
 #              GUI_A['solids_as'] = Draw.Menu(solids_as_menu, EVENT_NONE, but3c, y, but_3c, 20, GUI_A['solids_as'].val, "select target Blender-object")
-               Draw.EndAlign()
                #print 'deb:support solid, trace', GUI_B['trace'].val, GUI_B['solid'].val # ------------
 
 
                y -= 20
-               Draw.BeginAlign()
                GUI_B['text'] = Draw.Toggle('TEXT', EVENT_NONE, b0, y, b0_, 20, GUI_B['text'].val, "support dxf-TEXT on/off")
                GUI_B['mtext'] = Draw.Toggle('*MTEXT', EVENT_NONE, b1, y, b1_, 20, GUI_B['mtext'].val, "(*wip)support dxf-MTEXT on/off")
 #              GUI_A['texts_as'] = Draw.Menu(texts_as_menu, EVENT_NONE, but3c, y, but_3c, 20, GUI_A['texts_as'].val, "select target Blender-object")
-               Draw.EndAlign()
 
                y -= 20
                Draw.BeginAlign()
@@ -5671,13 +5831,14 @@ def draw_UI():  #---------------------------------------------------------------
                GUI_B['insert'].val = GUI_B['block'].val
                if GUI_B['block'].val:
                        GUI_A['block_nn'] = Draw.Toggle('n', EVENT_NONE, b1-30, y, 15, 20, GUI_A['block_nn'].val, "support hatch/noname BLOCKs *X... on/off")
-                       GUI_A['blockFilter_on'] = Draw.Toggle('F', EVENT_NONE, b1-15, y, 15, 20, GUI_A['blockFilter_on'].val, "(*wip) support name filtering of BLOCKs on/off")
-                       GUI_A['xref_on'] = Draw.Toggle('Xref', EVENT_NONE, b1, y, 20, 20, GUI_A['xref_on'].val, "support place holder for XREF-BLOCKs on/off")
+                       GUI_A['xref_on'] = Draw.Toggle('Xref', EVENT_NONE, b1-15, y, 35, 20, GUI_A['xref_on'].val, "support for XREF-BLOCKs (place holders) on/off")
                        GUI_A['blocks_as'] = Draw.Menu(blocks_as_menu, EVENT_NONE, b1+20, y, b1_-20, 20, GUI_A['blocks_as'].val, "select target representation for imported BLOCKs")
                Draw.EndAlign()
 
 
                y -= 20
+               y -= 20
+               
                Draw.BeginAlign()
                GUI_A['views_on'] = Draw.Toggle('views', EVENT_NONE, b0, y, b0_-25, 20, GUI_A['views_on'].val, "imports VIEWs and VIEWPORTs as cameras on/off")
                GUI_A['cams_on'] = Draw.Toggle('*cams', EVENT_NONE, b1-25, y, b1_-25, 20, GUI_A['cams_on'].val, "(*wip) support ASHADE cameras on/off")
@@ -5688,19 +5849,28 @@ def draw_UI():  #---------------------------------------------------------------
                if y < y_down: y_down = y
                # -----end supported objects--------------------------------------
 
-               b0, b0_ = but0c, but_0c + butt_margin
-               b1, b1_ = but1c, but_1c
-
                y_top = y_down
                y = y_top
                y -= 10
                y -= 20
+               but_ = menu_w / 6
+               b0 = but0c + (menu_w - but_*6)/2
                Draw.BeginAlign()
-               GUI_A['material_on'] = Draw.Toggle('material', EVENT_REDRAW, b0, y, b0_-20, 20, GUI_A['material_on'].val, "support for material assignment on/off")
-               if GUI_A['material_on'].val:
-                       GUI_A['material_from'] = Draw.Menu(material_from_menu,   EVENT_NONE, b1-20, y, b1_+20, 20, GUI_A['material_from'].val, "material assignment from?")
+               GUI_A['paper_space_on'] = Draw.Toggle('paper', EVENT_NONE, b0+but_*0, y, but_, 20, GUI_A['paper_space_on'].val, "import only from Paper-Space on/off")
+               GUI_A['layFrozen_on'] = Draw.Toggle ('frozen', EVENT_NONE, b0+but_*1, y, but_, 20, GUI_A['layFrozen_on'].val, "import also from frozen LAYERs on/off")
+               GUI_A['layerFilter_on'] = Draw.Toggle('layer', EVENT_NONE, b0+but_*2, y, but_, 20, GUI_A['layerFilter_on'].val, "(*wip) LAYER filtering on/off")
+               GUI_A['colorFilter_on'] = Draw.Toggle('color', EVENT_NONE, b0+but_*3, y, but_, 20, GUI_A['colorFilter_on'].val, "(*wip) COLOR filtering on/off")
+               GUI_A['groupFilter_on'] = Draw.Toggle('group', EVENT_NONE, b0+but_*4, y, but_, 20, GUI_A['groupFilter_on'].val, "(*wip) GROUP filtering on/off")
+               GUI_A['blockFilter_on'] = Draw.Toggle('block', EVENT_NONE, b0+but_*5, y, but_, 20, GUI_A['blockFilter_on'].val, "(*wip) BLOCK filtering on/off")
+               #GUI_A['dummy_on'] = Draw.Toggle('-', EVENT_NONE, but3c, y, but_3c, 20, GUI_A['dummy_on'].val, "dummy on/off")
                Draw.EndAlign()
 
+               # -----end filters--------------------------------------
+
+               b0, b0_ = but0c, but_0c + butt_margin
+               b1, b1_ = but1c, but_1c
+
+               y -= 10
                y -= 20
                Draw.BeginAlign()
                GUI_A['g_origin_on'] = Draw.Toggle('glob.reLoc', EVENT_REDRAW, b0, y, b0_, 20, GUI_A['g_origin_on'].val, "global relocate all DXF objects on/off")
@@ -5750,9 +5920,9 @@ def draw_UI():  #---------------------------------------------------------------
                y -= 10
                y -= 20
                Draw.BeginAlign()
-               GUI_A['meshSmooth_on'] = Draw.Toggle('smooth', EVENT_NONE, b0, y, b0_-20, 20, GUI_A['meshSmooth_on'].val, "mesh smooth for circles/arcsegments on/off")
-               GUI_A['pl_trim_on'] = Draw.Toggle('trim', EVENT_NONE, b1-20, y, 32, 20, GUI_A['pl_trim_on'].val, "intersection of POLYLINE-wide-segments on/off")
-               GUI_A['pl_trim_max'] = Draw.Number('', EVENT_NONE, b1+12, y,  b1_-12, 20, GUI_A['pl_trim_max'].val, 0, 5, "limit for intersection of POLYLINE-wide-segments: 0.0-5.0")
+               GUI_A['meshSmooth_on'] = Draw.Toggle('smooth', EVENT_NONE, b0, y, b0_-20, 20, GUI_A['meshSmooth_on'].val, "mesh smooth for circles/arc-segments on/off")
+               GUI_A['pl_trim_on'] = Draw.Toggle('trim', EVENT_NONE, b1-20, y, 32, 20, GUI_A['pl_trim_on'].val, "clean intersection of POLYLINE-wide-segments on/off")
+               GUI_A['pl_trim_max'] = Draw.Number('', EVENT_NONE, b1+12, y,  b1_-12, 20, GUI_A['pl_trim_max'].val, 0, 5, "threshold intersection of POLYLINE-wide-segments: 0.0-5.0")
                Draw.EndAlign()
 
                y -= 20
@@ -5765,21 +5935,21 @@ def draw_UI():  #---------------------------------------------------------------
 
                y -= 20
                Draw.BeginAlign()
-               GUI_A['curves_on'] = Draw.Toggle('to Curves', EVENT_PRESETCURV, b0, y, b0_, 20, GUI_A['curves_on'].val, "import into curves instead into meshes on/off")
-               GUI_A['curve_arc'] = Draw.Number('', EVENT_NONE, b1, y, b1_/2, 20, GUI_A['curve_arc'].val, 3, 32, "Bezier circle: amount of segments: 3-32")
-               GUI_A['curve_res'] = Draw.Number('', EVENT_NONE, b1+b1_/2, y,  b1_/2, 20, GUI_A['curve_res'].val, 1, 128, "Set the Curve's U-resolution value: 1-128")
+               GUI_A['curve_arc'] = Draw.Number('', EVENT_NONE, b0, y, b0_/2, 20, GUI_A['curve_arc'].val, 3, 32, "Bezier circle: amount of segments: 3-32")
+               GUI_A['curve_res'] = Draw.Number('', EVENT_NONE, b0+b0_/2, y,  b0_/2, 20, GUI_A['curve_res'].val, 1, 128, "Set the Curve's U-resolution value: 1-128")
+               GUI_A['curves_on'] = Draw.Toggle('to Curves', EVENT_PRESETCURV, b1, y, b1_, 20, GUI_A['curves_on'].val, "set Curve as target object type on/off")
                Draw.EndAlign()
 
                y -= 20
-               GUI_A['group_bylayer_on'] = Draw.Toggle('Lay', EVENT_NONE, b0, y, 30, 20, GUI_A['group_bylayer_on'].val, "grouping entities from the same layer on/off")
-               GUI_A['vGroup_on'] = Draw.Toggle('vGroups', EVENT_NONE, b0+30, y, b1_-10, 20, GUI_A['vGroup_on'].val, "support Blender-VertexGroups on/off")
+               GUI_A['group_bylayer_on'] = Draw.Toggle('Layer', EVENT_NONE, b0, y, 30, 20, GUI_A['group_bylayer_on'].val, "DXF-entities group by layer on/off")
+               GUI_A['vGroup_on'] = Draw.Toggle('vGroups', EVENT_NONE, b0+30, y, b1_-10, 20, GUI_A['vGroup_on'].val, "sort faces into VertexGroups on/off")
                GUI_A['one_mesh_on'] = Draw.Toggle('oneMesh', EVENT_NONE, b1+10, y, b1_-10, 20, GUI_A['one_mesh_on'].val, "draw DXF-entities into one mesh-object. Recommended for big DXF-files. on/off")
 
                y -= 30
                Draw.BeginAlign()
-               GUI_A['paper_space_on'] = Draw.Toggle('paper space', EVENT_NONE, b0, y, b0_+20, 20, GUI_A['paper_space_on'].val, "import only layout (paper space) on/off")
-               GUI_A['layFrozen_on'] = Draw.Toggle('frozen', EVENT_NONE, b1+20, y, b1_-20, 20, GUI_A['layFrozen_on'].val, "import also from frozen layers on/off")
-               #GUI_A['dummy_on'] = Draw.Toggle('-', EVENT_NONE, but3c, y, but_3c, 20, GUI_A['dummy_on'].val, "dummy on/off")
+               GUI_A['material_on'] = Draw.Toggle('material', EVENT_REDRAW, b0, y, b0_-20, 20, GUI_A['material_on'].val, "support for material assignment on/off")
+               if GUI_A['material_on'].val:
+                       GUI_A['material_from'] = Draw.Menu(material_from_menu,   EVENT_NONE, b1-20, y, b1_+20, 20, GUI_A['material_from'].val, "material assignment from?")
                Draw.EndAlign()
 
                y_down = y
@@ -5821,8 +5991,9 @@ def draw_UI():  #---------------------------------------------------------------
                Draw.EndAlign()
 
                y -= 30
-               GUI_A['newScene_on'] = Draw.Toggle('newScene', EVENT_NONE, b0, y, b0_, 20, GUI_A['newScene_on'].val, "creates new Blender-Scene for each import on/off")
-               GUI_A['target_layer'] = Draw.Number('layer', EVENT_NONE, b1, y, b1_, 20, GUI_A['target_layer'].val, 1, 18, "imports into this Blender-layer (<19> reserved for block_definitions)")
+               but, but_ = but2c, 25
+               Draw.BeginAlign()
+               Draw.EndAlign()
 
                if y < y_down: y_down = y
                # -----end options --------------------------------------
@@ -5835,45 +6006,60 @@ def draw_UI():  #---------------------------------------------------------------
                y -= 30
                Draw.BeginAlign()
                Draw.PushButton('INI file >', EVENT_CHOOSE_INI, but0c, y, but_0c, 20, 'Select INI-file from project directory')
-               iniFileName = Draw.String(' :', EVENT_NONE, but1c, y, menu_w-but_0c-butt_margin, 20, iniFileName.val, FILENAME_MAX, "write here the name of the INI-file")
+               iniFileName = Draw.String(' :', EVENT_NONE, but1c, y, menu_w-but_1c-60, 20, iniFileName.val, FILENAME_MAX, "write here the name of the INI-file")
+               but = but4c-60
+               Draw.PushButton('#', EVENT_PRESETS, but, y, 20, 20, "toggle Preset-INI-files")
+               Draw.PushButton('L', EVENT_LOAD_INI, but+20, y, 20, 20, 'Loads configuration from ini-file: %s' % iniFileName.val)
+               Draw.PushButton('S', EVENT_SAVE_INI, but+40, y, 20, 20, 'Saves configuration to ini-file: %s' % iniFileName.val)
                Draw.EndAlign()
 
-               y -= 20
-               Draw.BeginAlign()
-               Draw.PushButton('#', EVENT_PRESETS, but0c, y, 20, 20, "tipist for Preset-INI-files")
-               Draw.PushButton('Load', EVENT_LOAD_INI, but0c+20, y, but_0c-20, 20, '.Loads configuration from ini-file: %s' % iniFileName.val)
-               Draw.PushButton('Save', EVENT_SAVE_INI, but1c, y, but_1c-20, 20, 'Saves configuration to ini-file: %s' % iniFileName.val)
-               Draw.EndAlign()
-               but_ = (but_2c+but_3c)/4
-               but = but2c
-               Draw.PushButton('reset', EVENT_RESET, but, y, but_, 20, "reset configuration to defaults")
-               Draw.PushButton('2D', EVENT_PRESET2D, but+but_, y, but_, 20, 'set configuration for 2D import')
-               Draw.PushButton('3D', EVENT_PRESET3D, but+but_*2, y, but_, 20, 'set configuration for 3D import')
-               GUI_A['optimization'] = Draw.Number('', EVENT_NONE, but4c-35, y, 35, 20, GUI_A['optimization'].val, 0, 3, "Optimization Level: 0=Debug/directDrawing, 1=Verbose, 2=ProgressBar, 3=silentMode/fastest")
 
+       b0, b0_ = but2c, but_2c + butt_margin
+       b1, b1_ = but3c, but_3c
 
        y =     simple_menu_h
+       bm = butt_margin/2
+
+       #y -= 10
        Draw.BeginAlign()
        Draw.PushButton('DXFfile >', EVENT_CHOOSE_DXF, but0c, y, but_0c, 20, 'Select DXF-file from project directory')
        dxfFileName = Draw.String(' :', EVENT_NONE, but1c, y, but_1c+but_2c+but_3c-20, 20, dxfFileName.val, FILENAME_MAX, "type the name of DXF-file or type *.dxf for multi-import")
-       Draw.PushButton('*.*', EVENT_DXF_DIR, but3c+but_3c-20, y, 20, 20, 'Set asterisk * as filter')
+       Draw.PushButton('*.*', EVENT_DXF_DIR, but3c+but_3c-20, y, 20, 20, 'import all dxf files from this directory')
        Draw.EndAlign()
 
+       y -= 30
+       config_UI = Draw.Toggle('CONFIG', EVENT_REDRAW, but0c, y, but_0c+bm, 20, config_UI.val, 'Advanced configuration on/off' )
+       Draw.BeginAlign()
+       but, but_ = but1c, but_1c+bm
+       but_ /= 3
+       Draw.PushButton('X', EVENT_RESET, but, y, 15, 20, "reset configuration to defaults")
+       Draw.PushButton('2D', EVENT_PRESET2D, but+but_, y, but_, 20, 'set configuration for 2D import')
+       Draw.PushButton('3D', EVENT_PRESET3D, but+(but_*2), y, but_, 20, 'set configuration for 3D import')
+       Draw.EndAlign()
 
-       y -= 50
        Draw.BeginAlign()
-       Draw.PushButton('EXIT', EVENT_EXIT, but0c, y, but_0c, 40, '' )
-       Draw.PushButton('HELP', EVENT_HELP, but1c, y, but_1c-20, 20, 'calls BlenderWiki for Manual, Updates and Support.')
-       Draw.PushButton('?', EVENT_LIST, but1c+but_1c-20, y, 20, 20, 'DXF analyze tool: print listing of LAYERs and BLOCKs into the text file .INF')
-       Draw.PushButton('START IMPORT', EVENT_START, but2c, y, but_2c+but_3c+butt_margin, 40, 'Start the import procedure')
+       GUI_A['newScene_on'] = Draw.Toggle('newScene', EVENT_NONE, but2c, y, but_2c, 20, GUI_A['newScene_on'].val, "create new Scene for each imported dxf file on/off")
+       GUI_A['target_layer'] = Draw.Number('layer', EVENT_NONE, but3c, y, but_3c, 20, GUI_A['target_layer'].val, 1, 18, "target Blender-layer (<19> reserved for block_definitions)")
        Draw.EndAlign()
 
-       config_UI = Draw.Toggle('CONFIG', EVENT_REDRAW, but1c-butt_margin/2, y+20, but_1c+butt_margin, 20, config_UI.val, 'Advanced configuration on/off' )
+       y -= 40
+       Draw.PushButton('EXIT', EVENT_EXIT, but0c, y, but_0c+bm, 20, '' )
+       Draw.PushButton('HELP', EVENT_HELP, but1c, y, but_1c+bm, 20, 'calls DXF-Importer Manual Page on Wiki.Blender.org')
+       Draw.BeginAlign()
+       GUI_A['optimization'] = Draw.Number('', EVENT_NONE, but2c, y+20, 40, 20, GUI_A['optimization'].val, 0, 3, "Optimization Level: 0=Debug/directDrawing, 1=Verbose, 2=ProgressBar, 3=SilentMode")
+       Draw.EndAlign()
+       Draw.BeginAlign()
+       Draw.PushButton('TEST', EVENT_LIST, but2c, y, 40, 20, 'DXF-Analyze-Tool: reads data from selected dxf file and writes report in project_directory/dxf_blendname.INF')
+       Draw.PushButton('START IMPORT', EVENT_START, but2c+40, y, but_2c-40+but_3c+butt_margin, 40, 'Start the import process. For Cancel go to console and hit Ctrl-C')
+       Draw.EndAlign()
+
+
+
 
        y -= 20
        Draw.BeginAlign()
        Draw.Label(' ', but0c-menu_margin, y, menu_margin, 20)
-       Draw.Label("*) parts under construction", but0c, y, menu_w, 20)
+       Draw.Label(LAB, but0c, y, menu_w, 20)
        Draw.Label(' ', but0c+menu_w, y, menu_margin, 20)
        Draw.EndAlign()
 
@@ -5930,7 +6116,7 @@ def bevent(evt):
                resetDefaultConfig_3D()
                Draw.Redraw()
        elif (evt==EVENT_PRESETCURV):
-               presetConfig_curv()
+               presetConfig_curv(GUI_A['curves_on'].val)
                Draw.Redraw()
        elif (evt==EVENT_PRESETS):
                user_preset += 1
@@ -5974,11 +6160,6 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Import/DXF-3D')
 #              update_RegistryKey('dxfFileName', dxfFileName.val)
                GUI_A['newScene_on'].val = 1
                Draw.Redraw()
-#      elif (evt==EVENT_DXF_NAME):
-#              dirname == Blender.sys.dirname(Blender.Get('filename'))
-#              update_RegistryKey('DirName', dirname)
-#              #print 'deb:EVENT_DXF_NAME dxfFileName.val:', dxfFileName.val #--------------
-#              update_RegistryKey('dxfFileName', dxfFileName.val)
        elif (evt==EVENT_CHOOSE_DXF):
                filename = '' # '*.dxf'
                if dxfFileName.val:     filename = dxfFileName.val
@@ -5986,6 +6167,7 @@ http://wiki.blender.org/index.php?title=Scripts/Manual/Import/DXF-3D')
        elif (evt==EVENT_START):
                dxfFile = dxfFileName.val
                #print 'deb: dxfFile file: ', dxfFile #----------------------
+               if E_M: dxfFileName.val, dxfFile = e_mode(dxfFile) #evaluation mode
                update_RegistryKey('dxfFileName', dxfFileName.val)
                if dxfFile.lower().endswith('*.dxf'):
                        if Draw.PupMenu('DXF importer:  OK?|will import all DXF-files from:|%s' % dxfFile) == 1:
index ba1896f011e41fe5cdd30dc1e67d2e675f3c4650..ca2184bade401b05c9ca567bd8b230d399b33901 100644 (file)
@@ -25,7 +25,7 @@ It removes very low weighted verts from the current group with a weight option.
 # 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
@@ -51,13 +51,14 @@ def weightClean(me, PREF_THRESH, PREF_KEEP_SINGLE, PREF_OTHER_GROUPS):
                for wd in vWeightDict:
                        l = len(wd)
                        if not PREF_KEEP_SINGLE or l > 1:
+                               # cant use iteritems because the dict is having items removed
                                for group in wd.keys():
                                        w= wd[group]
                                        if w <= PREF_THRESH:
                                                # small weight, remove.
                                                del wd[group]
                                                rem_count +=1
-                                       l-=1
+                                               l-=1
                                        
                                        if PREF_KEEP_SINGLE and l == 1:
                                                break
@@ -117,4 +118,4 @@ def main():
        Draw.PupMenu('Removed %i verts from groups' % rem_count)
        
 if __name__=='__main__':
-       main()
\ No newline at end of file
+       main()
diff --git a/source/blender/blenkernel/BKE_bvhutils.h b/source/blender/blenkernel/BKE_bvhutils.h
new file mode 100644 (file)
index 0000000..dd9ea61
--- /dev/null
@@ -0,0 +1,98 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** 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.
+ *
+ * The Original Code is Copyright (C) 2006 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): AndrĂ© Pinto
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef BKE_BVHUTILS_H
+#define BKE_BVHUTILS_H
+
+#include "BLI_kdopbvh.h"
+
+/*
+ * This header encapsulates necessary code to buld a BVH
+ */
+
+struct DerivedMesh;
+struct MVert;
+struct MFace;
+
+/*
+ * struct that kepts basic information about a BVHTree build from a mesh
+ */
+typedef struct BVHTreeFromMesh
+{
+       struct BVHTree *tree;
+
+       /* default callbacks to bvh nearest and raycast */
+       BVHTree_NearestPointCallback nearest_callback;
+       BVHTree_RayCastCallback      raycast_callback;
+
+       /* Mesh represented on this BVHTree */
+       struct DerivedMesh *mesh; 
+
+       /* Vertex array, so that callbacks have instante access to data */
+       struct MVert *vert;
+       struct MFace *face;
+
+       /* radius for raycast */
+       float sphere_radius;
+
+} BVHTreeFromMesh;
+
+/*
+ * Builds a bvh tree where nodes are the vertexs of the given mesh.
+ * Configures BVHTreeFromMesh.
+ *
+ * The tree is build in mesh space coordinates, this means special care must be made on queries
+ * so that the coordinates and rays are first translated on the mesh local coordinates.
+ * Reason for this is that later bvh_from_mesh_* might use a cache system and so it becames possible to reuse
+ * a BVHTree.
+ * 
+ * free_bvhtree_from_mesh should be called when the tree is no longer needed.
+ */
+void bvhtree_from_mesh_verts(struct BVHTreeFromMesh *data, struct DerivedMesh *mesh, float epsilon, int tree_type, int axis);
+
+/*
+ * Builds a bvh tree where nodes are the faces of the given mesh.
+ * Configures BVHTreeFromMesh.
+ *
+ * The tree is build in mesh space coordinates, this means special care must be made on queries
+ * so that the coordinates and rays are first translated on the mesh local coordinates.
+ * Reason for this is that later bvh_from_mesh_* might use a cache system and so it becames possible to reuse
+ * a BVHTree.
+ * 
+ * free_bvhtree_from_mesh should be called when the tree is no longer needed.
+ */
+void bvhtree_from_mesh_faces(struct BVHTreeFromMesh *data, struct DerivedMesh *mesh, float epsilon, int tree_type, int axis);
+
+/*
+ * Frees data allocated by a call to bvhtree_from_mesh_*.
+ */
+void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data);
+
+#endif
+
index fade0f8cbaa4a1b1555b7c85894c2658e076a859..c162a04e0557a7859302a0d69ec7e16890049ab5 100644 (file)
@@ -73,6 +73,7 @@ void    BKE_free_envmap(struct EnvMap *env);
 struct EnvMap *BKE_add_envmap(void);
 struct EnvMap *BKE_copy_envmap(struct EnvMap *env);
 
+int     BKE_texture_dependsOnTime(const struct Tex *texture);
 
 #endif
 
index 3ad11a61de33125e6a08cc76b2ae8805c6cfb462..561d8d7c2a6bda1c843898f112ff3f971a776f71 100644 (file)
@@ -117,10 +117,14 @@ float BPY_pydriver_eval(struct IpoDriver *driver)
 {
        return 0;
 }
+
+/*
 int EXPP_dict_set_item_str(struct PyObject *dict, char *key, struct PyObject *value)
 {
        return 0;
 }
+*/
+
 void Node_SetStack(struct BPy_Node *self, struct bNodeStack **stack, int type){}
 void InitNode(struct BPy_Node *self, struct bNode *node){}
 void Node_SetShi(struct BPy_Node *self, struct ShadeInput *shi){}
index 1f8dd74a6ebd333cd266f6e739b63a3ece142979..1592c3e55042b2289c41581fd87ddcde7c84155d 100644 (file)
@@ -734,9 +734,8 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Object *par, float par_
        ParticleCacheKey *cache;
        ParticleSystemModifierData *psmd;
        float ctime, pa_time, scale = 1.0f;
-       float tmat[4][4], mat[4][4], obrotmat[4][4], pamat[4][4], size=0.0;
+       float tmat[4][4], mat[4][4], pamat[4][4], size=0.0;
        float (*obmat)[4], (*oldobmat)[4];
-       float xvec[3] = {-1.0, 0.0, 0.0}, q[4];
        int lay, a, b, k, step_nbr = 0, counter, hair = 0;
        int totpart, totchild, totgroup=0, pa_num;
 
@@ -898,14 +897,7 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Object *par, float par_
                                        /* to give ipos in object correct offset */
                                        where_is_object_time(ob, ctime-pa_time);
                                        
-                                       if(!hair) {
-                                               vectoquat(xvec, ob->trackflag, ob->upflag, q);
-                                               QuatToMat4(q, obrotmat);
-                                               obrotmat[3][3]= 1.0f;
-                                               Mat4MulMat4(mat, obrotmat, pamat);
-                                       }
-                                       else
-                                               Mat4CpyMat4(mat, pamat);
+                                       Mat4CpyMat4(mat, pamat);
 
                                        Mat4MulMat4(tmat, obmat, mat);
                                        Mat4MulFloat3((float *)tmat, size*scale);
diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c
new file mode 100644 (file)
index 0000000..10e92b8
--- /dev/null
@@ -0,0 +1,433 @@
+/**
+ *
+ * $Id$
+ *
+ * ***** 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.
+ *
+ * The Original Code is Copyright (C) Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): AndrĂ© Pinto.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#include "BKE_bvhutils.h"
+
+#include "DNA_object_types.h"
+#include "DNA_modifier_types.h"
+#include "DNA_meshdata_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_utildefines.h"
+#include "BKE_deform.h"
+#include "BKE_cdderivedmesh.h"
+#include "BKE_displist.h"
+#include "BKE_global.h"
+
+#include "BLI_arithb.h"
+
+/* Math stuff for ray casting on mesh faces and for nearest surface */
+
+static float nearest_point_in_tri_surface(const float *point, const float *v0, const float *v1, const float *v2, float *nearest);
+
+#define ISECT_EPSILON 1e-6
+static float ray_tri_intersection(const BVHTreeRay *ray, const float m_dist, const float *v0, const float *v1, const float *v2)
+{
+       float dist;
+
+       if(RayIntersectsTriangle((float*)ray->origin, (float*)ray->direction, (float*)v0, (float*)v1, (float*)v2, &dist, NULL))
+               return dist;
+
+       return FLT_MAX;
+}
+
+static float sphereray_tri_intersection(const BVHTreeRay *ray, float radius, const float m_dist, const float *v0, const float *v1, const float *v2)
+{
+       
+       float idist;
+       float p1[3];
+       float plane_normal[3], hit_point[3];
+
+       CalcNormFloat((float*)v0, (float*)v1, (float*)v2, plane_normal);
+
+       VECADDFAC( p1, ray->origin, ray->direction, m_dist);
+       if(SweepingSphereIntersectsTriangleUV((float*)ray->origin, p1, radius, (float*)v0, (float*)v1, (float*)v2, &idist, hit_point))
+       {
+               return idist * m_dist;
+       }
+
+       return FLT_MAX;
+}
+
+/*
+ * This calculates the distance from point to the plane
+ * Distance is negative if point is on the back side of plane
+ */
+static float point_plane_distance(const float *point, const float *plane_point, const float *plane_normal)
+{
+       float pp[3];
+       VECSUB(pp, point, plane_point);
+       return INPR(pp, plane_normal);
+}
+static float choose_nearest(const float v0[2], const float v1[2], const float point[2], float closest[2])
+{
+       float d[2][2], sdist[2];
+       VECSUB2D(d[0], v0, point);
+       VECSUB2D(d[1], v1, point);
+
+       sdist[0] = d[0][0]*d[0][0] + d[0][1]*d[0][1];
+       sdist[1] = d[1][0]*d[1][0] + d[1][1]*d[1][1];
+
+       if(sdist[0] < sdist[1])
+       {
+               if(closest)
+                       VECCOPY2D(closest, v0);
+               return sdist[0];
+       }
+       else
+       {
+               if(closest)
+                       VECCOPY2D(closest, v1);
+               return sdist[1];
+       }
+}
+/*
+ * calculates the closest point between point-tri (2D)
+ * returns that tri must be right-handed
+ * Returns square distance
+ */
+static float closest_point_in_tri2D(const float point[2], /*const*/ float tri[3][2], float closest[2])
+{
+       float edge_di[2];
+       float v_point[2];
+       float proj[2];                                  //point projected over edge-dir, edge-normal (witouth normalized edge)
+       const float *v0 = tri[2], *v1;
+       float edge_slen, d;                             //edge squared length
+       int i;
+       const float *nearest_vertex = NULL;
+
+
+       //for each edge
+       for(i=0, v0=tri[2], v1=tri[0]; i < 3; v0=tri[i++], v1=tri[i])
+       {
+               VECSUB2D(edge_di,    v1, v0);
+               VECSUB2D(v_point, point, v0);
+
+               proj[1] =  v_point[0]*edge_di[1] - v_point[1]*edge_di[0];       //dot product with edge normal
+
+               //point inside this edge
+               if(proj[1] < 0)
+                       continue;
+
+               proj[0] = v_point[0]*edge_di[0] + v_point[1]*edge_di[1];
+
+               //closest to this edge is v0
+               if(proj[0] < 0)
+               {
+                       if(nearest_vertex == NULL || nearest_vertex == v0)
+                               nearest_vertex = v0;
+                       else
+                       {
+                               //choose nearest
+                               return choose_nearest(nearest_vertex, v0, point, closest);
+                       }
+                       i++;    //We can skip next edge
+                       continue;
+               }
+
+               edge_slen = edge_di[0]*edge_di[0] + edge_di[1]*edge_di[1];      //squared edge len
+               //closest to this edge is v1
+               if(proj[0] > edge_slen)
+               {
+                       if(nearest_vertex == NULL || nearest_vertex == v1)
+                               nearest_vertex = v1;
+                       else
+                       {
+                               return choose_nearest(nearest_vertex, v1, point, closest);
+                       }
+                       continue;
+               }
+
+               //nearest is on this edge
+               d= proj[1] / edge_slen;
+               closest[0] = point[0] - edge_di[1] * d;
+               closest[1] = point[1] + edge_di[0] * d;
+
+               return proj[1]*proj[1]/edge_slen;
+       }
+
+       if(nearest_vertex)
+       {
+               VECSUB2D(v_point, nearest_vertex, point);
+               VECCOPY2D(closest, nearest_vertex);
+               return v_point[0]*v_point[0] + v_point[1]*v_point[1];
+       }
+       else
+       {
+               VECCOPY(closest, point);        //point is already inside
+               return 0.0f;
+       }
+}
+
+/*
+ * Returns the square of the minimum distance between the point and a triangle surface
+ * If nearest is not NULL the nearest surface point is written on it
+ */
+static float nearest_point_in_tri_surface(const float *point, const float *v0, const float *v1, const float *v2, float *nearest)
+{
+       //Lets solve the 2D problem (closest point-tri)
+       float normal_dist, plane_sdist, plane_offset;
+       float du[3], dv[3], dw[3];      //orthogonal axis (du=(v0->v1), dw=plane normal)
+
+       float p_2d[2], tri_2d[3][2], nearest_2d[2];
+
+       CalcNormFloat((float*)v0, (float*)v1, (float*)v2, dw);
+
+       //point-plane distance and calculate axis
+       normal_dist = point_plane_distance(point, v0, dw);
+
+       // OPTIMIZATION
+       //      if we are only interested in nearest distance if its closer than some distance already found
+       //  we can:
+       //              if(normal_dist*normal_dist >= best_dist_so_far) return FLOAT_MAX;
+       //
+
+       VECSUB(du, v1, v0);
+       Normalize(du);
+       Crossf(dv, dw, du);
+       plane_offset = INPR(v0, dw);
+
+       //project stuff to 2d
+       tri_2d[0][0] = INPR(du, v0);
+       tri_2d[0][1] = INPR(dv, v0);
+
+       tri_2d[1][0] = INPR(du, v1);
+       tri_2d[1][1] = INPR(dv, v1);
+
+       tri_2d[2][0] = INPR(du, v2);
+       tri_2d[2][1] = INPR(dv, v2);
+
+       p_2d[0] = INPR(du, point);
+       p_2d[1] = INPR(dv, point);
+
+       //we always have a right-handed tri
+       //this should always happen because of the way normal is calculated
+       plane_sdist = closest_point_in_tri2D(p_2d, tri_2d, nearest_2d);
+
+       //project back to 3d
+       if(nearest)
+       {
+               nearest[0] = du[0]*nearest_2d[0] + dv[0] * nearest_2d[1] + dw[0] * plane_offset;
+               nearest[1] = du[1]*nearest_2d[0] + dv[1] * nearest_2d[1] + dw[1] * plane_offset;
+               nearest[2] = du[2]*nearest_2d[0] + dv[2] * nearest_2d[1] + dw[2] * plane_offset;
+       }
+
+       return plane_sdist + normal_dist*normal_dist;
+}
+
+
+/*
+ * BVH from meshs callbacks
+ */
+
+// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces.
+// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+static void mesh_faces_nearest_point(void *userdata, int index, const float *co, BVHTreeNearest *nearest)
+{
+       const BVHTreeFromMesh *data = (BVHTreeFromMesh*) userdata;
+       MVert *vert     = data->vert;
+       MFace *face = data->face + index;
+
+       float *t0, *t1, *t2, *t3;
+       t0 = vert[ face->v1 ].co;
+       t1 = vert[ face->v2 ].co;
+       t2 = vert[ face->v3 ].co;
+       t3 = face->v4 ? vert[ face->v4].co : NULL;
+
+       
+       do
+       {       
+               float nearest_tmp[3], dist;
+               float vec[3][3];
+               
+               // only insert valid triangles / quads with area > 0
+               VECSUB(vec[0], t2, t1);
+               VECSUB(vec[1], t0, t1);
+               Crossf(vec[2], vec[0], vec[1]);
+               if(INPR(vec[2], vec[2]) >= FLT_EPSILON)
+               {
+                       dist = nearest_point_in_tri_surface(co,t0, t1, t2, nearest_tmp);
+                       if(dist < nearest->dist)
+                       {
+                               nearest->index = index;
+                               nearest->dist = dist;
+                               VECCOPY(nearest->co, nearest_tmp);
+                               CalcNormFloat((float*)t0, (float*)t1, (float*)t2, nearest->no); //TODO.. (interpolate normals from the vertexs coordinates?
+                       }
+               }
+
+               t1 = t2;
+               t2 = t3;
+               t3 = NULL;
+
+       } while(t2);
+}
+
+// Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces.
+// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree.
+static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+{
+       const BVHTreeFromMesh *data = (BVHTreeFromMesh*) userdata;
+       MVert *vert     = data->vert;
+       MFace *face = data->face + index;
+
+       float *t0, *t1, *t2, *t3;
+       t0 = vert[ face->v1 ].co;
+       t1 = vert[ face->v2 ].co;
+       t2 = vert[ face->v3 ].co;
+       t3 = face->v4 ? vert[ face->v4].co : NULL;
+
+       
+       do
+       {       
+               float dist;
+               if(data->sphere_radius == 0.0f)
+                       dist = ray_tri_intersection(ray, hit->dist, t0, t1, t2);
+               else
+                       dist = sphereray_tri_intersection(ray, data->sphere_radius, hit->dist, t0, t1, t2);
+
+               if(dist >= 0 && dist < hit->dist)
+               {
+                       hit->index = index;
+                       hit->dist = dist;
+                       VECADDFAC(hit->co, ray->origin, ray->direction, dist);
+
+                       CalcNormFloat(t0, t1, t2, hit->no);
+               }
+
+               t1 = t2;
+               t2 = t3;
+               t3 = NULL;
+
+       } while(t2);
+}
+
+/*
+ * BVH builders
+ */
+// Builds a bvh tree.. where nodes are the vertexs of the given mesh
+void bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
+{
+       int i;
+       int numVerts= mesh->getNumVerts(mesh);
+       MVert *vert     = mesh->getVertDataArray(mesh, CD_MVERT);
+       BVHTree *tree = NULL;
+
+       memset(data, 0, sizeof(*data));
+
+       if(vert == NULL)
+       {
+               printf("bvhtree cant be build: cant get a vertex array");
+               return;
+       }
+
+       tree = BLI_bvhtree_new(numVerts, epsilon, tree_type, axis);
+       if(tree != NULL)
+       {
+               for(i = 0; i < numVerts; i++)
+                       BLI_bvhtree_insert(tree, i, vert[i].co, 1);
+
+               BLI_bvhtree_balance(tree);
+
+               data->tree = tree;
+
+               //a NULL nearest callback works fine
+               //remeber the min distance to point is the same as the min distance to BV of point
+               data->nearest_callback = NULL;
+               data->raycast_callback = NULL;
+
+               data->mesh = mesh;
+               data->vert = mesh->getVertDataArray(mesh, CD_MVERT);
+               data->face = mesh->getFaceDataArray(mesh, CD_MFACE);
+
+               data->sphere_radius = epsilon;
+       }
+}
+
+// Builds a bvh tree.. where nodes are the faces of the given mesh.
+void bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis)
+{
+       int i;
+       int numFaces= mesh->getNumFaces(mesh);
+       MVert *vert     = mesh->getVertDataArray(mesh, CD_MVERT);
+       MFace *face = mesh->getFaceDataArray(mesh, CD_MFACE);
+       BVHTree *tree = NULL;
+
+       memset(data, 0, sizeof(*data));
+
+       if(vert == NULL && face == NULL)
+       {
+               printf("bvhtree cant be build: cant get a vertex/face array");
+               return;
+       }
+
+       /* Create a bvh-tree of the given target */
+       tree = BLI_bvhtree_new(numFaces, epsilon, tree_type, axis);
+       if(tree != NULL)
+       {
+               for(i = 0; i < numFaces; i++)
+               {
+                       float co[4][3];
+                       VECCOPY(co[0], vert[ face[i].v1 ].co);
+                       VECCOPY(co[1], vert[ face[i].v2 ].co);
+                       VECCOPY(co[2], vert[ face[i].v3 ].co);
+                       if(face[i].v4)
+                               VECCOPY(co[3], vert[ face[i].v4 ].co);
+                       
+                       BLI_bvhtree_insert(tree, i, co[0], face[i].v4 ? 4 : 3);
+               }
+               BLI_bvhtree_balance(tree);
+
+               data->tree = tree;
+               data->nearest_callback = mesh_faces_nearest_point;
+               data->raycast_callback = mesh_faces_spherecast;
+
+               data->mesh = mesh;
+               data->vert = mesh->getVertDataArray(mesh, CD_MVERT);
+               data->face = mesh->getFaceDataArray(mesh, CD_MFACE);
+
+               data->sphere_radius = epsilon;
+       }
+}
+
+// Frees data allocated by a call to bvhtree_from_mesh_*.
+void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data)
+{
+       if(data->tree)
+       {
+               BLI_bvhtree_free(data->tree);
+               memset( data, 0, sizeof(data) );
+       }
+}
+
+
index 5b3cec2577258b6282bc514c3fe893be87f47a34..cfcab54058d02885b118712453ab23baec49c7c2 100644 (file)
@@ -1291,116 +1291,6 @@ int cloth_collision_moving ( ClothModifierData *clmd, CollisionModifierData *col
        return 1;
 }
 
-int cloth_do_selfcollisions(ClothModifierData * clmd)
-{      
-       int ret2 = 0, l;
-       Cloth *cloth = clmd->clothObject;
-       
-       if ( clmd->clothObject->bvhselftree )
-       {
-               for(l = 0; l < clmd->coll_parms->self_loop_count; l++)
-               {
-                       BVHTreeOverlap *overlap = NULL;
-                       ClothVertex *verts = clmd->clothObject->verts; // needed for openMP
-                       int k;
-                       int ret = 0, result = 0;
-                       
-                       // search for overlapping collision pairs 
-                       overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
-       
-// #pragma omp parallel for private(k, i, j) schedule(static)
-                       for ( k = 0; k < result; k++ )
-                       {
-                               float temp[3];
-                               float length = 0;
-                               float mindistance;
-                               int i, j;
-       
-                               i = overlap[k].indexA;
-                               j = overlap[k].indexB;
-       
-                               mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
-       
-                               if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
-                               {
-                                       if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
-                                       && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
-                                       {
-                                               continue;
-                                       }
-                               }
-       
-                               VECSUB ( temp, verts[i].tx, verts[j].tx );
-       
-                               if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
-       
-                               // check for adjacent points (i must be smaller j)
-                               if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) )
-                               {
-                                       continue;
-                               }
-       
-                               length = Normalize ( temp );
-       
-                               if ( length < mindistance )
-                               {
-                                       float correction = mindistance - length;
-       
-                                       if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
-                                       {
-                                               VecMulf ( temp, -correction );
-                                               VECADD ( verts[j].tx, verts[j].tx, temp );
-                                       }
-                                       else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED )
-                                       {
-                                               VecMulf ( temp, correction );
-                                               VECADD ( verts[i].tx, verts[i].tx, temp );
-                                       }
-                                       else
-                                       {
-                                               VecMulf ( temp, -correction*0.5 );
-                                               VECADD ( verts[j].tx, verts[j].tx, temp );
-       
-                                               VECSUB ( verts[i].tx, verts[i].tx, temp );
-                                       }
-                                       ret = 1;
-                                       ret2 += ret;
-                               }
-                               else
-                               {
-                                       // check for approximated time collisions
-                               }
-                       }
-       
-                       if ( overlap )
-                               MEM_freeN ( overlap );
-               
-                       if(!ret)
-                               break;
-                       
-               }
-               ////////////////////////////////////////////////////////////
-       
-               ////////////////////////////////////////////////////////////
-               // SELFCOLLISIONS: update velocities
-               ////////////////////////////////////////////////////////////
-               if ( ret2 )
-               {
-                       int i; 
-                       ClothVertex *verts = clmd->clothObject->verts; // needed for openMP
-                       
-                       for ( i = 0; i < cloth->numverts; i++ )
-                       {
-                               if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) )
-                               {
-                                       VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold );
-                               }
-                       }
-               }
-               ////////////////////////////////////////////////////////////
-       }
-       return ret2;
-}
 
 // return all collision objects in scene
 // collision object will exclude self 
@@ -1547,7 +1437,7 @@ int cloth_bvh_objcollision ( Object *ob, ClothModifierData * clmd, float step, f
 {
        Cloth *cloth=NULL;
        BVHTree *cloth_bvh=NULL;
-       int i=0, numfaces = 0, numverts = 0;
+       int i=0, numfaces = 0, numverts = 0, k, l, j;
        int rounds = 0; // result counts applied collisions; ic is for debug output;
        ClothVertex *verts = NULL;
        int ret = 0, ret2 = 0;
@@ -1647,21 +1537,122 @@ int cloth_bvh_objcollision ( Object *ob, ClothModifierData * clmd, float step, f
                        VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
                }
                ////////////////////////////////////////////////////////////
-
+               
                
                ////////////////////////////////////////////////////////////
                // Test on *simple* selfcollisions
                ////////////////////////////////////////////////////////////
                if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF )
                {
-                       ret2 += cloth_do_selfcollisions(clmd);
+                       for(l = 0; l < clmd->coll_parms->self_loop_count; l++)
+                       {
+                               // TODO: add coll quality rounds again
+                               BVHTreeOverlap *overlap = NULL;
+                               int result = 0;
+       
+                               // collisions = 1;
+                               verts = cloth->verts; // needed for openMP
+       
+                               numfaces = clmd->clothObject->numfaces;
+                               numverts = clmd->clothObject->numverts;
+       
+                               verts = cloth->verts;
+       
+                               if ( cloth->bvhselftree )
+                               {
+                                       // search for overlapping collision pairs 
+                                       overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
+       
+       // #pragma omp parallel for private(k, i, j) schedule(static)
+                                       for ( k = 0; k < result; k++ )
+                                       {
+                                               float temp[3];
+                                               float length = 0;
+                                               float mindistance;
+       
+                                               i = overlap[k].indexA;
+                                               j = overlap[k].indexB;
+       
+                                               mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
+       
+                                               if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
+                                               {
+                                                       if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+                                                                               && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
+                                                       {
+                                                               continue;
+                                                       }
+                                               }
+       
+                                               VECSUB ( temp, verts[i].tx, verts[j].tx );
+       
+                                               if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
+       
+                                               // check for adjacent points (i must be smaller j)
+                                               if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) )
+                                               {
+                                                       continue;
+                                               }
+       
+                                               length = Normalize ( temp );
+       
+                                               if ( length < mindistance )
+                                               {
+                                                       float correction = mindistance - length;
+       
+                                                       if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
+                                                       {
+                                                               VecMulf ( temp, -correction );
+                                                               VECADD ( verts[j].tx, verts[j].tx, temp );
+                                                       }
+                                                       else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED )
+                                                       {
+                                                               VecMulf ( temp, correction );
+                                                               VECADD ( verts[i].tx, verts[i].tx, temp );
+                                                       }
+                                                       else
+                                                       {
+                                                               VecMulf ( temp, -correction*0.5 );
+                                                               VECADD ( verts[j].tx, verts[j].tx, temp );
+       
+                                                               VECSUB ( verts[i].tx, verts[i].tx, temp );
+                                                       }
+                                                       ret = 1;
+                                                       ret2 += ret;
+                                               }
+                                               else
+                                               {
+                                                       // check for approximated time collisions
+                                               }
+                                       }
+       
+                                       if ( overlap )
+                                               MEM_freeN ( overlap );
+       
+                               }
+                       }
+                       ////////////////////////////////////////////////////////////
+
+                       ////////////////////////////////////////////////////////////
+                       // SELFCOLLISIONS: update velocities
+                       ////////////////////////////////////////////////////////////
+                       if ( ret2 )
+                       {
+                               for ( i = 0; i < cloth->numverts; i++ )
+                               {
+                                       if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) )
+                                       {
+                                               VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold );
+                                       }
+                               }
+                       }
+                       ////////////////////////////////////////////////////////////
                }
-               ////////////////////////////////////////////////////////////
        }
        while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
        
        if(collobjs)
-               +               MEM_freeN(collobjs);
+               MEM_freeN(collobjs);
 
        return MIN2 ( ret, 1 );
 }
index 9012adb09b7a4c428cd8c375bfd7533304b615f0..2c1f6bb84c146b4bb8c4697cfc7f4102eb3d5204 100644 (file)
@@ -265,14 +265,34 @@ static void layerSwap_tface(void *data, int *corner_indices)
 {
        MTFace *tf = data;
        float uv[4][2];
+       const static short pin_flags[4] =
+           { TF_PIN1, TF_PIN2, TF_PIN3, TF_PIN4 };
+       const static char sel_flags[4] =
+           { TF_SEL1, TF_SEL2, TF_SEL3, TF_SEL4 };
+       short unwrap = tf->unwrap & ~(TF_PIN1 | TF_PIN2 | TF_PIN3 | TF_PIN4);
+       char flag = tf->flag & ~(TF_SEL1 | TF_SEL2 | TF_SEL3 | TF_SEL4);
        int j;
 
        for(j = 0; j < 4; ++j) {
-               uv[j][0] = tf->uv[corner_indices[j]][0];
-               uv[j][1] = tf->uv[corner_indices[j]][1];
+               int source_index = corner_indices[j];
+
+               uv[j][0] = tf->uv[source_index][0];
+               uv[j][1] = tf->uv[source_index][1];
+
+               // swap pinning flags around
+               if(tf->unwrap & pin_flags[source_index]) {
+                       unwrap |= pin_flags[j];
+               }
+
+               // swap selection flags around
+               if(tf->flag & sel_flags[source_index]) {
+                       flag |= sel_flags[j];
+               }
        }
 
        memcpy(tf->uv, uv, sizeof(tf->uv));
+       tf->unwrap = unwrap;
+       tf->flag = flag;
 }
 
 static void layerDefault_tface(void *data, int count)
index f13f8ef0298c7ccc3029e38fb43d42e36cf23895..1dc76296c28783d75d5164f5ca7280fc7fd6c0f6 100644 (file)
@@ -97,6 +97,7 @@
 #include "BKE_material.h"
 #include "BKE_particle.h"
 #include "BKE_pointcache.h"
+#include "BKE_texture.h"
 #include "BKE_utildefines.h"
 #include "depsgraph_private.h"
 #include "BKE_bmesh.h"
@@ -1130,8 +1131,18 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
                                  mface[numFaces].v1 = vert_map[mface[numFaces].v1];
                                  mface[numFaces].v2 = vert_map[mface[numFaces].v2];
                                  mface[numFaces].v3 = vert_map[mface[numFaces].v3];
-                                 if(mface[numFaces].v4)
+                                 if(mface[numFaces].v4) {
                                          mface[numFaces].v4 = vert_map[mface[numFaces].v4];
+
+                                         test_index_face(&mface[numFaces], &result->faceData,
+                                                         numFaces, 4);
+                                 }
+                                 else
+                                 {
+                                         test_index_face(&mface[numFaces], &result->faceData,
+                                                         numFaces, 3);
+                                 }
+
                                  origindex[numFaces] = ORIGINDEX_NONE;
 
                                  numFaces++;
@@ -1221,8 +1232,17 @@ static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
                                  mface[numFaces].v1 = vert_map[mface[numFaces].v1];
                                  mface[numFaces].v2 = vert_map[mface[numFaces].v2];
                                  mface[numFaces].v3 = vert_map[mface[numFaces].v3];
-                                 if(mface[numFaces].v4)
+                                 if(mface[numFaces].v4) {
                                          mface[numFaces].v4 = vert_map[mface[numFaces].v4];
+
+                                         test_index_face(&mface[numFaces], &result->faceData,
+                                                         numFaces, 4);
+                                 }
+                                 else
+                                 {
+                                         test_index_face(&mface[numFaces], &result->faceData,
+                                                         numFaces, 3);
+                                 }
                                  origindex[numFaces] = ORIGINDEX_NONE;
 
                                  numFaces++;
@@ -2980,6 +3000,20 @@ CustomDataMask displaceModifier_requiredDataMask(ModifierData *md)
        return dataMask;
 }
 
+static int displaceModifier_dependsOnTime(ModifierData *md)
+{
+       DisplaceModifierData *dmd = (DisplaceModifierData *)md;
+
+       if(dmd->texture)
+       {
+               return BKE_texture_dependsOnTime(dmd->texture);
+       }
+       else
+       {
+               return 0;
+       }
+}
+
 static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
                                               ObjectWalkFunc walk, void *userData)
 {
@@ -7335,6 +7369,7 @@ ModifierTypeInfo *modifierType_getInfo(ModifierType type)
                mti->initData = displaceModifier_initData;
                mti->copyData = displaceModifier_copyData;
                mti->requiredDataMask = displaceModifier_requiredDataMask;
+               mti->dependsOnTime = displaceModifier_dependsOnTime;
                mti->foreachObjectLink = displaceModifier_foreachObjectLink;
                mti->foreachIDLink = displaceModifier_foreachIDLink;
                mti->updateDepgraph = displaceModifier_updateDepgraph;
index 24a3d348ae7ba6e934763da40feb05619b37bf44..643f90637ad7c034d16ef5772629ecf6c702b491 100644 (file)
@@ -3744,6 +3744,9 @@ int psys_get_particle_state(Object *ob, ParticleSystem *psys, int p, ParticleKey
                        
                        /* TODO: pa_clump vgroup */
                        do_clump(state,key1,t,part->clumpfac,part->clumppow,1.0);
+
+                       if(psys->lattice)
+                               calc_latt_deform(state->co,1.0f);
                }
                else{
                        if (pa) { /* TODO PARTICLE - should this ever be NULL? - Campbell */
index 7dca87d5c135ad53b2de60acda7a7af89b365e44..d1c0cdec71ddba7556b8c3abe640c2cbf876c872 100644 (file)
@@ -4653,7 +4653,7 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
        PTCacheID pid;
        int totpart, oldtotpart, totchild, oldtotchild, p;
        float disp, *vg_vel= 0, *vg_tan= 0, *vg_rot= 0, *vg_size= 0;
-       int init= 0, distr= 0, alloc= 0, usecache= 0;
+       int init= 0, distr= 0, alloc= 0, usecache= 0, only_children_changed= 0;
        int framenr, framedelta, startframe, endframe;
 
        part= psys->part;
@@ -4720,6 +4720,7 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
        totchild = get_psys_tot_child(psys);
 
        if(oldtotpart != totpart || (psys->part->childtype && oldtotchild != totchild)) {
+               only_children_changed = (oldtotpart == totpart);
                realloc_particles(ob, psys, totpart);
                alloc = 1;
                distr= 1;
@@ -4740,14 +4741,17 @@ static void system_step(Object *ob, ParticleSystem *psys, ParticleSystemModifier
 
                        if((psys->part->type == PART_HAIR) && !(psys->flag & PSYS_HAIR_DONE))
                        /* don't generate children while growing hair - waste of time */
-                       psys_free_children(psys);
-               else if(get_psys_tot_child(psys))
-                       distribute_particles(ob, psys, PART_FROM_CHILD);
+                               psys_free_children(psys);
+                       else if(get_psys_tot_child(psys))
+                               distribute_particles(ob, psys, PART_FROM_CHILD);
                }
-               initialize_all_particles(ob, psys, psmd);
 
-               if(alloc)
-                       reset_all_particles(ob, psys, psmd, 0.0, cfra, oldtotpart);
+               if(only_children_changed==0) {
+                       initialize_all_particles(ob, psys, psmd);
+
+                       if(alloc)
+                               reset_all_particles(ob, psys, psmd, 0.0, cfra, oldtotpart);
+               }
 
                /* flag for possible explode modifiers after this system */
                psmd->flag |= eParticleSystemFlag_Pars;
index ad139220785679c33887bf8f297e34c7a4c9f8be..936381c85cc41c0e2ba6851a249974937670f19b 100644 (file)
@@ -545,6 +545,8 @@ Tex *copy_texture(Tex *tex)
        if(texn->type==TEX_IMAGE) id_us_plus((ID *)texn->ima);
        else texn->ima= 0;
        
+       id_us_plus((ID *)texn->ipo);
+       
        if(texn->plugin) {
                texn->plugin= MEM_dupallocN(texn->plugin);
                open_plugin_tex(texn->plugin);
@@ -845,3 +847,19 @@ void BKE_free_envmap(EnvMap *env)
 }
 
 /* ------------------------------------------------------------------------- */
+int BKE_texture_dependsOnTime(const struct Tex *texture)
+{
+       if(texture->plugin) {
+               // assume all plugins depend on time
+               return 1;
+       } else if(      texture->ima && 
+                       ELEM(texture->ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE)) {
+               return 1;
+       } else if(texture->ipo) {
+               // assume any ipo means the texture is animated
+               return 1;
+       }
+       return 0;
+}
+
+/* ------------------------------------------------------------------------- */
index b81ff0ee66f9588e15bd218969553d2524490cac..6d9a17efebffe7bcb2dcd5969638e57ba5f32b4c 100644 (file)
@@ -1,4 +1,6 @@
 /**
+ *
+ * $Id$
  *
  * ***** BEGIN GPL LICENSE BLOCK *****
  *
@@ -40,6 +42,35 @@ typedef struct BVHTreeOverlap {
        int indexB;
 } BVHTreeOverlap;
 
+typedef struct BVHTreeNearest
+{
+       int index;                      /* the index of the nearest found (untouched if none is found within a dist radius from the given coordinates) */
+       float co[3];            /* nearest coordinates (untouched it none is found within a dist radius from the given coordinates) */
+       float no[3];            /* normal at nearest coordinates (untouched it none is found within a dist radius from the given coordinates) */
+       float dist;                     /* squared distance to search arround */
+} BVHTreeNearest;
+
+typedef struct BVHTreeRay
+{
+       float origin[3];        /* ray origin */
+       float direction[3];     /* ray direction */
+} BVHTreeRay;
+
+typedef struct BVHTreeRayHit
+{
+       int index;                      /* index of the tree node (untouched if no hit is found) */
+       float co[3];            /* coordinates of the hit point */
+       float no[3];            /* normal on hit point */
+       float dist;                     /* distance to the hit point */
+} BVHTreeRayHit;
+
+/* callback must update nearest in case it finds a nearest result */
+typedef void (*BVHTree_NearestPointCallback) (void *userdata, int index, const float *co, BVHTreeNearest *nearest);
+
+/* callback must update hit in case it finds a nearest successful hit */
+typedef void (*BVHTree_RayCastCallback) (void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit);
+
+
 BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis);
 void BLI_bvhtree_free(BVHTree *tree);
 
@@ -56,5 +87,10 @@ BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
 
 float BLI_bvhtree_getepsilon(BVHTree *tree);
 
+/* find nearest node to the given coordinates (if nearest is given it will only search nodes where square distance is smaller than nearest->dist) */
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata);
+
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata);
+
 #endif // BLI_KDOPBVH_H
 
index a97b9ca6672bace8f7887ff6d3bfb3a9950615a4..9671551a7f10212041fd0cfb9bb59d8a82274e6f 100644 (file)
@@ -28,8 +28,9 @@
 
 #include "math.h"
 #include <stdio.h>
-#include <stdlib.h> 
+#include <stdlib.h>
 #include <string.h>
+#include <assert.h>
 
 #include "MEM_guardedalloc.h"
 
 #include <omp.h>
 #endif
 
+
+
+#define MAX_TREETYPE 32
+
 typedef struct BVHNode
 {
-       struct BVHNode **children; // max 8 children
-       struct BVHNode *parent; // needed for bottom - top update
-       float *bv; // Bounding volume of all nodes, max 13 axis
-       int index; /* face, edge, vertex index */
-       char totnode; // how many nodes are used, used for speedup
-       char traversed;  // how many nodes already traversed until this level?
-       char main_axis;
+       struct BVHNode **children;
+       float *bv;              // Bounding volume of all nodes, max 13 axis
+       int index;              // face, edge, vertex index
+       char totnode;   // how many nodes are used, used for speedup
+       char main_axis; // Axis used to split this node
 } BVHNode;
 
 struct BVHTree
@@ -72,8 +75,34 @@ typedef struct BVHOverlapData
        BVHTree *tree1, *tree2; 
        BVHTreeOverlap *overlap; 
        int i, max_overlap; /* i is number of overlaps */
+       int start_axis, stop_axis;
 } BVHOverlapData;
-////////////////////////////////////////
+
+typedef struct BVHNearestData
+{
+       BVHTree *tree;
+       float   *co;
+       BVHTree_NearestPointCallback callback;
+       void    *userdata;
+       float proj[13];                 //coordinates projection over axis
+       BVHTreeNearest nearest;
+
+} BVHNearestData;
+
+typedef struct BVHRayCastData
+{
+       BVHTree *tree;
+
+       BVHTree_RayCastCallback callback;
+       void    *userdata;
+
+
+       BVHTreeRay    ray;
+       float ray_dot_axis[13];
+
+       BVHTreeRayHit hit;
+} BVHRayCastData;
+////////////////////////////////////////m
 
 
 ////////////////////////////////////////////////////////////////////////
@@ -244,7 +273,7 @@ int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis){
        int begin = _begin, end = _end, cut;
        while(end-begin > 3)
        {
-               cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin+end)/2, end-1, axis), axis ); 
+               cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin+end)/2, end-1, axis), axis );
                if(cut <= n)
                        begin = cut;
                else
@@ -255,124 +284,15 @@ int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis){
        return n;
 }
 
-
 //////////////////////////////////////////////////////////////////////////////////////////////////////
 
-void BLI_bvhtree_free(BVHTree *tree)
-{      
-       if(tree)
-       {
-               MEM_freeN(tree->nodes);
-               MEM_freeN(tree->nodearray);
-               MEM_freeN(tree->nodebv);
-               MEM_freeN(tree->nodechild);
-               MEM_freeN(tree);
-       }
-}
-
-BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
-{
-       BVHTree *tree;
-       int numbranches=0, i;
-       
-       // only support up to octree
-       if(tree_type > 8)
-               return NULL;
-
-       tree = (BVHTree *)MEM_callocN(sizeof(BVHTree), "BVHTree");
-       
-       if(tree)
-       {
-               tree->epsilon = epsilon;
-               tree->tree_type = tree_type; 
-               tree->axis = axis;
-               
-               if(axis == 26)
-               {
-                       tree->start_axis = 0;
-                       tree->stop_axis = 13;
-               }
-               else if(axis == 18)
-               {
-                       tree->start_axis = 7;
-                       tree->stop_axis = 13;
-               }
-               else if(axis == 14)
-               {
-                       tree->start_axis = 0;
-                       tree->stop_axis = 7;
-               }
-               else if(axis == 8) // AABB
-               {
-                       tree->start_axis = 0;
-                       tree->stop_axis = 4;
-               }
-               else if(axis == 6) // OBB
-               {
-                       tree->start_axis = 0;
-                       tree->stop_axis = 3;
-               }
-               else
-               {
-                       MEM_freeN(tree);
-                       return NULL;
-               }
-
-
-               // calculate max number of branches, our bvh kdop is "almost perfect"
-               for(i = 1; i <= (int)ceil((float)((float)log(maxsize)/(float)log(tree_type))); i++)
-                       numbranches += (pow(tree_type, i) / tree_type);
-               
-               tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *)*(numbranches+maxsize + tree_type), "BVHNodes");
-               
-               if(!tree->nodes)
-               {
-                       MEM_freeN(tree);
-                       return NULL;
-               }
-               
-               tree->nodebv = (float*)MEM_callocN(sizeof(float)* axis * (numbranches+maxsize + tree_type), "BVHNodeBV");
-               if(!tree->nodebv)
-               {
-                       MEM_freeN(tree->nodes);
-                       MEM_freeN(tree);
-               }
-
-               tree->nodechild = (BVHNode**)MEM_callocN(sizeof(BVHNode*) * tree_type * (numbranches+maxsize + tree_type), "BVHNodeBV");
-               if(!tree->nodechild)
-               {
-                       MEM_freeN(tree->nodebv);
-                       MEM_freeN(tree->nodes);
-                       MEM_freeN(tree);
-               }
-
-               tree->nodearray = (BVHNode *)MEM_callocN(sizeof(BVHNode)*(numbranches+maxsize + tree_type), "BVHNodeArray");
-               
-               if(!tree->nodearray)
-               {
-                       MEM_freeN(tree->nodechild);
-                       MEM_freeN(tree->nodebv);
-                       MEM_freeN(tree->nodes);
-                       MEM_freeN(tree);
-                       return NULL;
-               }
-
-               //link the dynamic bv and child links
-               for(i=0; i< numbranches+maxsize + tree_type; i++)
-               {
-                       tree->nodearray[i].bv = tree->nodebv + i * axis;
-                       tree->nodearray[i].children = tree->nodechild + i * tree_type;
-               }
-               
-       }
-
-       return tree;
-}
-
-
+/*
+ * BVHTree bounding volumes functions
+ */
 static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoints, int moving)
 {
        float newminmax;
+       float *bv = node->bv;
        int i, k;
        
        // don't init boudings for the moving case
@@ -380,8 +300,8 @@ static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoi
        {
                for (i = tree->start_axis; i < tree->stop_axis; i++)
                {
-                       node->bv[2*i] = FLT_MAX;
-                       node->bv[2*i + 1] = -FLT_MAX;
+                       bv[2*i] = FLT_MAX;
+                       bv[2*i + 1] = -FLT_MAX;
                }
        }
        
@@ -391,10 +311,10 @@ static void create_kdop_hull(BVHTree *tree, BVHNode *node, float *co, int numpoi
                for (i = tree->start_axis; i < tree->stop_axis; i++)
                {
                        newminmax = INPR(&co[k * 3], KDOP_AXES[i]);
-                       if (newminmax < node->bv[2 * i])
-                               node->bv[2 * i] = newminmax;
-                       if (newminmax > node->bv[(2 * i) + 1])
-                               node->bv[(2 * i) + 1] = newminmax;
+                       if (newminmax < bv[2 * i])
+                               bv[2 * i] = newminmax;
+                       if (newminmax > bv[(2 * i) + 1])
+                               bv[(2 * i) + 1] = newminmax;
                }
        }
 }
@@ -405,6 +325,7 @@ static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
        float newmin,newmax;
        int i, j;
        float *bv = node->bv;
+
        
        for (i = tree->start_axis; i < tree->stop_axis; i++)
        {
@@ -426,37 +347,7 @@ static void refit_kdop_hull(BVHTree *tree, BVHNode *node, int start, int end)
                                bv[(2 * i) + 1] = newmax;
                }
        }
-}
-
-int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints)
-{
-       BVHNode *node= NULL;
-       int i;
-       
-       // insert should only possible as long as tree->totbranch is 0
-       if(tree->totbranch > 0)
-               return 0;
-       
-       if(tree->totleaf+1 >= MEM_allocN_len(tree->nodes))
-               return 0;
-       
-       // TODO check if have enough nodes in array
-       
-       node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
-       tree->totleaf++;
-       
-       create_kdop_hull(tree, node, co, numpoints, 0);
-       
-       // inflate the bv with some epsilon
-       for (i = tree->start_axis; i < tree->stop_axis; i++)
-       {
-               node->bv[(2 * i)] -= tree->epsilon; // minimum 
-               node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
-       }
 
-       node->index= index;
-       
-       return 1;
 }
 
 // only supports x,y,z axis in the moment
@@ -484,46 +375,76 @@ static char get_largest_axis(float *bv)
        }
 }
 
-static void bvh_div_nodes(BVHTree *tree, BVHNode *node, int start, int end, char lastaxis)
+// bottom-up update of bvh node BV
+// join the children on the parent BV
+static void node_join(BVHTree *tree, BVHNode *node)
 {
-       char laxis;
-       int i, tend;
-       BVHNode *tnode;
-       int slice = (end-start+tree->tree_type-1)/tree->tree_type;      //division rounded up
+       int i, j;
        
-       // Determine which axis to split along
-       laxis = get_largest_axis(node->bv);
+       for (i = tree->start_axis; i < tree->stop_axis; i++)
+       {
+               node->bv[2*i] = FLT_MAX;
+               node->bv[2*i + 1] = -FLT_MAX;
+       }
        
-       // split nodes along longest axis
-       for (i=0; start < end; start += slice, i++) //i counts the current child
-       {       
-               tend = start + slice;
-               
-               if(tend > end) tend = end;
-               
-               if(tend-start == 1)     // ok, we have 1 left for this node
+       for (i = 0; i < tree->tree_type; i++)
+       {
+               if (node->children[i]) 
                {
-                       node->children[i] = tree->nodes[start];
-                       node->children[i]->parent = node;
+                       for (j = tree->start_axis; j < tree->stop_axis; j++)
+                       {
+                               // update minimum 
+                               if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)]) 
+                                       node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
+                               
+                               // update maximum 
+                               if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
+                                       node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
+                       }
                }
                else
-               {
-                       tnode = node->children[i] = tree->nodes[tree->totleaf  + tree->totbranch] = &(tree->nodearray[tree->totbranch + tree->totleaf]);
-                       tree->totbranch++;
-                       tnode->parent = node;
-                       
-                       if(tend != end)
-                               partition_nth_element(tree->nodes, start, end, tend, laxis);
-                       refit_kdop_hull(tree, tnode, start, tend);
-                       bvh_div_nodes(tree, tnode, start, tend, laxis);
-               }
-               node->totnode++;
+                       break;
        }
-       
-       return;
+}
+
+/*
+ * Debug and information functions
+ */
+static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
+{
+       int i;
+       for(i=0; i<depth; i++) printf(" ");
+       printf(" - %d (%d): ", node->index, node - tree->nodearray);
+       for(i=2*tree->start_axis; i<2*tree->stop_axis; i++)
+               printf("%.3f ", node->bv[i]);
+       printf("\n");
+
+       for(i=0; i<tree->tree_type; i++)
+               if(node->children[i])
+                       bvhtree_print_tree(tree, node->children[i], depth+1);
+}
+
+static void bvhtree_info(BVHTree *tree)
+{
+       printf("BVHTree info\n");
+       printf("tree_type = %d, axis = %d, epsilon = %f\n", tree->tree_type, tree->axis, tree->epsilon);
+       printf("nodes = %d, branches = %d, leafs = %d\n", tree->totbranch + tree->totleaf,  tree->totbranch, tree->totleaf);
+       printf("Memory per node = %dbytes\n", sizeof(BVHNode) + sizeof(BVHNode*)*tree->tree_type + sizeof(float)*tree->axis);
+       printf("BV memory = %dbytes\n", MEM_allocN_len(tree->nodebv));
+
+       printf("Total memory = %dbytes\n", sizeof(BVHTree)
+               + MEM_allocN_len(tree->nodes)
+               + MEM_allocN_len(tree->nodearray)
+               + MEM_allocN_len(tree->nodechild)
+               + MEM_allocN_len(tree->nodebv)
+               );
+
+//     bvhtree_print_tree(tree, tree->nodes[tree->totleaf], 0);
 }
 
 #if 0
+
+
 static void verify_tree(BVHTree *tree)
 {
        int i, j, check = 0;
@@ -571,81 +492,497 @@ static void verify_tree(BVHTree *tree)
        printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
 }
 #endif
-       
-void BLI_bvhtree_balance(BVHTree *tree)
+
+//Helper data and structures to build a min-leaf generalized implicit tree
+//This code can be easily reduced (basicly this is only method to calculate pow(k, n) in O(1).. and stuff like that)
+typedef struct BVHBuildHelper
 {
-       BVHNode *node;
-       
-       if(tree->totleaf == 0)
-               return;
-       
-       // create root node
-       node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
-       tree->totbranch++;
-       
-       // refit root bvh node
-       refit_kdop_hull(tree, tree->nodes[tree->totleaf], 0, tree->totleaf);
-       // create + balance tree
-       bvh_div_nodes(tree, tree->nodes[tree->totleaf], 0, tree->totleaf, 0);
-       
-       // verify_tree(tree);
-}
+       int tree_type;                          //
+       int totleafs;                           //
 
-// overlap - is it possbile for 2 bv's to collide ?
-static int tree_overlap(float *bv1, float *bv2, int start_axis, int stop_axis)
+       int leafs_per_child  [32];      //Min number of leafs that are archievable from a node at depth N
+       int branches_on_level[32];      //Number of nodes at depth N (tree_type^N)
+
+       int remain_leafs;                       //Number of leafs that are placed on the level that is not 100% filled
+
+} BVHBuildHelper;
+
+static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
 {
-       float *bv1_end = bv1 + (stop_axis<<1);
-               
-       bv1 += start_axis<<1;
-       bv2 += start_axis<<1;
-       
-       // test all axis if min + max overlap
-       for (; bv1 != bv1_end; bv1+=2, bv2+=2)
+       int depth = 0;
+       int remain;
+       int nnodes;
+
+       data->totleafs = tree->totleaf;
+       data->tree_type= tree->tree_type;
+
+       //Calculate the smallest tree_type^n such that tree_type^n >= num_leafs
+       for(
+               data->leafs_per_child[0] = 1;
+               data->leafs_per_child[0] <  data->totleafs;
+               data->leafs_per_child[0] *= data->tree_type
+       );
+
+       data->branches_on_level[0] = 1;
+
+       //We could stop the loop first (but I am lazy to find out when)
+       for(depth = 1; depth < 32; depth++)
        {
-               if ((*(bv1) > *(bv2 + 1)) || (*(bv2) > *(bv1 + 1))) 
-                       return 0;
+               data->branches_on_level[depth] = data->branches_on_level[depth-1] * data->tree_type;
+               data->leafs_per_child  [depth] = data->leafs_per_child  [depth-1] / data->tree_type;
        }
-       
-       return 1;
+
+       remain = data->totleafs - data->leafs_per_child[1];
+       nnodes = (remain + data->tree_type - 2) / (data->tree_type - 1);
+       data->remain_leafs = remain + nnodes;
 }
 
-static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
+// return the min index of all the leafs archivable with the given branch
+static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index)
 {
-       int j;
-       
-       if(tree_overlap(node1->bv, node2->bv, MIN2(data->tree1->start_axis, data->tree2->start_axis), MIN2(data->tree1->stop_axis, data->tree2->stop_axis)))
-       {
-               // check if node1 is a leaf
-               if(!node1->totnode)
-               {
-                       // check if node2 is a leaf
-                       if(!node2->totnode)
-                       {
-                               
-                               if(node1 == node2)
-                               {
-                                       return;
-                               }
-                                       
-                               if(data->i >= data->max_overlap)
-                               {       
-                                       // try to make alloc'ed memory bigger
-                                       data->overlap = realloc(data->overlap, sizeof(BVHTreeOverlap)*data->max_overlap*2);
-                                       
-                                       if(!data->overlap)
-                                       {
-                                               printf("Out of Memory in traverse\n");
-                                               return;
-                                       }
-                                       data->max_overlap *= 2;
-                               }
-                               
-                               // both leafs, insert overlap!
-                               data->overlap[data->i].indexA = node1->index;
-                               data->overlap[data->i].indexB = node2->index;
+       int min_leaf_index = child_index * data->leafs_per_child[depth-1];
+       if(min_leaf_index <= data->remain_leafs)
+               return min_leaf_index;
+       else if(data->leafs_per_child[depth])
+               return data->totleafs - (data->branches_on_level[depth-1] - child_index) * data->leafs_per_child[depth];
+       else
+               return data->remain_leafs;
+}
 
-                               data->i++;
-                       }
+/**
+ * Generalized implicit tree build
+ *
+ * An implicit tree is a tree where its structure is implied, thus there is no need to store child pointers or indexs.
+ * Its possible to find the position of the child or the parent with simple maths (multiplication and adittion). This type
+ * of tree is for example used on heaps.. where node N has its childs at indexs N*2 and N*2+1.
+ *
+ * Altought in this case the tree type is general.. and not know until runtime.
+ * tree_type stands for the maximum number of childs that a tree node can have.
+ * All tree types >= 2 are supported.
+ *
+ * Advantages of the used trees include:
+ *  - No need to store child/parent relations (they are implicit);
+ *  - Any node child always has an index greater than the parent;
+ *  - Brother nodes are sequencial in memory;
+ *
+ *
+ * Some math relations derived for general implicit trees:
+ *
+ *   K = tree_type, ( 2 <= K )
+ *   ROOT = 1
+ *   N child of node A = A * K + (2 - K) + N, (0 <= N < K)
+ *
+ * Util methods:
+ *   TODO...
+ *    (looping elements, knowing if its a leaf or not.. etc...)
+ */
+
+// This functions returns the number of branches needed to have the requested number of leafs.
+static int implicit_needed_branches(int tree_type, int leafs)
+{
+       return MAX2(1, (leafs + tree_type - 3) / (tree_type-1) );
+}
+
+/*
+ * This function handles the problem of "sorting" the leafs (along the split_axis).
+ *
+ * It arranges the elements in the given partitions such that:
+ *  - any element in partition N is less or equal to any element in partition N+1.
+ *  - if all elements are diferent all partition will get the same subset of elements
+ *    as if the array was sorted.
+ *
+ * partition P is described as the elements in the range ( nth[P] , nth[P+1] ]
+ *
+ * TODO: This can be optimized a bit by doing a specialized nth_element instead of K nth_elements
+ */
+static void split_leafs(BVHNode **leafs_array, int *nth, int partitions, int split_axis)
+{
+       int i;
+       for(i=0; i < partitions-1; i++)
+       {
+               if(nth[i] >= nth[partitions])
+                       break;
+
+               partition_nth_element(leafs_array, nth[i], nth[partitions], nth[i+1], split_axis);
+       }
+}
+
+/*
+ * This functions builds an optimal implicit tree from the given leafs.
+ * Where optimal stands for:
+ *  - The resulting tree will have the smallest number of branches;
+ *  - At most only one branch will have NULL childs;
+ *  - All leafs will be stored at level N or N+1.
+ *
+ * This function creates an implicit tree on branches_array, the leafs are given on the leafs_array.
+ *
+ * The tree is built per depth levels. First branchs at depth 1.. then branches at depth 2.. etc..
+ * The reason is that we can build level N+1 from level N witouth any data dependencies.. thus it allows
+ * to use multithread building.
+ *
+ * To archieve this is necessary to find how much leafs are accessible from a certain branch, BVHBuildHelper
+ * implicit_needed_branches and implicit_leafs_index are auxiliar functions to solve that "optimal-split".
+ */
+static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
+{
+       int i;
+
+       const int tree_type   = tree->tree_type;
+       const int tree_offset = 2 - tree->tree_type; //this value is 0 (on binary trees) and negative on the others
+       const int num_branches= implicit_needed_branches(tree_type, num_leafs);
+
+       BVHBuildHelper data;
+       int depth;
+
+       branches_array--;       //Implicit trees use 1-based indexs
+       
+       build_implicit_tree_helper(tree, &data);
+
+       //Loop tree levels (log N) loops
+       for(i=1, depth = 1; i <= num_branches; i = i*tree_type + tree_offset, depth++)
+       {
+               const int first_of_next_level = i*tree_type + tree_offset;
+               const int  end_j = MIN2(first_of_next_level, num_branches + 1); //index of last branch on this level
+               int j;
+
+               //Loop all branches on this level
+#pragma omp parallel for private(j) schedule(static)
+               for(j = i; j < end_j; j++)
+               {
+                       int k;
+                       const int parent_level_index= j-i;
+                       BVHNode* parent = branches_array + j;
+                       int nth_positions[ MAX_TREETYPE + 1];
+                       char split_axis;
+
+                       int parent_leafs_begin = implicit_leafs_index(&data, depth, parent_level_index);
+                       int parent_leafs_end   = implicit_leafs_index(&data, depth, parent_level_index+1);
+
+                       //This calculates the bounding box of this branch
+                       //and chooses the largest axis as the axis to divide leafs
+                       refit_kdop_hull(tree, parent, parent_leafs_begin, parent_leafs_end);
+                       split_axis = get_largest_axis(parent->bv);
+
+                       //Save split axis (this can be used on raytracing to speedup the query time)
+                       parent->main_axis = split_axis / 2;
+
+                       //Split the childs along the split_axis, note: its not needed to sort the whole leafs array
+                       //Only to assure that the elements are partioned on a way that each child takes the elements
+                       //it would take in case the whole array was sorted.
+                       //Split_leafs takes care of that "sort" problem.
+                       nth_positions[        0] = parent_leafs_begin;
+                       nth_positions[tree_type] = parent_leafs_end;
+                       for(k = 1; k < tree_type; k++)
+                       {
+                               int child_index = j * tree_type + tree_offset + k;
+                               int child_level_index = child_index - first_of_next_level; //child level index
+                               nth_positions[k] = implicit_leafs_index(&data, depth+1, child_level_index);
+                       }
+
+                       split_leafs(leafs_array, nth_positions, tree_type, split_axis);
+
+
+                       //Setup children and totnode counters
+                       //Not really needed but currently most of BVH code relies on having an explicit children structure
+                       for(k = 0; k < tree_type; k++)
+                       {
+                               int child_index = j * tree_type + tree_offset + k;
+                               int child_level_index = child_index - first_of_next_level; //child level index
+
+                               int child_leafs_begin = implicit_leafs_index(&data, depth+1, child_level_index);
+                               int child_leafs_end   = implicit_leafs_index(&data, depth+1, child_level_index+1);
+
+                               if(child_leafs_end - child_leafs_begin > 1)
+                                       parent->children[k] = branches_array + child_index;
+                               else if(child_leafs_end - child_leafs_begin == 1)
+                                       parent->children[k] = leafs_array[ child_leafs_begin ];
+                               else
+                                       break;
+
+                               parent->totnode = k+1;
+                       }
+               }
+       }
+}
+
+
+/*
+ * BLI_bvhtree api
+ */
+BVHTree *BLI_bvhtree_new(int maxsize, float epsilon, char tree_type, char axis)
+{
+       BVHTree *tree;
+       int numnodes, i;
+       
+       // theres not support for trees below binary-trees :P
+       if(tree_type < 2)
+               return NULL;
+       
+       if(tree_type > MAX_TREETYPE)
+               return NULL;
+
+       tree = (BVHTree *)MEM_callocN(sizeof(BVHTree), "BVHTree");
+       
+       if(tree)
+       {
+               tree->epsilon = epsilon;
+               tree->tree_type = tree_type; 
+               tree->axis = axis;
+               
+               if(axis == 26)
+               {
+                       tree->start_axis = 0;
+                       tree->stop_axis = 13;
+               }
+               else if(axis == 18)
+               {
+                       tree->start_axis = 7;
+                       tree->stop_axis = 13;
+               }
+               else if(axis == 14)
+               {
+                       tree->start_axis = 0;
+                       tree->stop_axis = 7;
+               }
+               else if(axis == 8) // AABB
+               {
+                       tree->start_axis = 0;
+                       tree->stop_axis = 4;
+               }
+               else if(axis == 6) // OBB
+               {
+                       tree->start_axis = 0;
+                       tree->stop_axis = 3;
+               }
+               else
+               {
+                       MEM_freeN(tree);
+                       return NULL;
+               }
+
+
+               //Allocate arrays
+               numnodes = maxsize + implicit_needed_branches(tree_type, maxsize) + tree_type;
+
+               tree->nodes = (BVHNode **)MEM_callocN(sizeof(BVHNode *)*numnodes, "BVHNodes");
+               
+               if(!tree->nodes)
+               {
+                       MEM_freeN(tree);
+                       return NULL;
+               }
+               
+               tree->nodebv = (float*)MEM_callocN(sizeof(float)* axis * numnodes, "BVHNodeBV");
+               if(!tree->nodebv)
+               {
+                       MEM_freeN(tree->nodes);
+                       MEM_freeN(tree);
+               }
+
+               tree->nodechild = (BVHNode**)MEM_callocN(sizeof(BVHNode*) * tree_type * numnodes, "BVHNodeBV");
+               if(!tree->nodechild)
+               {
+                       MEM_freeN(tree->nodebv);
+                       MEM_freeN(tree->nodes);
+                       MEM_freeN(tree);
+               }
+
+               tree->nodearray = (BVHNode *)MEM_callocN(sizeof(BVHNode)* numnodes, "BVHNodeArray");
+               
+               if(!tree->nodearray)
+               {
+                       MEM_freeN(tree->nodechild);
+                       MEM_freeN(tree->nodebv);
+                       MEM_freeN(tree->nodes);
+                       MEM_freeN(tree);
+                       return NULL;
+               }
+
+               //link the dynamic bv and child links
+               for(i=0; i< numnodes; i++)
+               {
+                       tree->nodearray[i].bv = tree->nodebv + i * axis;
+                       tree->nodearray[i].children = tree->nodechild + i * tree_type;
+               }
+               
+       }
+
+       return tree;
+}
+
+void BLI_bvhtree_free(BVHTree *tree)
+{      
+       if(tree)
+       {
+               MEM_freeN(tree->nodes);
+               MEM_freeN(tree->nodearray);
+               MEM_freeN(tree->nodebv);
+               MEM_freeN(tree->nodechild);
+               MEM_freeN(tree);
+       }
+}
+
+void BLI_bvhtree_balance(BVHTree *tree)
+{
+       int i;
+
+       BVHNode*  branches_array = tree->nodearray + tree->totleaf;
+       BVHNode** leafs_array    = tree->nodes;
+
+       //This function should only be called once (some big bug goes here if its being called more than once per tree)
+       assert(tree->totbranch == 0);
+
+       //Build the implicit tree
+       non_recursive_bvh_div_nodes(tree, branches_array, leafs_array, tree->totleaf);
+
+       //current code expects the branches to be linked to the nodes array
+       //we perform that linkage here
+       tree->totbranch = implicit_needed_branches(tree->tree_type, tree->totleaf);
+       for(i = 0; i < tree->totbranch; i++)
+               tree->nodes[tree->totleaf + i] = branches_array + i;
+
+       //bvhtree_info(tree);
+}
+
+int BLI_bvhtree_insert(BVHTree *tree, int index, float *co, int numpoints)
+{
+       int i;
+       BVHNode *node = NULL;
+       
+       // insert should only possible as long as tree->totbranch is 0
+       if(tree->totbranch > 0)
+               return 0;
+       
+       if(tree->totleaf+1 >= MEM_allocN_len(tree->nodes)/sizeof(*(tree->nodes)))
+               return 0;
+       
+       // TODO check if have enough nodes in array
+       
+       node = tree->nodes[tree->totleaf] = &(tree->nodearray[tree->totleaf]);
+       tree->totleaf++;
+       
+       create_kdop_hull(tree, node, co, numpoints, 0);
+       node->index= index;
+       
+       // inflate the bv with some epsilon
+       for (i = tree->start_axis; i < tree->stop_axis; i++)
+       {
+               node->bv[(2 * i)] -= tree->epsilon; // minimum 
+               node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
+       }
+
+       return 1;
+}
+
+
+// call before BLI_bvhtree_update_tree()
+int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints)
+{
+       int i;
+       BVHNode *node= NULL;
+       
+       // check if index exists
+       if(index > tree->totleaf)
+               return 0;
+       
+       node = tree->nodearray + index;
+       
+       create_kdop_hull(tree, node, co, numpoints, 0);
+       
+       if(co_moving)
+               create_kdop_hull(tree, node, co_moving, numpoints, 1);
+       
+       // inflate the bv with some epsilon
+       for (i = tree->start_axis; i < tree->stop_axis; i++)
+       {
+               node->bv[(2 * i)] -= tree->epsilon; // minimum 
+               node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
+       }
+
+       return 1;
+}
+
+// call BLI_bvhtree_update_node() first for every node/point/triangle
+void BLI_bvhtree_update_tree(BVHTree *tree)
+{
+       //Update bottom=>top
+       //TRICKY: the way we build the tree all the childs have an index greater than the parent
+       //This allows us todo a bottom up update by starting on the biger numbered branch
+
+       BVHNode** root  = tree->nodes + tree->totleaf;
+       BVHNode** index = tree->nodes + tree->totleaf + tree->totbranch-1;
+
+       for (; index >= root; index--)
+               node_join(tree, *index);
+}
+
+float BLI_bvhtree_getepsilon(BVHTree *tree)
+{
+       return tree->epsilon;
+}
+
+
+/*
+ * BLI_bvhtree_overlap
+ */
+// overlap - is it possbile for 2 bv's to collide ?
+static int tree_overlap(BVHNode *node1, BVHNode *node2, int start_axis, int stop_axis)
+{
+       float *bv1 = node1->bv;
+       float *bv2 = node2->bv;
+
+       float *bv1_end = bv1 + (stop_axis<<1);
+               
+       bv1 += start_axis<<1;
+       bv2 += start_axis<<1;
+       
+       // test all axis if min + max overlap
+       for (; bv1 != bv1_end; bv1+=2, bv2+=2)
+       {
+               if ((*(bv1) > *(bv2 + 1)) || (*(bv2) > *(bv1 + 1))) 
+                       return 0;
+       }
+       
+       return 1;
+}
+
+static void traverse(BVHOverlapData *data, BVHNode *node1, BVHNode *node2)
+{
+       int j;
+       
+       if(tree_overlap(node1, node2, data->start_axis, data->stop_axis))
+       {
+               // check if node1 is a leaf
+               if(!node1->totnode)
+               {
+                       // check if node2 is a leaf
+                       if(!node2->totnode)
+                       {
+                               
+                               if(node1 == node2)
+                               {
+                                       return;
+                               }
+                                       
+                               if(data->i >= data->max_overlap)
+                               {       
+                                       // try to make alloc'ed memory bigger
+                                       data->overlap = realloc(data->overlap, sizeof(BVHTreeOverlap)*data->max_overlap*2);
+                                       
+                                       if(!data->overlap)
+                                       {
+                                               printf("Out of Memory in traverse\n");
+                                               return;
+                                       }
+                                       data->max_overlap *= 2;
+                               }
+                               
+                               // both leafs, insert overlap!
+                               data->overlap[data->i].indexA = node1->index;
+                               data->overlap[data->i].indexB = node2->index;
+
+                               data->i++;
+                       }
                        else
                        {
                                for(j = 0; j < data->tree2->tree_type; j++)
@@ -679,7 +1016,7 @@ BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
                return 0;
        
        // fast check root nodes for collision before doing big splitting + traversal
-       if(!tree_overlap(tree1->nodes[tree1->totleaf]->bv, tree2->nodes[tree2->totleaf]->bv, MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
+       if(!tree_overlap(tree1->nodes[tree1->totleaf], tree2->nodes[tree2->totleaf], MIN2(tree1->start_axis, tree2->start_axis), MIN2(tree1->stop_axis, tree2->stop_axis)))
                return 0;
 
        data = MEM_callocN(sizeof(BVHOverlapData *)* tree1->tree_type, "BVHOverlapData_star");
@@ -694,6 +1031,8 @@ BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
                data[j]->tree2 = tree2;
                data[j]->max_overlap = MAX2(tree1->totleaf, tree2->totleaf);
                data[j]->i = 0;
+               data[j]->start_axis = MIN2(tree1->start_axis, tree2->start_axis);
+               data[j]->stop_axis  = MIN2(tree1->stop_axis,  tree2->stop_axis );
        }
 
 #pragma omp parallel for private(j) schedule(static)
@@ -725,88 +1064,251 @@ BVHTreeOverlap *BLI_bvhtree_overlap(BVHTree *tree1, BVHTree *tree2, int *result)
 }
 
 
-// bottom up update of bvh tree:
-// join the 4 children here
-static void node_join(BVHTree *tree, BVHNode *node)
+/*
+ * Nearest neighbour - BLI_bvhtree_find_nearest
+ */
+static float squared_dist(const float *a, const float *b)
 {
-       int i, j;
-       
-       for (i = tree->start_axis; i < tree->stop_axis; i++)
+       float tmp[3];
+       VECSUB(tmp, a, b);
+       return INPR(tmp, tmp);
+}
+
+//Determines the nearest point of the given node BV. Returns the squared distance to that point.
+static float calc_nearest_point(BVHNearestData *data, BVHNode *node, float *nearest)
+{
+       int i;
+       const float *bv = node->bv;
+
+       //nearest on AABB hull
+       for(i=0; i != 3; i++, bv += 2)
        {
-               node->bv[2*i] = FLT_MAX;
-               node->bv[2*i + 1] = -FLT_MAX;
+               if(bv[0] > data->proj[i])
+                       nearest[i] = bv[0];
+               else if(bv[1] < data->proj[i])
+                       nearest[i] = bv[1];
+               else
+                       nearest[i] = data->proj[i];
        }
-       
-       for (i = 0; i < tree->tree_type; i++)
+
+/*
+       //nearest on a general hull
+       VECCOPY(nearest, data->co);
+       for(i = data->tree->start_axis; i != data->tree->stop_axis; i++, bv+=2)
        {
-               if (node->children[i]) 
+               float proj = INPR( nearest, KDOP_AXES[i]);
+               float dl = bv[0] - proj;
+               float du = bv[1] - proj;
+
+               if(dl > 0)
                {
-                       for (j = tree->start_axis; j < tree->stop_axis; j++)
-                       {
-                               // update minimum 
-                               if (node->children[i]->bv[(2 * j)] < node->bv[(2 * j)]) 
-                                       node->bv[(2 * j)] = node->children[i]->bv[(2 * j)];
-                               
-                               // update maximum 
-                               if (node->children[i]->bv[(2 * j) + 1] > node->bv[(2 * j) + 1])
-                                       node->bv[(2 * j) + 1] = node->children[i]->bv[(2 * j) + 1];
-                       }
+                       VECADDFAC(nearest, nearest, KDOP_AXES[i], dl);
                }
+               else if(du < 0)
+               {
+                       VECADDFAC(nearest, nearest, KDOP_AXES[i], du);
+               }
+       }
+*/
+       return squared_dist(data->co, nearest);
+}
+
+
+// TODO: use a priority queue to reduce the number of nodes looked on
+static void dfs_find_nearest(BVHNearestData *data, BVHNode *node)
+{
+       int i;
+       float nearest[3], sdist;
+
+       sdist = calc_nearest_point(data, node, nearest);
+       if(sdist >= data->nearest.dist) return;
+
+       if(node->totnode == 0)
+       {
+               if(data->callback)
+                       data->callback(data->userdata , node->index, data->co, &data->nearest);
                else
-                       break;
+               {
+                       data->nearest.index     = node->index;
+                       VECCOPY(data->nearest.co, nearest);
+                       data->nearest.dist      = sdist;
+               }
+       }
+       else
+       {
+               for(i=0; i != node->totnode; i++)
+                       dfs_find_nearest(data, node->children[i]);
        }
 }
 
-// call before BLI_bvhtree_update_tree()
-int BLI_bvhtree_update_node(BVHTree *tree, int index, float *co, float *co_moving, int numpoints)
+int BLI_bvhtree_find_nearest(BVHTree *tree, const float *co, BVHTreeNearest *nearest, BVHTree_NearestPointCallback callback, void *userdata)
 {
-       BVHNode *node= NULL;
-       int i = 0;
-       
-       // check if index exists
-       if(index > tree->totleaf)
-               return 0;
-       
-       node = tree->nodearray + index;
-       
-       create_kdop_hull(tree, node, co, numpoints, 0);
-       
-       if(co_moving)
-               create_kdop_hull(tree, node, co_moving, numpoints, 1);
-       
-       // inflate the bv with some epsilon
-       for (i = tree->start_axis; i < tree->stop_axis; i++)
+       int i;
+
+       BVHNearestData data;
+       BVHNode* root = tree->nodes[tree->totleaf];
+
+       //init data to search
+       data.tree = tree;
+       data.co = co;
+
+       data.callback = callback;
+       data.userdata = userdata;
+
+       for(i = data.tree->start_axis; i != data.tree->stop_axis; i++)
        {
-               node->bv[(2 * i)] -= tree->epsilon; // minimum 
-               node->bv[(2 * i) + 1] += tree->epsilon; // maximum 
+               data.proj[i] = INPR(data.co, KDOP_AXES[i]);
        }
-       
-       return 1;
+
+       if(nearest)
+       {
+               memcpy( &data.nearest , nearest, sizeof(*nearest) );
+       }
+       else
+       {
+               data.nearest.index = -1;
+               data.nearest.dist = FLT_MAX;
+       }
+
+       //dfs search
+       if(root)
+               dfs_find_nearest(&data, root);
+
+       //copy back results
+       if(nearest)
+       {
+               memcpy(nearest, &data.nearest, sizeof(*nearest));
+       }
+
+       return data.nearest.index;
 }
 
-// call BLI_bvhtree_update_node() first for every node/point/triangle
-void BLI_bvhtree_update_tree(BVHTree *tree)
+
+/*
+ * Raycast - BLI_bvhtree_ray_cast
+ *
+ * raycast is done by performing a DFS on the BVHTree and saving the closest hit
+ */
+
+//Determines the distance that the ray must travel to hit the bounding volume of the given node
+static float ray_nearest_hit(BVHRayCastData *data, BVHNode *node)
 {
-       BVHNode *leaf, *parent;
-       
-       // reset tree traversing flag
-       for (leaf = tree->nodearray + tree->totleaf; leaf != tree->nodearray + tree->totleaf + tree->totbranch; leaf++)
-               leaf->traversed = 0;
+       int i;
+       const float *bv = node->bv;
+
+       float low = 0, upper = data->hit.dist;
+
+       for(i=0; i != 3; i++, bv += 2)
+       {
+               if(data->ray_dot_axis[i] == 0.0f)
+               {
+                       //axis aligned ray
+                       if(data->ray.origin[i] < bv[0]
+                       || data->ray.origin[i] > bv[1])
+                               return FLT_MAX;
+               }
+               else
+               {
+                       float ll = (bv[0] - data->ray.origin[i]) / data->ray_dot_axis[i];
+                       float lu = (bv[1] - data->ray.origin[i]) / data->ray_dot_axis[i];
+
+                       if(data->ray_dot_axis[i] > 0)
+                       {
+                               if(ll > low)   low = ll;
+                               if(lu < upper) upper = lu;
+                       }
+                       else
+                       {
+                               if(lu > low)   low = lu;
+                               if(ll < upper) upper = ll;
+                       }
        
-       for (leaf = tree->nodearray; leaf != tree->nodearray + tree->totleaf; leaf++)
+                       if(low > upper) return FLT_MAX;
+               }
+       }
+       return low;
+}
+
+static void dfs_raycast(BVHRayCastData *data, BVHNode *node)
+{
+       int i;
+
+       //ray-bv is really fast.. and simple tests revealed its worth to test it
+       //before calling the ray-primitive functions
+       float dist = ray_nearest_hit(data, node);
+       if(dist >= data->hit.dist) return;
+
+       if(node->totnode == 0)
+       {
+               if(data->callback)
+                       data->callback(data->userdata, node->index, &data->ray, &data->hit);
+               else
+               {
+                       data->hit.index = node->index;
+                       data->hit.dist  = dist;
+                       VECADDFAC(data->hit.co, data->ray.origin, data->ray.direction, dist);
+               }
+       }
+       else
        {
-               for (parent = leaf->parent; parent; parent = parent->parent)
+               //pick loop direction to dive into the tree (based on ray direction and split axis)
+               if(data->ray_dot_axis[ node->main_axis ] > 0)
                {
-                       parent->traversed++;    // we tried to go up in hierarchy 
-                       if (parent->traversed < parent->totnode) 
-                               break;  // we do not need to check further 
-                       else 
-                               node_join(tree, parent);
+                       for(i=0; i != node->totnode; i++)
+                       {
+                               dfs_raycast(data, node->children[i]);
+                       }
+               }
+               else
+               {
+                       for(i=node->totnode-1; i >= 0; i--)
+                       {
+                               dfs_raycast(data, node->children[i]);
+                       }
                }
        }
 }
 
-float BLI_bvhtree_getepsilon(BVHTree *tree)
+int BLI_bvhtree_ray_cast(BVHTree *tree, const float *co, const float *dir, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
 {
-       return tree->epsilon;
+       int i;
+       BVHRayCastData data;
+       BVHNode * root = tree->nodes[tree->totleaf];
+
+       data.tree = tree;
+
+       data.callback = callback;
+       data.userdata = userdata;
+
+       VECCOPY(data.ray.origin,    co);
+       VECCOPY(data.ray.direction, dir);
+
+       Normalize(data.ray.direction);
+
+       for(i=0; i<3; i++)
+       {
+               data.ray_dot_axis[i] = INPR( data.ray.direction, KDOP_AXES[i]);
+
+               if(fabs(data.ray_dot_axis[i]) < 1e-7)
+                       data.ray_dot_axis[i] = 0.0;
+       }
+
+
+       if(hit)
+               memcpy( &data.hit, hit, sizeof(*hit) );
+       else
+       {
+               data.hit.index = -1;
+               data.hit.dist = FLT_MAX;
+       }
+
+       if(root)
+               dfs_raycast(&data, root);
+
+
+       if(hit)
+               memcpy( hit, &data.hit, sizeof(*hit) );
+
+       return data.hit.index;
 }
+
index acd53e5d516c11a0e6fe746b1892715f3aec7639..db7bae8a91d77d2f93fb871ca13d6f00be99c877 100644 (file)
@@ -42,6 +42,8 @@
 #define TRF 2
 #define TLF 4
 #define BRF 8
+#define CORNERFLAGS (BLF|TRF|TLF|BRF)
+
 #define BL 0
 #define TR 1
 #define TL 2
@@ -159,7 +161,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
                vert->blb = vert->brb = vert->tlb =\
                        vert->isect_cache[0] = vert->isect_cache[1] =\
                        vert->isect_cache[2] = vert->isect_cache[3] = NULL;
-               vert->free = 15 &~ TRF;
+               vert->free = CORNERFLAGS &~ TRF;
                vert->trb = box;
                vert->index = i; i++;
                box->v[BL] = vert; vert++;
@@ -167,7 +169,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
                vert->trb= vert->brb = vert->tlb =\
                        vert->isect_cache[0] = vert->isect_cache[1] =\
                        vert->isect_cache[2] = vert->isect_cache[3] = NULL;
-               vert->free = 15 &~ BLF;
+               vert->free = CORNERFLAGS &~ BLF;
                vert->blb = box;
                vert->index = i; i++;
                box->v[TR] = vert; vert++;
@@ -175,7 +177,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
                vert->trb = vert->blb = vert->tlb =\
                        vert->isect_cache[0] = vert->isect_cache[1] =\
                        vert->isect_cache[2] = vert->isect_cache[3] = NULL;
-               vert->free = 15 &~ BRF;
+               vert->free = CORNERFLAGS &~ BRF;
                vert->brb = box;
                vert->index = i; i++;
                box->v[TL] = vert; vert++;
@@ -183,7 +185,7 @@ void boxPack2D(boxPack *boxarray, int len, float *tot_width, float *tot_height)
                vert->trb = vert->blb = vert->brb =\
                        vert->isect_cache[0] = vert->isect_cache[1] =\
                        vert->isect_cache[2] = vert->isect_cache[3] = NULL;
-               vert->free = 15 &~ TLF;
+               vert->free = CORNERFLAGS &~ TLF;
                vert->tlb = box; 
                vert->index = i; i++;
                box->v[BR] = vert; vert++;
index 720f5b0f7c8d0bc967424642274a1af88d33c5fd..c0e84b73e47bb64c5bef4e24c5a047420dde12da 100644 (file)
@@ -612,6 +612,7 @@ static int startffmpeg(struct anim * anim) {
                av_free(anim->pFrameRGB);
                av_free(anim->pFrameDeinterlaced);
                av_free(anim->pFrame);
+               anim->pCodecCtx = NULL;
                return -1;
        }
 
@@ -639,7 +640,19 @@ static int startffmpeg(struct anim * anim) {
                PIX_FMT_BGR32,
                SWS_FAST_BILINEAR | SWS_PRINT_INFO,
                NULL, NULL, NULL);
-                               
+               
+       if (!anim->img_convert_ctx) {
+               fprintf (stderr,
+                        "Can't transform color space??? Bailing out...\n");
+               avcodec_close(anim->pCodecCtx);
+               av_close_input_file(anim->pFormatCtx);
+               av_free(anim->pFrameRGB);
+               av_free(anim->pFrameDeinterlaced);
+               av_free(anim->pFrame);
+               anim->pCodecCtx = NULL;
+               return -1;
+       }
+               
        return (0);
 }
 
index da98eb3d4f1a8beb122345ccf11669cdaf6aad36..13c16749612c6a881cf594b3fc18828f0460007f 100644 (file)
@@ -108,7 +108,8 @@ void        mouse_armature(void);
 void   remake_editArmature(void);
 void   selectconnected_armature(void);
 void   selectconnected_posearmature(void);
-void   select_bone_parent(void);
+void   armature_select_hierarchy(short direction, short add_to_sel);
+
 void   setflag_armature(short mode);
 void    unique_editbone_name (struct ListBase *ebones, char *name);
 
@@ -143,6 +144,10 @@ void       set_locks_armature_bones(short lock);
 
 #define BONESEL_NOSEL  0x80000000      /* Indicates a negative number */
 
+/* used in bone_select_hierachy() */
+#define BONE_SELECT_PARENT     0
+#define BONE_SELECT_CHILD      1
+
 #endif
 
 
index ca9f3d6a378f4cd9a7e6baf8812f1c3f263ff19a..9354a577ac160fea47c87498c192da23ff97afd8 100644 (file)
@@ -132,7 +132,7 @@ extern int EM_check_backbuf(unsigned int index);
 extern void EM_free_backbuf(void);
 
 extern void EM_selectmode_menu(void);
-
+extern void EM_mesh_copy_face(short type);
 
 extern void vertexnoise(void);
 extern void vertexsmooth(void);
index 58c67ff102a15ffb19361a496923d38341aaa5e9..ab96f7ec03e44981e9fa280aea0489cbb703c4da 100644 (file)
@@ -65,6 +65,8 @@ void pose_assign_to_posegroup(short active);
 void pose_remove_from_posegroups(void);
 void pgroup_operation_with_menu(void);
 
+void pose_select_hierarchy(short direction, short add_to_sel);
+
 void pose_select_grouped(short nr);
 void pose_select_grouped_menu(void);
 
index c0542e3f34c17ca11a4bffaa1b89eabdf3258dd6..8e80f630cf25f2d8f9098fc9c6f2de68c196bed0 100644 (file)
@@ -593,7 +593,7 @@ void curvemap_buttons(struct uiBlock *block, struct CurveMapping *cumap, char la
 
 #define B_VPCOLSLI             2801
 #define B_VPGAMMA              2802
-
+#define B_COPY_TF_TRANSP       2803
 #define B_COPY_TF_MODE         2804
 #define B_COPY_TF_UV           2805
 #define B_COPY_TF_COL          2806
index 36a8ee27a5003595318fbd6f9c8ece54253d82b9..48633d37fa2abdcda490fad0d1131a446d222b1a 100644 (file)
@@ -160,11 +160,10 @@ ScriptError g_script_error;
 * Function prototypes 
 ***************************************************************************/
 PyObject *RunPython( Text * text, PyObject * globaldict );
-char *GetName( Text * text );
 PyObject *CreateGlobalDictionary( void );
 void ReleaseGlobalDictionary( PyObject * dict );
 void DoAllScriptsFromList( ListBase * list, short event );
-PyObject *importText( char *name );
+static PyObject *importText( char *name );
 void init_ourImport( void );
 void init_ourReload( void );
 PyObject *blender_import( PyObject * self, PyObject * args );
@@ -651,7 +650,7 @@ int BPY_txt_do_python_Text( struct Text *text )
        }
 
        /* Create a new script structure and initialize it: */
-       script = alloc_libblock( &G.main->script, ID_SCRIPT, GetName( text ) );
+       script = alloc_libblock( &G.main->script, ID_SCRIPT, text->id.name+2 );
 
        if( !script ) {
                printf( "couldn't allocate memory for Script struct!" );
@@ -662,8 +661,7 @@ int BPY_txt_do_python_Text( struct Text *text )
         * an error after it will call BPY_Err_Handle below, but the text struct
         * will have been deallocated already, so we need to copy its name here.
         */
-       BLI_strncpy( textname, GetName( text ),
-                    strlen( GetName( text ) ) + 1 );
+       BLI_strncpy( textname, text->id.name+2, 21 );
 
        script->id.us = 1;
        script->flags = SCRIPT_RUNNING;
@@ -1135,12 +1133,10 @@ int BPY_menu_invoke( BPyMenu *pym, short menutype )
 *****************************************************************************/
 void BPY_free_compiled_text( struct Text *text )
 {
-       if( !text->compiled )
-               return;
-       Py_DECREF( ( PyObject * ) text->compiled );
-       text->compiled = NULL;
-
-       return;
+       if( text->compiled ) {
+               Py_DECREF( ( PyObject * ) text->compiled );
+               text->compiled = NULL;
+       }
 }
 
 /*****************************************************************************
@@ -2753,8 +2749,7 @@ PyObject *RunPython( Text * text, PyObject * globaldict )
                buf = txt_to_buf( text );
 
                text->compiled =
-                       Py_CompileString( buf, GetName( text ),
-                                         Py_file_input );
+                       Py_CompileString( buf, text->id.name+2, Py_file_input );
 
                MEM_freeN( buf );
 
@@ -2768,15 +2763,6 @@ PyObject *RunPython( Text * text, PyObject * globaldict )
        return PyEval_EvalCode( text->compiled, globaldict, globaldict );
 }
 
-/*****************************************************************************
-* Description: This function returns the value of the name field of the        
-*      given Text struct.
-*****************************************************************************/
-char *GetName( Text * text )
-{
-       return ( text->id.name + 2 );
-}
-
 /*****************************************************************************
 * Description: This function creates a new Python dictionary object.
 *****************************************************************************/
@@ -2821,49 +2807,38 @@ void DoAllScriptsFromList( ListBase * list, short event )
        return;
 }
 
-PyObject *importText( char *name )
+static PyObject *importText( char *name )
 {
        Text *text;
-       char *txtname;
+       char txtname[22]; /* 21+NULL */
        char *buf = NULL;
        int namelen = strlen( name );
-
-       txtname = malloc( namelen + 3 + 1 );
-       if( !txtname )
-               return NULL;
-
+       
+       if (namelen>21-3) return NULL; /* we know this cant be importable, the name is too long for blender! */
+       
        memcpy( txtname, name, namelen );
        memcpy( &txtname[namelen], ".py", 4 );
 
-       text = ( Text * ) & ( G.main->text.first );
-
-       while( text ) {
-               if( !strcmp( txtname, GetName( text ) ) )
+       for(text = G.main->text.first; text; text = text->id.next) {
+               if( !strcmp( txtname, text->id.name+2 ) )
                        break;
-               text = text->id.next;
        }
 
-       if( !text ) {
-               free( txtname );
+       if( !text )
                return NULL;
-       }
 
        if( !text->compiled ) {
                buf = txt_to_buf( text );
-               text->compiled =
-                       Py_CompileString( buf, GetName( text ),
-                                         Py_file_input );
+               text->compiled = Py_CompileString( buf, text->id.name+2, Py_file_input );
                MEM_freeN( buf );
 
                if( PyErr_Occurred(  ) ) {
                        PyErr_Print(  );
                        BPY_free_compiled_text( text );
-                       free( txtname );
                        return NULL;
                }
        }
 
-       free( txtname );
        return PyImport_ExecCodeModule( name, text->compiled );
 }
 
@@ -2934,7 +2909,7 @@ static PyObject *reimportText( PyObject *module )
        /* look up the text object */
        text = ( Text * ) & ( G.main->text.first );
        while( text ) {
-               if( !strcmp( txtname, GetName( text ) ) )
+               if( !strcmp( txtname, text->id.name+2 ) )
                        break;
                text = text->id.next;
        }
@@ -2951,8 +2926,7 @@ static PyObject *reimportText( PyObject *module )
 
        /* compile the buffer */
        buf = txt_to_buf( text );
-       text->compiled = Py_CompileString( buf, GetName( text ),
-                       Py_file_input );
+       text->compiled = Py_CompileString( buf, text->id.name+2, Py_file_input );
        MEM_freeN( buf );
 
        /* if compile failed.... return this error */
index 420d292cdcef7073eec1c18f12e0ad6ba2eda759..2b190a6c828cf1534e3ebe092a7f063e8ff1c95f 100644 (file)
@@ -1074,7 +1074,7 @@ void M_Blender_Init(void)
        PyDict_SetItemString(dict, "Material", Material_Init());
        PyDict_SetItemString(dict, "Mesh", Mesh_Init()); 
        PyDict_SetItemString(dict, "Metaball", Metaball_Init());
-       PyDict_SetItemString(dict, "Mathutils", Mathutils_Init());
+       PyDict_SetItemString(dict, "Mathutils", Mathutils_Init("Blender.Mathutils"));
        PyDict_SetItemString(dict, "Geometry", Geometry_Init());
        PyDict_SetItemString(dict, "Modifier", Modifier_Init());
        PyDict_SetItemString(dict, "NMesh", NMesh_Init());
index 8db6a49465e3d2cb0ab832f4613fa8e65d31ddc4..a62a5ee7ed8b23566c0a17d770b61afa0d6afa4c 100644 (file)
@@ -29,6 +29,7 @@
 
 #include "Constraint.h" /*This must come first*/
 
+#include "DNA_armature_types.h"
 #include "DNA_object_types.h"
 #include "DNA_effect_types.h"
 #include "DNA_vec_types.h"
@@ -43,6 +44,7 @@
 #include "BKE_constraint.h"
 #include "BLI_blenlib.h"
 #include "BIF_editconstraint.h"
+#include "BIF_poseobject.h"
 #include "BSE_editipo.h"
 #include "MEM_guardedalloc.h"
 #include "butspace.h"
@@ -2286,19 +2288,32 @@ static PyObject *ConstraintSeq_moveDown( BPy_ConstraintSeq *self, BPy_Constraint
 
 static PyObject *ConstraintSeq_remove( BPy_ConstraintSeq *self, BPy_Constraint *value )
 {
-       bConstraint *con = locate_constr( self,  value );
+       bConstraint *con = locate_constr(self, value);
+       bPoseChannel *active= NULL;
 
        /* if we can't locate the constraint, return (exception already set) */
-       if( !con )
+       if (!con)
                return (PyObject *)NULL;
 
-       /* do the actual removal */
-       if( self->pchan )
-               BLI_remlink( &self->pchan->constraints, con );
-       else
-               BLI_remlink( &self->obj->constraints, con);
+       /* check if we need to set temporary 'active' flag for pchan */
+       if (self->pchan) {
+               active= get_active_posechannel(self->obj);
+               
+               if (active != self->pchan) {
+                       if (active) active->bone->flag &= ~BONE_ACTIVE;
+                       self->pchan->bone->flag |= BONE_ACTIVE;
+               }
+       }
+       
+       /* del_constr_func() frees constraint + its data */
        del_constr_func( self->obj, con );
 
+       /* reset active pchan (if applicable) */
+       if (self->pchan && self->pchan!=active) {
+               if (active) active->bone->flag |= BONE_ACTIVE;
+               self->pchan->bone->flag &= ~BONE_ACTIVE;
+       }
+       
        /* erase the link to the constraint */
        value->con = NULL;
 
index c36213950b0f3628c9a7957a211b2d9386567f89..ccd24a437b5e8edd801b5774ce8150a73673e2e9 100644 (file)
 #define EXPP_MAT_RAYMIRRGLOSS_MIN                       0.0
 #define EXPP_MAT_RAYMIRRGLOSS_MAX                       1.0
 #define EXPP_MAT_RAYMIRRGLOSSSAMPLES_MIN        0
-#define EXPP_MAT_RAYMIRRGLOSSSAMPLES_MAX        255
+#define EXPP_MAT_RAYMIRRGLOSSSAMPLES_MAX        1024
 #define EXPP_MAT_RAYTRANSPGLOSS_MIN                     0.0
 #define EXPP_MAT_RAYTRANSPGLOSS_MAX                     1.0
 #define EXPP_MAT_RAYTRANSPGLOSSSAMPLES_MIN      0
-#define EXPP_MAT_RAYTRANSPGLOSSSAMPLES_MAX      255
+#define EXPP_MAT_RAYTRANSPGLOSSSAMPLES_MAX      1024
 #define EXPP_MAT_FILTER_MIN                    0.0
 #define EXPP_MAT_FILTER_MAX                    1.0
 #define EXPP_MAT_TRANSLUCENCY_MIN                      0.0
@@ -738,8 +738,10 @@ static PyMethodDef BPy_Material_methods[] = {
         "() - Return fresnel power for refractions factor"},
        {"getRayTransGloss", ( PyCFunction ) Material_getGlossTrans, METH_NOARGS,
         "() - Return amount refraction glossiness"},
+       {"getRayTransGlossSamples", ( PyCFunction ) Material_getGlossTransSamples, METH_NOARGS,
+        "() - Return number of sampels for transparent glossiness"},
        {"getRayMirrGlossSamples", ( PyCFunction ) Material_getGlossMirrSamples, METH_NOARGS,
-        "() - Return amount mirror glossiness"},
+        "() - Return number of sampels for mirror glossiness"},
        {"getFilter", ( PyCFunction ) Material_getFilter, METH_NOARGS,
         "() - Return the amount of filtering when transparent raytrace is enabled"},
        {"getTranslucency", ( PyCFunction ) Material_getTranslucency, METH_NOARGS,
@@ -847,8 +849,10 @@ static PyMethodDef BPy_Material_methods[] = {
         "(f) - Set blend fac for mirror fresnel - [1.0, 5.0]"},
        {"setRayTransGloss", ( PyCFunction ) Material_setGlossTrans, METH_VARARGS,
         "(f) - Set amount refraction glossiness - [0.0, 1.0]"},
+       {"setRayTransGlossSamples", ( PyCFunction ) Material_setGlossTransSamples, METH_VARARGS,
+        "(i) - Set number transparent gloss samples - [1, 1024]"},
        {"setRayMirrGlossSamples", ( PyCFunction ) Material_setGlossMirrSamples, METH_VARARGS,
-        "(f) - Set amount mirror glossiness - [0.0, 1.0]"},
+        "(i) - Set number mirror gloss samples - [1, 1024]"},
        {"setFilter", ( PyCFunction ) Matr_oldsetFilter, METH_VARARGS,
         "(f) - Set the amount of filtering when transparent raytrace is enabled"},
        {"setTranslucency", ( PyCFunction ) Matr_oldsetTranslucency, METH_VARARGS,
index 85c56a616288dd9a3574270577643ed0b75ec590..217e096060f9d372fbad81a726e588d083ad2c8f 100644 (file)
@@ -106,8 +106,9 @@ struct PyMethodDef M_Mathutils_methods[] = {
        {"Point", (PyCFunction) M_Mathutils_Point, METH_VARARGS, M_Mathutils_Point_doc},
        {NULL, NULL, 0, NULL}
 };
-//----------------------------MODULE INIT-------------------------
-PyObject *Mathutils_Init(void)
+/*----------------------------MODULE INIT-------------------------*/
+/* from can be Blender.Mathutils or GameLogic.Mathutils for the BGE */
+PyObject *Mathutils_Init(char *from)
 {
        PyObject *submodule;
 
@@ -125,8 +126,7 @@ PyObject *Mathutils_Init(void)
        if( PyType_Ready( &quaternion_Type ) < 0 )
                return NULL;
        
-       submodule = Py_InitModule3("Blender.Mathutils",
-                                   M_Mathutils_methods, M_Mathutils_doc);
+       submodule = Py_InitModule3(from, M_Mathutils_methods, M_Mathutils_doc);
        return (submodule);
 }
 //-----------------------------METHODS----------------------------
index dd9aae2abed4a7fa2b2ff1e81e5ae43252ca1df1..76d53cb6c4cdf8b93de1852a5373eced088a77a0 100644 (file)
@@ -38,7 +38,7 @@
 #include "euler.h"
 #include "point.h"
 
-PyObject *Mathutils_Init( void );
+PyObject *Mathutils_Init( char * from );
 PyObject *row_vector_multiplication(VectorObject* vec, MatrixObject * mat);
 PyObject *column_vector_multiplication(MatrixObject * mat, VectorObject* vec);
 PyObject *row_point_multiplication(PointObject* pt, MatrixObject * mat);
index d4dc83e84a039491b9c8e9c24e8b07b4eaf83893..df688893aa387f922d57645174ed58844a90ed6c 100644 (file)
@@ -772,7 +772,7 @@ class RenderData:
     """
     Get/set the starting frame for sequence rendering.
     @type frame: int (optional)
-    @param frame: must be between 1 - 18000
+    @param frame: must be a valid Blender frame number.
     @rtype: int (if prototype is empty)
     @return: Current starting frame for the scene.
     """
@@ -781,7 +781,7 @@ class RenderData:
     """
     Get/set the ending frame for sequence rendering.
     @type frame: int (optional)
-    @param frame: must be between 1 - 18000
+    @param frame: must be a valid Blender frame number.
     @rtype: int (if prototype is empty)
     @return: Current ending frame for the scene.
     """
index faa7a68f75421390db0f51d6bfdcd8bf35c82e34..e4a5ad676315993082f2fc8c879a5fdc0ac9bd4f 100644 (file)
@@ -1865,9 +1865,17 @@ static int render_new_particle_system(Render *re, ObjectRen *obr, ParticleSystem
                        num= cpa->num;
 
                        /* get orco */
-                       psys_particle_on_emitter(ob, psmd,
-                               (part->childtype == PART_CHILD_FACES)? PART_FROM_FACE: PART_FROM_PARTICLE,
-                               cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,nor,0,0,orco,0);
+                       if(part->childtype == PART_CHILD_FACES) {
+                               psys_particle_on_emitter(ob, psmd,
+                                       PART_FROM_FACE, cpa->num,DMCACHE_ISCHILD,
+                                       cpa->fuv,cpa->foffset,co,nor,0,0,orco,0);
+                       }
+                       else {
+                               ParticleData *par = psys->particles + cpa->parent;
+                               psys_particle_on_emitter(ob, psmd, part->from,
+                                       par->num,DMCACHE_ISCHILD,par->fuv,
+                                       par->foffset,co,nor,0,0,orco,0);
+                       }
 
                        if(uvco){
                                if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
index b26c52a92e2dcbec6f68479ff8fa6455fcba1044..cb6f7e629fa42e9fd9c9bfa9982d151d8d09397c 100644 (file)
@@ -5671,13 +5671,9 @@ void sculptmode_draw_interface_textures(uiBlock *block, unsigned short cx, unsig
 
 void do