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,263 thoughts on “Use a simple script to achieve powder pile | Maya nParticle简单脚本实现粒子堆叠

  1. สล็อต

    Terrific article! This is the type of information that should be shared around the internet.

    Disgrace on Google for not positioning this post higher!
    Come on over and visit my site . Thanks =)

    Reply
  2. Narkologicheskii stacionar_sipa

    Люди помогите советом Близкий человек уже неделю в запое Соседи стучат в стену Платная клиника — бешеные деньги Короче, врачи вытащили с того света — госпитализация в наркологический стационар 24/7 Капельницы и препараты подбирали индивидуально В общем, телефон и цены тут — лечение наркомании стационар [url=https://narkologicheskij-staczionar-moskva-vex.ru]https://narkologicheskij-staczionar-moskva-vex.ru[/url] Звоните прямо сейчас Перешлите тем кто в отчаянии

    Reply
  3. 이심

    hello!,I really like your writing very much!
    proportion we be in contact more approximately your post on AOL?
    I requir a specialist on this area to ressolve my problem.
    Mayb that is you! Taking a look ahead to see you.

    이심

    Reply
  4. Aiyaphorm RECENSIONI

    I am now not sure the place you are getting your information, however
    good topic. I needs to spend some time finding out more or
    understanding more. Thank you for excellent information I was searching
    for this info for my mission.

    Reply
  5. situs 18+

    Howdy just wanted to give you a quick heads up and let you know a few of the images aren’t loading properly.
    I’m not sure why but I think its a linking issue. I’ve tried it in two
    different internet browsers and both show the same results.

    Reply
  6. codigo cbet

    I just couldn’t go away your website before suggesting
    that I really loved the usual information a person supply to
    your visitors? Is going to be back regularly in order to check out new posts

    Reply
  7. TheOption 入出金方法

    バイナリーオプション 初心者 – 取引の流れを丁寧に解説.
    リスク管理が初心者の最重要ポイント.
    サポートが手厚く安心. 焦らずコツコツ学ぶ
    ザオプション ボーナス – 出金条件があるので要確認.
    メールやアプリでお知らせが届く.
    初心者にも優しい条件設定. お得に始めるならボーナス必須
    バイナリーオプション 比較 – 口コミや評判をチェック.

    取引ツールや分析機能も確認. 初心者から上級者まで満足できる.
    自分に合った条件を最優先に
    バイナリー 少額取引 – 取引に慣れるまでは少額が安心.
    慣れてきたら段階的に金額を増やす. ザオプションは少額取引に対応.
    焦らずじっくり取引を楽しむ

    Reply
  8. bally bet ontario

    This design is steller! You certainly know how to keep a reader entertained.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
    I really enjoyed what you had to say, and more than that, how you
    presented it. Too cool!

    Reply
  9. watch now

    I like the helpful information you supply in your articles.
    I will bookmark your blog and test once more here regularly.

    I am fairly certain I will be told many new stuff
    proper right here! Good luck for the next!

    Reply
  10. driving habits

    Solid breakdown of the topic — the way this is explained really works.
    I have been thinking about this exact topic recently and
    your points genuinely helped. What I appreciate most was how the actual considerations were laid out
    plainly. A lot of content stays superficial — refreshing to see something that respects the reader.
    Definitely coming back to this when I finalise my own decisions.
    Really value posts like this in a sea of generic advice.

    Reply
  11. rape sex child

    Hi! I know this is kinda off topic but I was wondering if you knew where I could get a captcha
    plugin for my comment form? I’m using the same blog platform as yours and I’m
    having problems finding one? Thanks a lot!

    Reply
  12. Narkologicheskii stacionar_dcel

    Слушайте кто знает Кошмар в семье Соседи уже вызвали участкового В диспансер тащить — последнее дело Короче, врачи стационара реально вытащили — госпитализация в наркологический стационар 24/7 Положили в палату В общем, не потеряйте контакты — стационар наркологический москва [url=https://narkologicheskij-staczionar-moskva-bny.ru]https://narkologicheskij-staczionar-moskva-bny.ru[/url] Стационар — это единственный выход Это может спасти жизнь

    Reply
  13. Narkologicheskii stacionar_abSt

    Слушайте кто знает Сосед совсем спился Мать места себе не находит Скорая не приезжает на такие вызовы Короче, единственное что сработало — лечение в наркологическом стационаре под контролем Положили в палату В общем, жмите чтобы сохранить — наркологические стационары [url=https://narkologicheskij-staczionar-moskva-fal.ru]наркологические стационары[/url] Звоните прямо сейчас Перешлите тем кто в такой же беде

    Reply
  14. horus casino

    Howdy! This blog post couldn’t be written any better!
    Looking through this post reminds me of my previous
    roommate! He continually kept talking about this. I’ll
    send this article to him. Pretty sure he’s going to
    have a great read. Thank you for sharing!

    Reply
  15. Narkologicheskii stacionar_ejEt

    Здорова, народ Мой друг уже 9 дней в запое Дети боятся заходить в дом Платная клиника — бешеные счета Короче, врачи стационара реально помогли — госпитализация в наркологический стационар 24/7 Выписали через 4 дня здоровым В общем, телефон и цены тут — наркологическая клиника стационар [url=https://narkologicheskij-staczionar-moskva-rtv.ru]наркологическая клиника стационар[/url] Звоните прямо сейчас Перешлите тем кто в такой же беде

    Reply
  16. Narkologicheskii stacionar_dlSl

    Слушайте кто сталкивался Мой брат уже две недели в запое Родные просто в шоке Скорая отказывается выезжать Короче, спасла только госпитализация — наркологический стационар цена доступная Сделали кодировку на год В общем, не потеряйте контакты — лечение в наркологическом стационаре [url=https://narkologicheskij-staczionar-moskva-cde.ru]лечение в наркологическом стационаре[/url] Не надейтесь на чудо Это может спасти жизнь близкого

    Reply
  17. Narkologicheskii stacionar_ijer

    Здорова, народ Беда пришла в семью Жена в истерике Платная клиника — бешеные деньги Короче, врачи вытащили с того света — платный наркологический стационар с палатами Провели полную детоксикацию В общем, жмите чтобы сохранить — наркологический стационар москва [url=https://narkologicheskij-staczionar-moskva-lba.ru]https://narkologicheskij-staczionar-moskva-lba.ru[/url] Стационар — это реальный шанс Перешлите тем кто в отчаянии

    Reply
  18. Narkologicheskii stacionar_tqpr

    Москва, всем привет Близкий человек уже 10 дней в запое Соседи уже вызвали участкового В диспансер тащить — последнее дело Короче, врачи стационара реально вытащили — лечение в наркологическом стационаре с психологом Врачи и медсёстры 24/7 В общем, телефон и цены тут — наркология москва стационар [url=https://narkologicheskij-staczionar-moskva-jmw.ru]https://narkologicheskij-staczionar-moskva-jmw.ru[/url] Стационар — это единственный выход Это может спасти жизнь

    Reply
  19. Narkologicheskii stacionar_goei

    Слушайте кто знает Близкий человек уже 10 дней в запое Жена рыдает Скорая не приедет на такой вызов Короче, врачи стационара реально вытащили — госпитализация в наркологический стационар 24/7 Положили в палату В общем, вся инфа по ссылке — палата в наркологии [url=https://narkologicheskij-staczionar-moskva-zrt.ru]https://narkologicheskij-staczionar-moskva-zrt.ru[/url] Не ждите пока станет хуже Это может спасти жизнь

    Reply
  20. Narkologicheskii stacionar_ipPt

    Всем привет из Москвы Отец не встаёт с кровати Родные просто в шоке В диспансер тащить — стыд и страх Короче, единственное что сработало — лечение в наркологическом стационаре с психотерапией Сделали кодировку на год В общем, телефон и цены тут — наркологический стационар цена [url=https://narkologicheskij-staczionar-moskva-pfk.ru]наркологический стационар цена[/url] Не надейтесь на чудо Перешлите тем кто в такой же беде

    Reply
  21. kobicms.com

    This design is spectacular! You obviously know how to
    keep a reader entertained. Between your wit and your videos, I
    was almost moved to start my own blog (well, almost…HaHa!) Great job.
    I really loved what you had to say, and more than that, how you presented it.
    Too cool!

    Reply
  22. Hammer of thor

    Excellent post. I was checking continuously this blog and I’m impressed!
    Very helpful info particularly the last part 🙂 I care for such information a lot.
    I was seeking this certain information for a long time.

    Thank you and good luck.

    Reply
  23. The Epoch Times

    Heya! I’m at work surfing around your blog
    from my new iphone 4! Just wanted to say I love
    reading through your blog and look forward to all your posts!
    Keep up the great work!

    Reply
  24. Buy European

    I would like to thank you for the efforts you have put
    in penning this website. I’m hoping to see the same high-grade content by you later
    on as well. In truth, your creative writing abilities has motivated me to get my own, personal
    blog now 😉

    Reply
  25. HRZ file converter

    Pretty great post. I just stumbled upon your blog and wished to say that I have really loved surfing around your blog posts.
    After all I’ll be subscribing in your rss feed and I hope you write again soon!

    Reply
  26. 일본 이심

    Whaqts up thi is somewhat of off topic but I was wanting to
    know iif blogs use WYSIWYG editors or if you have to manuallky code with HTML.
    I’m starting a blog soon but have no coding know-how so I wanted to get advice from someone
    with experience. Any help would be greatly appreciated!

    일본 이심

    Reply
  27. ai cold calling software

    I think what you posted made a bunch of sense. However, consider this, suppose you composed a catchier post title?
    I ain’t suggesting your content is not good, but what if you
    added a headline that makes people want more? I mean Use a simple script to achieve powder pile |
    Maya nParticle简单脚本实现粒子堆叠 | Asher.GG is kinda boring.
    You ought to look at Yahoo’s home page and watch
    how they create article headlines to grab people interested.
    You might add a video or a related pic or two to get
    readers interested about what you’ve written. Just my opinion, it would
    bring your website a little bit more interesting.

    Reply
  28. Kapelnica ot pohmelya_paml

    Здорова, народ Тошнит, трясёт, сил нет Рассол уже не лезет Короче, врачи приехали и поставили систему — капельница при похмелье с препаратами Поставили капельницу с солевым раствором В общем, телефон и цены тут — поставить капельницу от алкоголизма [url=https://kapelnicza-ot-pokhmelya-samara-lhb.ru]https://kapelnicza-ot-pokhmelya-samara-lhb.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации

    Reply
  29. блог о жизни

    First of all I want to say wonderful blog! I had a quick question in which I’d like to ask
    if you don’t mind. I was curious to know how you center yourself and clear your head prior to writing.
    I have had a hard time clearing my mind in getting my ideas out there.
    I do take pleasure in writing but it just seems like the first 10 to 15 minutes are
    generally lost just trying to figure out how to begin. Any recommendations or tips?
    Thanks!

    Reply
  30. site here

    Appreciating the time and effort you put into your website and in depth information you provide.
    It’s great to come across a blog every once in a while that isn’t the same outdated rehashed information. Excellent read!
    I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

    Reply
  31. ดูซีรี่ย์

    Terrific article! This is the kind of info that are supposed
    to be shared across the internet. Disgrace on Google for no longer positioning this
    submit upper! Come on over and consult with my site .

    Thanks =)

    Reply
  32. Narkologicheskii stacionar_mhel

    Здорова, народ Брат потерял человеческий облик Родственники в полном отчаянии Скорая не приедет на такой вызов Короче, спасла только госпитализация — платный наркологический стационар с палатами Провели полную детоксикацию В общем, не потеряйте контакты — наркологические центры москвы цены [url=https://narkologicheskij-staczionar-moskva-bny.ru]https://narkologicheskij-staczionar-moskva-bny.ru[/url] Звоните прямо сейчас Это может спасти жизнь

    Reply
  33. Narkologicheskii stacionar_trpa

    Москва, всем привет Отец не выходит из штопора Соседи стучат в стену В диспансер тащить — страшно и стыдно Короче, единственные кто взялся за сложный случай — платный наркологический стационар с палатами Капельницы и препараты подбирали индивидуально В общем, вся инфа по ссылке — клиника наркологическая стационар москва [url=https://narkologicheskij-staczionar-moskva-vex.ru]https://narkologicheskij-staczionar-moskva-vex.ru[/url] Звоните прямо сейчас Перешлите тем кто в отчаянии

    Reply
  34. Narkologicheskii stacionar_fqSt

    Люди подскажите Брат умирает на глазах Мать места себе не находит Платная клиника — бешеные счета Короче, единственное что сработало — наркологическая больница стационар с капельницами Провели полное очищение организма В общем, не потеряйте контакты — наркологический стационар цена [url=https://narkologicheskij-staczionar-moskva-fal.ru]наркологический стационар цена[/url] Стационар — единственное решение Перешлите тем кто в такой же беде

    Reply

Leave a Reply

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