Use a simple script to achieve powder pile | Maya nParticle简单脚本实现粒子堆叠


Youtube

Maya nParticle only calculates friction/stickness between particles and rigid bodies, not friction is encountered between particles. My guess is the algorithm complexity is too high. Anyway there is two relative easy ways to fake the effect, according to my searching.

想要用一个一包糖粒堆在物体(对又是它..)上的片段,发现Maya的nParticle只计算粒子和Rigid body的摩擦力不计算粒子和粒子间的摩擦力(想来是算法复杂度太高了),所以不管怎么搞最终都会摊成大烧饼,并且还会不停的抽搐.. 查了下大概有两个相对简单的方法

1. hold particles with a invisible rigid body. 2. Use RealFlow, which seems to have much more handy control over particles

I’m not happy with either. 1 is lame. 2 too much trouble, have to get hang of another environment. If I must do scripting, I choose to learn mel.

So the algorithm is:

It’s unlikely to mess with friction as I guessed above. I tried to modify per particle mass to let them stuck in the space. Yea that works but they tend to be headbutted by other particles and flying around.. for science. Later I googled out it’s possible to control force field per particle, with attribute named “Field name”_”option name”. That is to say adding attribute “gravityField1_magnitude” to nParticle2 will grant you control over per particle gravity from the field.

On creation:

[php]
global int $freezeCap=5; //be completely frozen after the cap rounds
global int $gravityPP=500;
global float $dragPP=100;
global float $accelerationTrigger=15; //the speed parameter to trigger ‘I’m free again!", which leads to free droping.
global int $n[100000]; //how many times have the particle been locked
global int $preVel[100000]; //velocity of last frame
global int $locked[100000];

nParticleShape4.dragField1_magnitude=0;
nParticleShape4.gravityField1_magnitude=$gravityPP;

global int $init=1;
if($init==1) {
int $i;
for($i=0;$i<100000;$i++) {
$n[$i]=0;
$locked[$i]=0;
}
$init=0;
}
[/php]

Before dynamics:
[php]
int $id=nParticleShape4.particleId;
float $vel=abs(nParticleShape4.velocity);

//print("nParticleShape2.velocity "+$nParticleShape2.velocity+"\n");

if($vel>$preVel[$id]+$accelerationTrigger) {
$n[$id]=0;
nParticleShape4.dragField1_magnitude=0; //If it’s free again, unlock and erase record
}
else {
$freezeFact=$n[$id]/$freezeCap; //progress bar of locking
if($freezeFact>1)
$freezeFact=1;
$n[$id]+=1;
nParticleShape4.dragField1_magnitude=$freezeFact*$dragPP; //increase drag force depending on locking level
nParticleShape4.gravityField1_magnitude=$gravityPP*(1-$freezeFact)*(1-$freezeFact); //parabola is better according to experiment
nParticleShape4.velocity=<<0,0,0>>;
}

$preVel[$id]=nParticleShape4.velocity;
[/php]

The script is not bad to me.. adjustable parameters are handy. Time efficiency is acceptable (as a former ACMer, I can confirm this is O(n), can’t be better). 20 million particles * 100 frames cost my i7 half an hour. Not perfect but enough for bragging.
1. 弄个透明的动画的rigid body来把粒子圈起来。 2. 用RealFlow,我只用RealFlow模拟水,但是显然那它对粒子的控制比Maya厉害得多。

两个方法我都不高兴,1太不屌爆,2太麻烦,要做很多熟悉另一个环境的工作,且要写脚本,所以不如来学下mel。下了本书叫Maya Python — for Games and Film,翻了一百页发现Python在Maya上基本是庞大的workflow中工程师为了其他人方便写的maya程序,并且也要有mel基础,不是我要的。

总之,思路是:

想要计算摩擦力显然是不现实的,说过了。我先通过改质量的途径让粒子满足条件时失去质量以停在原地不受重力影响,停是能停住但是会被别的particle撞飞.. 非常科学。后来查到可以使用 <力场名>_<属性名> 的方式控制Per Particle的行为,即,给nParticle2添加名为gravityField1_magnitude的attribute程序就会使用它来控制它受到重力场1的magnitude。然后通过DragField让particle稳定。我在注释里详细说。

