Python + MXS


#281

It certainly was! Thanks for the update.


#282

Hi, i’m new in max scripting and want integrating python function in 3ds max. Firstly i toad that i need to totally re-wright full *.py script into maxscript language, but after i see this thread i really think about integrating. And for clean up for my self all of the previous posts i want ask for help. Please show to me how to run functions of python script into 3d max.

this is python script

import bpy,struct,os
import Blender
from Blender import *
from struct import *
from Blender.Mathutils import *
from Blender import Armature as A
from Blender.Window import DrawProgressBar
import math



#=========== open file ======================
extends=['bma','bms']
dir = os.getcwd()
g = os.listdir(dir)
bool={}
draw={}  
block=[] 
texpath="D:\\3D\\==SOURCES==\\king bounty\	extures"
for plik in g:
  extend = plik[plik.lower().find('.')+1:]
  if extend in extends: 
      bool[plik] = False
      draw[plik] = Draw.Create(bool[plik])
      block.append((plik,draw[plik]))
Draw.PupBlock("bma files",block) 
for file in bool:
        bool[file] = draw[file].val
        if bool[file]==True: 
            filename = dir+os.sep+file
            object = file
        else:
            Draw.Exit()         
plik = open(filename,'rb')
vertexy=[]
uvcoord=[]
faceslist=[]
normalne=[]

print '============================================================='
print filename
print '============================================================='  

def word(long): 
   s=''
   for j in range(0,long):  
       s+=struct.unpack('c',plik.read(1))[0]
   return s


print struct.unpack(16*'B',plik.read(16))
print struct.unpack('i',plik.read(4))

print
print "===skeleton==="
print
numbones = struct.unpack('i',plik.read(4))[0]
print 'numbones = ',numbones

a=10
b=1
 

scn = Scene.GetCurrent() 
newarmature = A.Armature('arm')
newarmobj = Object.New('Armature','armature')
newarm = A.Get('arm')
newarm.drawType = Armature.STICK 
newarmobj.link(newarm)
scn.link(newarmobj)

bonenames=[]
for i in range(numbones):
        id = struct.unpack('i',plik.read(4))[0]
        namebone = word(id)
        #print namebone
        namebone =str(i)
        bonenames.append(namebone)
        eb = A.Editbone() 
        struct.unpack('b',plik.read(1))    
        parent = struct.unpack('i',plik.read(4))[0]
        p1 = struct.unpack(3*'f',plik.read(12)) #szkielet nr 1
        p2 = struct.unpack(3*'f',plik.read(12)) #szkielet nr 2
        p3 = struct.unpack(3*'f',plik.read(12)) #szkielet nr 3
        if 'box' not in namebone and 'tipp' not in namebone:
            newarm.makeEditable()
            newarm.bones[namebone] = eb
            newarm.bones[namebone].head=Vector(p1[0]*a*b,p1[2]*a*b,p1[1]*a*b)
            newarm.bones[namebone].tail=Vector(p1[0]*a*b+0.01,p1[2]*a*b,p1[1]*a*b)
            if i!=0:
               newarm.bones[namebone].parent=newarm.bones[bonenames[parent]]
               newarm.update()
        struct.unpack(3*'f',plik.read(12))
        struct.unpack(3*'f',plik.read(12))
        struct.unpack(3*'f',plik.read(12))
        struct.unpack(3*'f',plik.read(12))
        struct.unpack(3*'f',plik.read(12))
        struct.unpack(3*'f',plik.read(12))

print
print "===material==="
print
struct.unpack(4*'h',plik.read(8))#to samo

keywords = ['k_specularenvspecmask','k_specularenvspecmask_uvanim',\
           'texDiffuse','k_specularenv',\
           'texSpecular',\
           'texEnv',\
           'cLuminosity','tgLumiMap',\
           'cDiffuse','k_diffuselumi','texLumiMap',\
           'cSpecular',\
           'cEnv',\
           'fShadowTransp',\
           'tgDiffuse',\
           'tgSpecular',\
           'k_diffuse','diffuse','k_specular']



