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跑半个小时。显然不完美,蒙人没问题。

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

  1. Casie

    Hello! Do you use Twitter? I’d like to follow you if that would be ok.
    I’m definitely enjoying your blog and look forward to new
    posts.

    Reply
  2. 구글상위노출

    Hi there this is somewhat of off topic but I was
    wanting to know if blogs use WYSIWYG editors or if you have to manually
    code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get advice from
    someone with experience. Any help would be enormously appreciated!

    Reply
  3. click this

    Having read this I believed it was very enlightening.
    I appreciate you taking the time and energy to put this
    article together. I once again find myself spending a lot of time both reading and
    leaving comments. But so what, it was still
    worthwhile!

    Reply
  4. Bhubaneswar Call Girl

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

    Reply
  5. web page

    You really make it seem so easy with your presentation but I
    find this topic to be really something that I think I
    would never understand. It seems too complex and extremely broad for me.
    I’m looking forward for your next post, I will try to get the hang of it!

    Reply
  6. repuestos de vehiculos

    Hey there! This post couldn’t be written any better!
    Reading this post reminds me of my previous room mate!
    He always kept chatting about this. I will forward this
    post to him. Pretty sure he will have a good read. Thanks for sharing!

    Reply
  7. B1Agalyeon.москва

    Magnificent beat ! I wish to apprentice while you amend your site, how could i
    subscribe for a blog website? The account aided me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast provided bright clear idea

    Reply
  8. http://altbookmark.com,59,54,https://altbookmark.com/story22806914/repuestos-agrícolas

    Hi there would you mind sharing which blog platform you’re
    using? I’m looking to start my own blog soon but I’m having a difficult
    time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems
    different then most blogs and I’m looking for something unique.
    P.S My apologies for being off-topic but I had to ask!

    Reply
  9. crowdemprende.com

    Hi, i believe that i noticed you visited my website so i came to return the want?.I’m attempting to find things to enhance my site!I guess its good enough
    to use a few of your ideas!!

    Reply
  10. Flossie

    Ciekawy wpis. Dużo przydatnych inspiracji. Dzięki że dzielisz się wiedzą.
    Polecam innym.
    Dokładnie – kwestia doboru mebli bywa niełatwa.

    Dobrze, że ktoś to wyjaśnia.
    Szczerze pomocne. Szukałem podobnych porad już jakiś czas.
    Dziękuję!

    Here is my homepage :: Flossie

    Reply
  11. press release

    I never imagined that I would end up divorced. For years I built my career,
    believing that everything was fine. Then one day I discovered that my wife
    was involved with someone else. What hurt the most was that he had a lot of money.
    My world fell apart.
    The separation was emotionally exhausting. I spent countless nights awake.
    At first I blamed myself. I worried about starting over.
    But eventually I understood the truth: my future depended on me.

    Instead of living in the past, I became determined to rebuild
    my life. I started studying investing. Every day
    I learned about asset allocation, blockchain technology,
    and wealth preservation.
    Eventually I found Paybis and it changed my routine. What stood out immediately was how simple the platform felt.

    Managing digital assets became surprisingly efficient.

    These days I rely on Paybis for converting digital assets
    into traditional currency. Everything is easy to follow.

    I can track transactions while maintaining
    better financial organization.
    The fintech side fascinated me. Learning about blockchain settlements gave me a new perspective on money.
    I analyzed trends. Gradually I became more confident with my
    decisions.
    Then something unexpected happened. As my finances improved, I realized that the problem was never financial.
    The real issue was attitude. No amount of money can fix that.

    Things changed when I least expected it. A new relationship entered my life.

    She was younger than my ex. What mattered most she was encouraging and respectful.

    Today I feel stronger than ever. That period of
    my life is finished. I regained confidence, improved my future, and found a new beginning.

    In hindsight, I don’t hold onto bitterness.
    I respect the journey. The worst moment became a turning point.
    My financial journey reminds me how much I have grown. The emotions are incredible—relief,
    excitement, confidence, and gratitude all at once.

    Reply
  12. TRADING PLATFORM REVIEW

    Hi, I do believe this is an excellent web
    site. I stumbledupon it 😉 I am going to come back once again since i have saved as a favorite it.

    Money and freedom is the greatest way to change,
    may you be rich and continue to help other people.

    Reply
  13. Lingou aur

    I have read so many articles or reviews on the topic of the blogger lovers but this post is in fact a pleasant article,
    keep it up.

    Reply
  14. math tuition jc

    The caring atmosphere ɑt OMT encourages interest in mathematics,
    turning Singapore students іnto passionate learners inspired tо achieve tߋp exam outcomes.

    Dive іnto self-paced math proficiency ѡith OMT’s 12-month e-learning courses, tοtal wіth practice worksheets аnd tape-recorded sessions fօr comprehensive
    modification.

    Αs mathematics forms tһе bedrock of abstract thought ɑnd critical problem-solving in Singapore’ѕ education system, expert math tuition supplies tһe customized assistance necessary to turn difficulties іnto victories.

    Tuition іn primary school mathematics іs essential fοr PSLE preparation, аs it introduces
    advanced methods fоr dealing with non-routine pгoblems that
    stump numerous prospects.

    Secondary math tuition lays а strong groundwork fօr post-O Level researches,
    ѕuch aѕ A Levels оr polytechnic courses, Ьʏ excelling in foundational subjects.

    Βy supplying extensive experiment pɑѕt A Level examination documents,
    math tuition acquaints trainees ᴡith concern layouts
    ɑnd noting systems fօr ideal efficiency.

    By integrating exclusive strategies ᴡith the MOE curriculum, OMT supplies аan unique method tbat stresses clearness аnd deepness in mathematical thinking.

    Gamified elements mɑke revision enjoyable lor, encouraging mⲟre teschnique andd causing quality renovations.

    Singapore’ѕ concentrate on all natural education іѕ matched by math
    tuition that constructs sеnsible reasoning fօr lifelong test advantages.

    Taқe a loοk аt my web site; math tuition jc

    Reply
  15. learn more

    Good cleaning can help save time.
    This applies to offices where maintenance matters.
    One example in this field is reinigungs-profies.de.

    Reply
  16. 世界杯

    Greetings I am so glad I found your webpage, I really found you by mistake, while I was researching on Digg for something else, Anyways I am here now and would just like to say thanks a lot
    for a tremendous post and a all round thrilling blog (I also love the theme/design), I don’t have time to browse
    it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great work.

    Reply
  17. Mohammed

    Having read this I thought it was rather enlightening. I appreciate you taking the
    time and energy to put this content together. I once again find myself spending
    a significant amount of time both reading and posting comments.

    But so what, it was still worthwhile!

    Reply
  18. 中国钓鱼人网官网app

    Does your site have a contact page? I’m having trouble locating it
    but, I’d like to shoot you an e-mail. I’ve got some suggestions for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it
    develop over time.

    Reply
  19. Vivod iz zapoya na domy_qipn

    Сил уже нет, человек просто не просыхает. Что делать — непонятно. Проверенный вариант — срочный вывод из запоя без лишних вопросов. Не шарлатаны какие-то. Короче, смотрите сами по ссылке — вывод из запоя круглосуточно [url=https://vyvod-iz-zapoya-na-domu-voronezh-bvc.ru]вывод из запоя круглосуточно[/url] Каждая пьянка минус ресурс. Сам через это прошел, чем хоронить близкого. Очень советую эту контору.

    Reply
  20. alkoholizem_hson

    Zdravo, ljudje. Že dolgo sem iskal resnično rešitev. Ko gre za odvajanje od alkohola — veliko ljudi se muči v tišini. Prijatelj mi je svetoval en center, kjer res vedo, kaj delajo. Govorim o Dr Vorobjev centru. Vse podrobnosti in izkušnje drugih ljudi najdete tukaj: zdravljenje alkoholizma [url=https://www.alkoholizem-zdravljenje.com]zdravljenje alkoholizma[/url] Najboljša odločitev, kar sem jih kdaj sprejel. Odvisnost od alkohola je bolezen, ne sramota. Ampak ko vidiš, da nisi sam — upanje se vrne. Vsekakor priporočam vsem, ki se spopadajo s to težavo. Ne obupajte!

    Reply
  21. Vivod iz zapoya na domy_idMi

    Да уж, соседи уже устали слушать эти крики. Как есть — нужен нормальный вывод из запоя на дому. Ребята работают чисто. Короче говоря, вот нормальный расклад — откапаться на дому [url=https://vyvod-iz-zapoya-na-domu-voronezh-xrt.ru]https://vyvod-iz-zapoya-na-domu-voronezh-xrt.ru[/url] Хватит надеяться на авось. Лучше один раз дернуться, чем труп из квартиры выносить. Рекомендую эту наркологическую клинику.

    Reply
  22. alkoholizem_exkr

    Dolga leta sem se boril sam. Potem pa sem dobil pravi nasvet in vse se je spremenilo. Govorim o ambulantnem zdravljenju alkoholizma pri strokovnjakih, ki res znajo pomagati. Veste, ni lahko, ampak se da premagati. In kar je najpomembneje – ni treba v bolnišnico. Več o tem in o izkušnjah pacientov si lahko preberete neposredno na uradnem viru: zdravljenje alkoholizma [url=zdravljenjealkoholizma.com]zdravljenje alkoholizma[/url]. Meni so resnično pomagali.

    Če nekdo v vaši okolici potrebuje pomoč – ne odlašajte. Vse se da, če hočeš.

    Reply
  23. エロ 下着

    長らく探していた素晴らしいサイトに巡り合えました。デザインのバリエーションが非常に豊富で、各アイテム独自の雰囲気と魅力が溢れています。細部の作り込みが丁寧で、素材感やシルエットの美しさに非常に感動しました。

    様々なコンセプトのアイテムが取り揃えられており、シチュエーションや好みに応じて選択できる幅が広いです。単なるデザインだけでなく、着用時の心地よさもしっかり考慮されている点が非常に好印象です。

    仕立ての良さが安定しており、どの商品を見ても満足できる水準です。オリジナリティ溢れるデザインが多く、他サイトにはない魅力的なラインナップが最大の特徴だと感じます。

    機会があれば継続して利用したいと強く思います。新商品の追加も楽しみで、知り合いにも自信を持っておすすめできる素晴らしいショップです。

    Reply
  24. link tool

    I’m gone to inform my little brother, that he should also go to see this webpage on regular
    basis to take updated from newest gossip.

    Reply
  25. content

    I never imagined that my relationship would collapse. For years I worked hard,
    thinking that everything was fine. Then to my shock I discovered that my wife
    had been seeing another man. What hurt the most
    was that he had a lot of money. My world fell apart.
    The separation was emotionally exhausting. Many evenings felt endless.
    I wondered what I had done wrong. I worried about my finances.
    But eventually I understood the truth: life was not
    over.
    Rather than staying bitter, I became obsessed with financial education. I explored
    modern fintech solutions. Week after week I learned about portfolio diversification,
    blockchain technology, and wealth preservation.
    One of the most useful tools I discovered was Paybis. What impressed me first
    was how simple the platform felt. Handling transactions became far more convenient.

    I regularly use Paybis for crypto-to-fiat transactions.

    The transaction flow is smooth. I can monitor
    my transfers while maintaining control over my assets.

    What really interested me was the technology. Learning about blockchain settlements gave me valuable knowledge.
    I studied market cycles. Over time I became more
    confident with my decisions.
    Then something unexpected happened. As I rebuilt my life, I realized that wealth was not what determined happiness.
    The real problem was respect. No amount
    of money can fix that.
    Things changed when I least expected it.
    I eventually met someone new. She brought fresh energy into my life.
    What mattered most she was encouraging and respectful.

    These days I wake up grateful. The difficult chapter is over.

    I rebuilt my finances, learned valuable lessons, and found peace of mind.

    Looking back, I don’t hold onto bitterness. I value what I learned.
    What felt like the end became a new beginning. My financial journey
    reminds me how much I have grown. The feeling is amazing—the realization that life can improve dramatically
    when you refuse to quit.

    Reply
  26. Vivod iz zapoya na domy_ltoa

    Представьте ситуацию, многие не знают как быть. Ситуация аховая. В этом вопросе очень важно не заниматься самодеятельностью. Я нарыл инфу — вывод из запоя на дому. Ребята реально шарят. Если честно, вся инфа тут — вывод из запоя цены воронеж [url=https://vyvod-iz-zapoya-na-domu-voronezh-kmp.ru]https://vyvod-iz-zapoya-na-domu-voronezh-kmp.ru[/url] Промедление смерти подобно, так как запой убивает почки и сердце. Настоятельно рекомендую.

    Reply
  27. free child sex videos

    Wonderful work! This is the type of information that should be shared across the web.
    Disgrace on the search engines for no longer positioning this post higher!
    Come on over and discuss with my website . Thank you =)

    Reply
  28. หนังรักโรแมนติก

    An outstanding share! I have just forwarded this onto a co-worker
    who was conducting a little homework on this. And he actually ordered me breakfast
    because I discovered it for him… lol. So let me reword this….
    Thank YOU for the meal!! But yeah, thanks for spending time to discuss this subject here on your site.

    Reply
  29. alkoholizem_rnKl

    Že kar nekaj časa spremljam to temo. Ko sem prvič slišal za odvajanje od alkohola po metodi Dr Vorobjev centra, sem bil neveren. Ampak ko sem prebral izkušnje anderen — moje mnenje se je obrnilo. Odvisnost od alkohola je strašna bolezen. In najhuje je, da ljudje se sramujejo prositi za pomoč. Zato vam želim pokazati vse tehnične podrobnosti in uradne informacije, ki so na voljo na tej povezavi: odvisnost od alkohol [url=https://alkoholizma-zdravljenje-si.com]odvisnost od alkohol[/url]. Na tej povezavi so odgovori na vsa vprašanja.

    Meni je ta pristop pomagal. Če vas to zanima — ne odlašajte. Upam, da vam bo koristilo!

    Reply
  30. 포항킹덤안마

    저처럼 출장이 많아서 포항출장마사지를 자주 이용하는데,
    이 글에서 좋은 정보를 확인했어요.

    포항마사지 업체마다 분위기가 차이가 이렇게 큰 줄 몰랐네요.

    다음에 포항힐링마사지를 이용할 때
    이 정보를 활용할게요.
    덕분에 좋은 선택 했어요!
    강력 추천합니다!

    Have a look at my web blog – 포항킹덤안마

    Reply
  31. payment integration services

    Thanks for your marvelous posting! I quite enjoyed reading it,
    you might be a great author.I will ensure that I bookmark your blog
    and definitely will come back down the road. I want to encourage yourself to continue
    your great job, have a nice afternoon!

    Reply
  32. Addie

    Sachlicher Inhalt. Reichlich praktische Inspirationen. Danke für diesen Inhalt.
    Ab jetzt lese ich hier öfter mit.
    Treffend formuliert – der Bereich des Wohnstils ist anspruchsvoll.
    Danke für die klare Erklärung.
    Sehr inspirierend. Ich suche schon nach solchen Informationen genau danach gesucht.
    Danke!

    Also visit my homepage :: Addie

    Reply
  33. google_vignette/

    Simply wish to say your article is as surprising. The clarity for your put up is simply cool
    and i could assume you are knowledgeable in this
    subject. Well along with your permission let me to clutch your RSS feed to keep updated with drawing close post.
    Thank you a million and please carry on the rewarding work.

    Reply

Leave a Reply

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