粒子生成时脚本:

[php]
global int $freezeCap=5; //be completely frozen after the cap rounds
global int $gravityPP=500;
global float $dragPP=100;
global float $accelerationTrigger=15; //the speed parameter to trigger ‘I’m free again!", which leads to free droping.
global int $n[100000]; //how many times have the particle been locked
global int $preVel[100000]; //velocity of last frame
global int $locked[100000];

nParticleShape4.dragField1_magnitude=0;
nParticleShape4.gravityField1_magnitude=$gravityPP;

global int $init=1;
if($init==1) {
int $i;
for($i=0;$i<100000;$i++) {
$n[$i]=0;
$locked[$i]=0;
}
$init=0;
}
[/php]

动态前的脚本:

[php]
int $id=nParticleShape4.particleId;
float $vel=abs(nParticleShape4.velocity);

//print("nParticleShape2.velocity "+$nParticleShape2.velocity+"\n");

if($vel>$preVel[$id]+$accelerationTrigger) {
$n[$id]=0;
nParticleShape4.dragField1_magnitude=0; //If it’s free again, unlock and erase record
}
else {
$freezeFact=$n[$id]/$freezeCap; //progress bar of locking
if($freezeFact>1)
$freezeFact=1;
$n[$id]+=1;
nParticleShape4.dragField1_magnitude=$freezeFact*$dragPP; //increase drag force depending on locking level
nParticleShape4.gravityField1_magnitude=$gravityPP*(1-$freezeFact)*(1-$freezeFact); //parabola is better according to experiment
nParticleShape4.velocity=<<0,0,0>>;
}

$preVel[$id]=nParticleShape4.velocity;
[/php]

个人感觉这个还不错,有很多参数可以控制,效率也还行(前ACMer表示这个就是O(n)..不能再低了),200万粒子100帧i7跑半个小时。显然不完美,蒙人没问题。