id = struct.unpack('i',plik.read(4))[0]
key = word(id)
materials=[]
print key
numtex=0
while key in keywords:
    if key == 'k_specular':
          #plik.read(62)
          print struct.unpack(62*'b',plik.read(62))
    if key == 'k_specularenvspecmask':
          plik.read(62)
    if key == 'k_specularenvspecmask_uvanim':
          plik.read(62)
    if key == 'k_diffuse':
          plik.read(62)
    if key == 'k_diffuselumi':
          plik.read(62)
    if key == 'k_specularenv':
          plik.read(62)
    if key == 'diffuse':
          plik.read(2)
          info = struct.unpack(15*'i',plik.read(60))
          print info
          if info[11]==0:
             print struct.unpack(4*'b',plik.read(4))
    if key == 'texDiffuse':
          newmat = Material.New(object[:-4]+'-M-'+str(numtex))
          plik.read(5)
          id = struct.unpack('i',plik.read(4))[0]
          texdiff = word(id)
          print 'texdiff = ',texdiff
          imagepath = texpath+os.sep+texdiff  
          tex = Texture.New('tex'+str(numtex))
          try:
               img = Blender.Image.Load(imagepath)
               tex.image = img
          except:
               print 'no found',imagepath 
          plik.read(1)
          numtex=numtex+1 
          newmat.setTexture(0,tex,Texture.TexCo.UV,Texture.MapTo.COL)
          materials.append(newmat)
    if key == 'texSpecular':
          plik.read(5)
          id = struct.unpack('i',plik.read(4))[0]
          texspec = word(id)
          print 'texspec = ',texspec
          plik.read(1)
    if key == 'texLumiMap':
          plik.read(5)
          id = struct.unpack('i',plik.read(4))[0]
          texspec = word(id)
          print 'texspec = ',texspec
          plik.read(1)
    if key == 'texEnv':
          plik.read(5)
          id = struct.unpack('i',plik.read(4))[0]
          texenv = word(id)
          print 'texenv = ',texenv
          plik.read(1)
    if key == 'cLuminosity':
          plik.read(21)
    if key == 'cDiffuse':
          plik.read(21)
    if key == 'cSpecular':
          plik.read(21)
    if key == 'cEnv':
          plik.read(21)
    if key == 'fShadowTransp':
         plik.read(9)
    if key == 'tgDiffuse':
          plik.read(1)
          #print struct.unpack(84*'b',plik.read(84))
          info = struct.unpack(24*'b',plik.read(24))
          print info
          if info[8]!=0:
            print struct.unpack(60*'b',plik.read(60))
    if key == 'tgSpecular':
          plik.read(85)
    if key == 'tgLumiMap':
          plik.read(85)
    back = plik.tell()
    id = struct.unpack('i',plik.read(4))[0]
    #print id
    if id > 70:
        plik.seek(back)
        break
    key = word(id)
    print key
           

print
print'====mesh===='
print
numfacespermesh=[]
weightsgroup={}
struct.unpack(2*'H',plik.read(2*2))# TO SAMO W KAZDYM PLIKU
numobjects = struct.unpack('i',plik.read(4))[0]
print 'nummeshes = ',numobjects
texpermesh=[]
for i in range(numobjects):
      info = struct.unpack(5*'i',plik.read(5*4))
      texpermesh.append(info[1])
      numfacespermesh.append(info[3]/3)
      wg = struct.unpack(16*'B',plik.read(16))
      weightsgroup[str(i)]=[]
      for g in wg:
           weightsgroup[str(i)].append(g)
struct.unpack('i',plik.read(4))[0]# TO SAMO W KAZDYM PLIKU
numvertices = struct.unpack('i',plik.read(4))[0]
print 'total numvertices = ',numvertices
groups={}
vertgroup=[]
for i in range(numvertices):
        xyz = struct.unpack(3*'h',plik.read(6))
        v1 = a*xyz[0]*2**-14
        v2 = a*xyz[1]*2**-14
        v3 = a*xyz[2]*2**-14
        vertexy.append([v1,v3,v2])
        dane = struct.unpack(5*'H',plik.read(10))
        u = 2*dane[3]*2**-12
        v = 2*dane[4]*2**-12
        uvcoord.append([u,1-v])
        dane = struct.unpack(8*'B',plik.read(8))
        for j in range(4):
             if dane[j]!=84:
                  if 'grupa'+str(dane[j]) not in groups:
                      groups['grupa'+str(dane[j])]=[]
                      #print dane[j]
                  groups['grupa'+str(dane[j])].append([i,float(dane[j+4])/255])
struct.unpack('i',plik.read(4))
numfaces = struct.unpack('i',plik.read(4))[0]/3
print 'total numfaces = ',numfaces
for i in range(numfaces):
         f= struct.unpack('HHH',plik.read(3*2))
         faceslist.append([f[0],f[1],f[2]])

mesh = bpy.data.meshes.new(object[:-4])
mesh.verts.extend(vertexy)
mesh.faces.extend(faceslist,ignoreDups=True)
for i in range(len(materials)):
    mesh.materials += [materials[i]]

for faceID in range(0,len(mesh.faces)):
            face = mesh.faces[faceID]
            index1 = faceslist[faceID][0]
            index2 = faceslist[faceID][1]
            index3 = faceslist[faceID][2]
            uv1 = Vector(uvcoord[index1])
            uv2 = Vector(uvcoord[index2])
            uv3 = Vector(uvcoord[index3])
            face.uv = [uv1, uv2, uv3]
            face.smooth=True
scene = bpy.data.scenes.active
scene.objects.new(mesh,object[:-4])
mesh.recalcNormals(0)

for i in range(16):                  
     mesh.addVertGroup('grupa'+str(i))
     mesh.update()
for vgroup in groups:
     for dane in groups[vgroup]:
         mesh.assignVertsToGroup(vgroup,[dane[0]],dane[1],1)
mesh.update()


def selectfaces(id,object,id1,id2):
     obj = Object.Get(object)
     mesh=obj.getData(mesh=1)
     for i in range(16):  
         newgrup= str(weightsgroup[str(id)][i])
         if newgrup not in  mesh.getVertGroupNames():              
               mesh.addVertGroup(newgrup)
               mesh.update()
         
     for fid in range(id1,id2):
         face = mesh.faces[fid]
         face.mat = texpermesh[id]
         for namegroup in mesh.getVertGroupNames():
            if 'grupa' in namegroup:
                listvert = mesh.getVertsFromGroup(namegroup)
                #print listvert
                for v in face.v:
                   if v.index in listvert:
                         for inf in groups[namegroup]:
                               if v.index == inf[0]:
                                    nowagrupa=str(weightsgroup[str(id)][int(namegroup[5:])])
                                    mesh.assignVertsToGroup(nowagrupa,[v.index],inf[1],1)

id1=0
for i in range(len(numfacespermesh)):
    id2=id1+numfacespermesh[i]
    #print id1,id2
    selectfaces(i,object[0:-4],id1,id2)
    id1=id2

    DrawProgressBar (i/len(numfacespermesh),"%s"%i)
DrawProgressBar (1,"wczytano")

Redraw()

this python script imports *.bms 3d models into blender, so all i want that *.bms 3d models imports in 3d max.


#283

Hay everyone seen this: https://autodesk.uservoice.com/forums/80701-publicsdkandscriptingenhancements/suggestions/1489587-python?ref=title
Please vote, if you like to see python in 3dsmax!


#284

if i don’t can i vote against? :wink:


#285

write a comment, why this is not good for you… :wink:

why do you against it?


#286

i want to see c# fully integrated in max. from my experience i know when the system tries to support two alternative ways, it makes both of them clumsy.


#287

Hey all -

I know its been a hell of a long time - but the Blur support for Python in 3dsMax is back online. It has been working in production for us for a year now, so a lot of the bugs and clunks from the initial go at it have been worked out.

You can download the project (including source code) here:

blur-dev.googlecode.com

Cheers,
Eric


#288

Thx a lot for it Eric :slight_smile:


#289

Eric - thanks for this - its awesome to have both the source and the plugins to tinker with! Much nicer than the current state of Maxsharp, and more pythonic too. Any chance Autodesk will adopt this in the same way they did Pymel?

Anyone had good luck getting the latest to work? Any stumbling blocks?

I’ve been tinkering with it a bit on Win7x64, Max2011x64, and it does seem to have some rough patches. I’ve been able to get python executing from Maxscript and vice-versa, but I’ve not had much luck getting the logger to come online.

Update: All the logger issues seemed to stem from Qt being unhappy. removing all installs except the one that comes with the blur installer seems to have done the trick :slight_smile:

One last useful thing - Autodesk posted some wonderful Py3dsmax tips that reflect the current build. Could this be a sign of beautiful things to come?

http://area.autodesk.com/blogs/chris/py3dsmax_python_scripting_for_3ds_max_from_blur_studios


#290

Hi together,

please could anyone support the setup with 3dsMax 2012? Tried it a couple of times, changing the path’s and so on without success.
I use the standard installationpaths.


#291

hey guys, i’m trying to set up whats in the op and i’m getting this error in in python when i try to import win32com.client

  File "C:\Python27\lib\site-packages\win32com\__init__.py", line 5, in <module>
    import win32api, sys, os
ImportError: No module named win32api

anyone know whats up with this?


#292

it s a python module

http://code.google.com/p/blur-dev/wiki/Installing

How to get pywin32

Some of our tools will use the pywin32 package for Python, which is a 3rd-party package that can be found here:

pywin32

Direct links to the latest Python24 x32 version are here.

Direct links to the latest Python26 x64 version are here

Here are some instructions to get Python up and running in Softimage if you have not already done so:

[ul]
[li]http://xsisupport.wordpress.com/2010/02/22/getting-python-to-show-up-in-softimage/[/li]> [/ul]


#293

yeah i have the pywin32 module, its just when i try to import win32com.client it fails, are you syaing i need to install all that blur-dev stuff aswell?


#294

it works now, not sure why it wasn’t before, strange


#295

Hi,
I am trying the Py3dsMax python tool.
I took this max script exemple and try to convert it in python.


        macroScript QuickPreview category:"HowTo"
    
    (
     preview_name = (getDir #preview)+"/quickpreview.avi"
     view_size = getViewSize()
     anim_bmp = bitmap view_size.x view_size.y filename:preview_name
      for t = animationrange.start to animationrange.end do
     (
      sliderTime = t
      dib = gw.getViewportDib()
      copy dib anim_bmp
      save anim_bmp
     )
     close anim_bmp
     gc()
     ramplayer preview_name ""
     )
        

I can’t translate these commands

 anim_bmp = bitmap view_size.x view_size.y filename:preview_name
copy dib anim_bmp
save anim_bmp

in a pythonic syntax.

Does anybody have an idea or some code example for Py3dsMax?

Thanks lucas


#296

Most things are accessible via the mxs module, so you should be able to write that code as:

Maxscript:

anim_bmp = bitmap view_size.x view_size.y filename:preview_name
copy dib anim_bmp
save anim_bmp

Python:

anim_bmp = mxs.bitmap( view_size.x, view_size.y, filename = preview_name )
mxs.copy( anim_bmp )
mxs.save( anim_bmp )

I haven’t actually tested that, but that SHOULD work.


#297

My question is basically as it reads in the title. I’m switching from just Maxscript to Python and Maxscript since I understand Python much more. My question is whether or not the built in object sets and arrays like “objects” or “geometry” are still accessible, and if so, what changes in how they are called? Thanks. You guys are very helpful with trying to figure out MaxScript.


#298

Hi all! There is little question:
I need rotate in XForm gizmo. But I can not do that, tell me what the problem is and how to rotate it? Thank you for your attention.

from Py3dsMax import mxs

for obj in mxs.objects:
     XForm = mxs.pyhelper.namify('XForm') #  set flag
     obj.modifiers[XForm].gizmo.rotation += mxs.quat(0.707107, 0, 0, 0.707107) #  rotate 90"

#299

I solved the problem though not completely in Python. I would like to make it completely in Python.

mxs.addModifier(obj, mxs.XForm())
XForm = mxs.pyhelper.namify('XForm') #  set flag
mxs.execute('max modify mode')
mxs.modPanel.setCurrentObject(obj.modifiers[XForm])
mxs.execute('mod_obj = modPanel.getCurrentObject();gizmo_rotation = mod_obj.gizmo.rotation;mod_obj.gizmo.rotation += quat 0.707107 0 0 0.707107') #  rotate 90"



#300

Thanks for the great work Eric. :beer:

Any news on a max 2013 compile?