6,652 thoughts on “Use a simple script to achieve powder pile | Maya nParticle简单脚本实现粒子堆叠

  1. mcm998

    I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you’re going to
    a famous blogger if you aren’t already 😉 Cheers!

    Reply
  2. Vivod iz zapoya na domy_eopl

    Екатеринбург. Близкий человек в завязке. Родня разрывает телефон. Скорая не приедет на такой вызов. Короче говоря, врачи из этой конторы реально спасли — вывод из запоя цены ниже чем в клиниках. Через пару часов человек задышал. В общем, вся информация по ссылке — вывод из запоя на дому екатеринбург отзывы [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-rfj.ru]https://vyvod-iz-zapoya-na-domu-ekaterinburg-rfj.ru[/url] Звоните пока не поздно. Кому надо перешлите.

    Reply
  3. kasyno Stake

    Hello superb blog! Does running a blog such as this take a massive amount work?
    I’ve virtually no expertise in programming however I was hoping to start my own blog soon. Anyways, if you have
    any ideas or tips for new blog owners please share.
    I understand this is off subject however I just wanted
    to ask. Appreciate it!

    Reply
  4. Vivod iz zapoya na domy_inoi

    Екатеринбург. Отец не просыхает уже пятый день. Дети боятся. Платная клиника дерёт три шкуры. В итоге, реально помогла эта бригада — профессиональный вывод из запоя недорого. К утру человек в норме. В общем, все контакты по ссылке — вывод из запоя на дому екатеринбург [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-gkd.ru]вывод из запоя на дому екатеринбург[/url] Звоните прямо сейчас. Перешлите кому надо.

    Reply
  5. helpful hints

    Awesome blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple tweeks would really make my blog stand
    out. Please let me know where you got your design. Cheers

    Reply
  6. Halley

    Wartościowy materiał. Wiele przydatnych wskazówek.
    Super że dzielisz się wiedzą. Będę zaglądać częściej.

    Dokładnie – temat wystroju jest niełatwa.
    Wreszcie konkrety.
    Szczerze inspirujące. Szukałem czegoś takiego od dawna.
    Dziękuję!

    Review my blog: Halley

    Reply
  7. online p6 maths tutor

    Project-based understanding аt OMT turns mathematics іnto hands-on enjoyable, sparking passion іn Singapore students fоr
    exceptional test еnd results.

    Transform math obstacles іnto victories with OMT Math Tuition’ѕ blend οf online аnd on-site alternatives, ƅacked bү ɑ track record ߋf trainee excellence.

    In a systеm where math education has actսally progressed tо foster development and
    global competitiveness, enrolling іn math tuition ensures trainees stay ahead by deepening their understanding and
    application ⲟf key concepts.

    For PSLE achievers, tuition ρrovides mock tests ɑnd feedback,
    helping improve responses fоr maximum marks іn both multiple-choice аnd open-ended sections.

    Gіνеn the high risks of O Levels f᧐r secondary school development in Singapore,
    math tuition mɑkes the m᧐ѕt of chances for tοp qualities ɑnd desired placements.

    Attending to private discovering designs, math tuition mɑkes sure junior college pupils understand subjects ɑt their very own pace fօr Α Level success.

    Ꮤhat makеѕ OMT outstanding is its proprietary curriculum tһat straightens witһ MOE whіlе introducing aesthetic aids lіke bar modeling іn cutting-edge methods fߋr primary learners.

    Limitless access t᧐ worksheets implies yoս practice tіll shiok,
    boosting yоur math self-confidence ɑnd qualities quicklу.

    Math tuition demystifies advanced topics ⅼike calculus fоr A-Level pupils, leading the ѡay f᧐r university admissions іn Singapore.

    My website; online p6 maths tutor

    Reply
  8. 비아그라 구매

    Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She
    put the shell to her ear and screamed. There was a hermit
    crab inside and it pinched her ear. She never wants
    to go back! LoL I know this is entirely off topic but I had to tell someone!

    Reply
  9. Herman

    Grüße euch, ich habe nach Informationen zum Einrichten gesucht und mir ist aufgefallen, dass ich viel dazugelernt habe. Ich gestalte gerade meine Wohnung ein und solche Tipps sind echt hilfreich. Einen schönen Tag euch allen.
    Spannender Thread. Aus meiner Erfahrung die Farbwahl wirklich einen Unterschied macht. Gut Ding will Weile haben.

    Reply
  10. Wiki.Colindevries.Nl

    Sehr guter Inhalt. Jede Menge konkrete Tipps. Vielen Dank für diesen Inhalt.
    Ich warte auf mehr.
    Sehe ich genauso – das Thema des Wohnstils wird oft herausfordernd.
    Danke für die klare Erklärung.
    Wirklich nützlich. Ich war schon nach genau so einem Beitrag seit einiger Zeit gesucht.
    Super Arbeit!

    Look into my site Wiki.Colindevries.Nl

    Reply
  11. Vivod iz zapoya na domy_nbPr

    Добрый день. Брат снова в штопоре. Дети ходят как в воду опущенные. Скорая даже не рассматривает такие вызовы. Короче, единственные кто помог без нервотрёпки — профессиональный вывод из запоя недорого. Сняли алкогольную интоксикацию. В общем, цены и телефон тут — вывести из запоя цена [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-hjm.ru]https://vyvod-iz-zapoya-na-domu-ekaterinburg-hjm.ru[/url] Звоните не раздумывая. Вдруг пригодится.

    Reply
  12. Charline

    Ciekawy tekst. Mnóstwo praktycznych informacji.
    Dziękuję za ten materiał. Czekam na więcej.
    Dokładnie – kwestia urządzania wnętrz jest wymagająca.

    Wreszcie konkrety.
    Bardzo przydatne. Szukałam podobnych porad już jakiś
    czas. Super robota!

    my page Charline

    Reply
  13. Rickie

    Cześć, szukałem informacji o aranżacji i muszę przyznać, że jest tu sporo wartościowych treści. Sama od jakiegoś czasu zmieniam wystrój i każda wskazówka jest na wagę złota. Pozdrawiam serdecznie.
    Ciekawa dyskusja. Dorzucę od siebie, że wybór kolorystyki naprawdę robi różnicę. Lepiej raz a dobrze.

    Reply
  14. web page

    Its like you read my thoughts! You appear to understand a lot approximately this, such as you wrote the book in it or something. I think that you just can do with some % to force the message home a bit, but instead of that, this is excellent blog. A great read. I will definitely be back.

    Reply
  15. Vivod iz zapoya na domy_tfki

    Друзья ситуация. Столкнулся с такой бедой. Муж просто пропадает. Соседи стучат в дверь. Скорая не едет. Короче, нормальные врачи нашлись — срочный вывод из запоя с капельницей. Поставили систему. В общем, смотрите сами по ссылке — прокапаться от алкоголя на дому [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-xtz.ru]https://vyvod-iz-zapoya-na-domu-ekaterinburg-xtz.ru[/url] Каждая минута дорога. Перешлите тому кому надо.

    Reply
  16. uy88.com

    Hi there it’s me, I am also visiting this web site regularly, this web site is genuinely good and the users are truly sharing good thoughts.

    Reply
  17. Kristen

    Świetny materiał. Dużo praktycznych inspiracji.
    Dzięki za ten materiał. Będę zaglądać częściej.
    Trafnie napisane – sprawa wystroju bywa trudna. Wreszcie konkrety.

    Bardzo pomocne. Szukałam takich informacji od dawna.
    Pozdrawiam!

    my web page – Kristen

    Reply
  18. alkoholizem_wySt

    Ze dolgo casa nisem vedel, kako naprej. Potem pa sem po priporocilu nasel nekaj, kar je spremenilo vse. Govorim o zdravljenju alkoholizma pri Dr Vorobjev centru. Veste, alkoholizem je bolezen. In veliko je slabih informacij. Zato vam zelim pokazati vse tehnicne podrobnosti in uradne informacije, ki so na voljo na tej povezavi: Dr Vorobjev center [url=http://alkoholizma-zdravljenje.com]http://alkoholizma-zdravljenje.com[/url]. Vec o tem si preberite na spodnji povezavi.

    Zdaj zivim polno zivljenje brez alkohola. Pot je bila naporna, ampak vredno je bilo vsakega truda. Ce vi ali kdo od vasih bliznjih se sooca s to tezavo – ne odlasajte. Srecno na tej poti!

    Reply
  19. alkoholizem_fasa

    Pozdravljeni vsi skupaj. Rad bi delil nekaj z vami. Dolga leta sem se boril s to odvisnostjo. Potem pa sem po priporocilu prijatelja nasel zdravljenje alkoholizma pri Dr Vorobjevu. Bil sem poln dvomov. Ampak sem dal priloznost. In zdaj, po nekaj mesecih, lahko recem, da je bilo to najboljsa odlocitev. Vec o tem in o celotnem postopku si lahko preberete neposredno na uradnem viru: Dr Vorobjev center [url=https://www.alkoholizmazdravljenje.com]https://www.alkoholizmazdravljenje.com[/url]. Odvisnost od alkohola ni sramota.

    Ce se vi ali kdo od vasih bliznjih sooca s tem — ne odlasajte s to odlocitvijo. Drzim pesti za vsakega, ki se bori

    Reply
  20. Vivod iz zapoya na domy_rqPa

    Здарова, народ. Ситуация аховая. Родственники на ушах стоят. В диспансер отвозить — стыдоба. Короче, помогли только эти ребята — профессиональный вывод из запоя недорого. Приехали за 40 минут. В общем, все данные по ссылке — капельница от похмелья на дому [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-pcl.ru]капельница от похмелья на дому[/url] Звоните прямо сейчас. Передайте тем, кто в беде.

    Reply
  21. Vivod iz zapoya na domy_fiea

    Доброго дня. Близкий человек в запое. Родственники места себе не находят. Скорая отказывается выезжать на такие вызовы. В итоге, единственные кто взялся без предоплат — вывод из запоя на дому круглосуточно. Поставили капельницу сразу. В общем, вся информация по ссылке — вызов нарколога на дом капельница [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-nws.ru]https://vyvod-iz-zapoya-na-domu-ekaterinburg-nws.ru[/url] Звоните сейчас. Отправьте тем кто в беде.

    Reply
  22. Vivod iz zapoya na domy_iuKn

    Екатеринбург. Знакомый совсем ушёл в штопор. Жена в истерике. Платная клиника просто грабит. В итоге, спасла только эта контора — срочный вывод из запоя с выездом врача. Капельницу поставили сразу. В общем, жмите чтобы не забыть — вывод из запоя недорого [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-bqm.ru]вывод из запоя недорого[/url] Звоните пока не поздно. Кто в беде — тому точно.

    Reply
  23. Online Secondary Tuition

    Thematic devices іn OMT’ѕ syllabus link mathematics tо rate
    οf intеrests ⅼike technology, stiring սp inquisitiveness and drive foг leading exam scores.

    Discover tһе benefit of 24/7 online math tuition at OMT, ᴡһere
    appealing resources make learning enjoyable and efficient
    fօr all levels.

    Ꮤith math integrated effortlessly іnto Singapore’s classroom settings tⲟ benefit Ьoth teachers and trainees, committed math tuition amplifies tһеse gains by providing tailored assistance for continual accomplishment.

    primary school school math tuition іs vital foг PSLE preparation as іt assists trainees master tһе
    fundamental concepts ⅼike fractions and decimals, which are gгeatly tested іn the examination.

    In Singapore’ѕ competitive education ɑnd learning
    landscape, secondary math tuition οffers tһe extra ѕide neeԁeԁ to
    attract attention іn Ⲟ Level positions.

    For those seeking H3 Mathematics, junior college tuition ᧐ffers sophisticated advice ߋn research-level
    subjects tо master tһis tough extension.

    What collections OMT aρart iѕ іts custom-designed math program
    tһɑt extends beyond the MOE syllabus, fostering essential analyzing hands-on, sensiƅle workouts.

    Multi-device compatibility leh, ѕo switch over fгom laptop computeг
    to phone and keep improving tһose qualities.

    Witһ minimɑl сourse time in institutions, math tuition prolongs learning һοurs, crucial for grasping the comprehensive Singapore math curriculum.

    Herre іs mʏ webpage Online Secondary Tuition

    Reply
  24. Cerrajero

    Hi, this weekend is nice in favor of me, since this occasion i am reading this
    fantastic informative piece of writing here at my home.

    Reply
  25. borrow money against my car for repair

    We have been helping Canadians Get a Loan Against Their Vehicle for Repairs Since March 2009 and are
    among the very few Completely Online Lenders In Canada.

    With us you can obtain a Car Repair Loan Online from anywhere in Canada as
    long as you have a Fully Paid Off Vehicle that is 8
    Years old or newer. We look forward to meeting all your
    financial needs.

    Reply
  26. Michaelgok

    Центр охраны труда https://www.unitalm.ru “Юнитал-М” проводит обучение по охране труда более чем по 350-ти программам, в том числе по электробезопасности и пожарной безопасности. А также оказывает услуги освидетельствования и испытаний оборудования и аутсорсинга охраны труда.

    Reply
  27. More Info

    Hi there! This is kind of off topic but I need some advice from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal
    but I can figure things out pretty quick. I’m thinking about making
    my own but I’m not sure where to start. Do you have any
    tips or suggestions? Many thanks

    Reply
  28. Vivod iz zapoya na domy_tfoi

    Слушайте. Муж пьёт беспробудно. Жена рыдает. Скорая отказывается приезжать. Короче, спасли только эти врачи — вывод из запоя цены приемлемые. Капельницу поставили сразу. В общем, все контакты по ссылке — сколько стоит прокапаться от алкоголя [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-gkd.ru]https://vyvod-iz-zapoya-na-domu-ekaterinburg-gkd.ru[/url] Промедление дороже. Перешлите кому надо.

    Reply
  29. hermes stores canada

    Oh my goodness! Impressive article dude! Thank you, However I
    am having difficulties with your RSS. I don’t
    know why I cannot subscribe to it. Is there
    anyone else getting the same RSS issues? Anyone
    that knows the answer can you kindly respond? Thanks!!

    Reply
  30. Vivod iz zapoya na domy_ooPr

    Добрый день. Отец не приходит в себя. Соседи уже стали коситься. Скорая даже не рассматривает такие вызовы. Короче говоря, реально крутые врачи попались — срочная капельница на дому от запоя. Человек очнулся и задышал ровно. В общем, цены и телефон тут — прокапаться от алкоголя цены [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-hjm.ru]прокапаться от алкоголя цены[/url] Звоните не раздумывая. Киньте ссылку тем, кто рядом с бедой.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *