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

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

  1. Gentle yoga

    Hmm is anyone else encountering problems with the pictures on this blog loading?

    I’m trying to figure out if its a problem on my end or if it’s the blog.
    Any feedback would be greatly appreciated.

    Reply
  2. DELICUAN WD TIDAK MAMPU BAYAR

    I was recommended this web site by my cousin. I’m no
    longer positive whether or not this submit is written via him
    as no one else recognise such exact approximately
    my problem. You are incredible! Thank you!

    Reply
  3. xnxx

    Hello there I am so delighted I found your webpage, I really found you by error, while I was browsing
    on Digg for something else, Nonetheless I am here now and would just like to say kudos for a
    fantastic post and a all round enjoyable blog (I also love the theme/design), I
    don’t have time to read it all at the moment but I have bookmarked it and also included your RSS feeds, so when I
    have time I will be back to read a great deal more, Please do keep up
    the great jo.

    Reply
  4. waterfront villas Dubai

    Dubai is the same of the universe’s top real manor investment destinations,
    gift dues advantages, strong rental yields, and премиум lifestyle
    opportunities. From self-indulgence villas to high-rise apartments, buying
    acreage in Dubai provides excellent passive for the sake of both return and long-term money growth.

    Reply
  5. my blog

    I think this is one of the most important info for me. And i’m glad reading your article.
    But should remark on few general things, The website style is perfect, the articles is really nice : D.

    Good job, cheers

    Reply
  6. information

    Simply desire to say your article is as astounding. The clearness in your post is simply nice and i could assume you’re an expert on this subject.
    Well with your permission let me to grab your feed to keep up to date with forthcoming post.

    Thanks a million and please carry on the rewarding work.

    Reply
  7. learn more

    Hello! Quick question that’s completely off topic. Do you know how to make your site mobile friendly?
    My weblog looks weird when browsing from my iphone4. I’m trying to find a template or plugin that might be able to correct this
    issue. If you have any recommendations, please share. Cheers!

    Reply
  8. ۵. سرعت تراکنش بالاتر

    سلام، خودم امروز هنگام گشتن
    آنلاین به این سایت آشنا شدم و بدون اغراق خیلی خوشماومد.
    محتواش کاربردی بود و خیلی کم پیش
    میاد همچین منبعی پیدا کنم.

    احساس می‌کنم برای کاربرای زیادی ارزش دیدن داره.

    برای کسایی که دنبال محتوای مفید هستن پیشنهاد می‌کنم حتما یه نگاهی بندازن.
    در مجموع خوشم اومد و احتمالا باز هم سر می‌زنم

    بطور خلاصه

    برای اونایی که می‌خوان وارد بشن

    شرط بندی

    هستن

    این برند

    می‌تونه تبدیل بشه

    گزینه ارزشمندی باشه

    از سوی دیگر

    برندهای شناخته‌شده‌ای مثل

    پلتفرم enfejaronlіne

    و

    ѕibbet محبوب

    نقش مهمی دارن

    خلاصه اینکه

    بد نبود

    و

    قطعا دوباره

    میام دوباره

    .

    Feel free to visit my webpage :: ۵. سرعت تراکنش بالاتر

    Reply
  9. platform review

    Howdy! This is my first comment here so I just wanted
    to give a quick shout out and tell you I genuinely enjoy reading through your articles.
    Can you recommend any other blogs/websites/forums that go over
    the same subjects? Appreciate it!

    Reply
  10. ngentod

    Aw, this was a very nice post. Finding the time and actual effort to produce a great article… but what can I
    say… I put things off a lot and don’t manage to get anything done.

    Reply
  11. aiagentdev.help

    This blog post was surprisingly informative I’ve read
    in recent months.
    Your breakdown of modern AI automation trends provided a lot of clarity.

    The strongest aspect of this article is that you don’t
    overcomplicate the subject.
    It makes the information easier to trust.

    Looking forward to your future posts.
    Your blog is becoming a valuable resource for anyone
    interested in AI automation.

    Reply
  12. Jewel

    Interessanter Text. Reichlich konkrete Hinweise.
    Grüße für den Beitrag. Ich warte auf mehr.
    Du hast recht – die Frage des Wohnstils kann nicht einfach.
    Endlich mal Klartext.
    Aufrichtig praxisnah. Ich suche schon nach solchen Informationen seit Wochen gesucht.
    Super Arbeit!

    my webpage :: Jewel

    Reply
  13. pornoterbaru

    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses. But he’s tryiong none the less.
    I’ve been using Movable-type on a number of websites for about
    a year and am nervous about switching to another platform.
    I have heard good things about blogengine.net. Is there a way I can import all my wordpress posts into it?
    Any kind of help would be really appreciated!

    Reply
  14. Fatiha Travel

    Nice post atas informasi yang sangat menarik ini. Memang benar bahwa kenyamanan dalam
    perjalanan sangat menentukan kualitas liburan kita. Bagi teman-teman yang sedang mencari referensi perjalanan atau sewa armada,
    silakan cek di **Fatiha Travel**. Pelayanannya sudah terbukti berkualitas untuk
    berbagai destinasi. Sukses terus untuk blognya! Fatiha Travel Official

    Reply
  15. رقبای سرسخت مایک

    در آخر کار

    برای اون دسته که

    بازی‌های شرطی

    علاقه دارن

    این پلتفرم شرطی

    کاملا میتونه

    مناسب کاربران باشه

    یه نکته مهم اینه که

    اسم‌هایی مثل

    enfejaronline شناخته شده

    و

    sibbet حرفه‌ای

    تونستن اعتماد جلب کنن

    در جمع‌بندی

    دلنشین بود

    و

    به زودی

    مراجعه مجدد دارم

    Here іs my homeρage; رقبای سرسخت مایک

    Reply
  16. 詳細はこちら

    I am no longer positive the place you are getting your information, but great
    topic. I needs to spend some time learning much more or working
    out more. Thank you for fantastic info I used to be looking for this info for my mission.

    Reply
  17. Alan

    Hey! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing
    a few months of hard work due to no backup. Do you have any solutions to stop hackers?

    Reply
  18. macaugg

    Spot on with this write-up, I absolutely believe that this amazing
    site needs far more attention. I’ll probably
    be back again to see more, thanks for the info!

    Reply
  19. Jamika

    Bachem is a leading, innovation-driven business specializing in the growth and manufacture of peptides and oligonucleotides.

    Reply
  20. تعمیر لباسشویی بکو

    I believe what you composed was actually very logical.
    But, what about this? suppose you added a little content?

    I mean, I don’t want to tell you how to run your website, but
    what if you added a headline that grabbed a person’s attention? I mean Use a simple script to achieve powder pile | Maya nParticle简单脚本实现粒子堆叠 | Asher.GG is kinda
    vanilla. You should peek at Yahoo’s home page and see
    how they create article headlines to get viewers interested.
    You might add a related video or a picture or two to grab
    people excited about everything’ve written. Just my opinion, it
    could make your posts a little bit more interesting.

    Reply
  21. Judith

    Wertvoller Artikel. Jede Menge wertvolle Informationen. Danke
    für den Beitrag. Ich warte auf mehr.
    Du hast recht – die Sache der Raumgestaltung wird oft schwierig.
    Danke für die klare Erklärung.
    Aufrichtig inspirierend. Ich suche schon nach ähnlichen Tipps
    seit einiger Zeit gesucht. Danke!

    Feel free to surf to my web-site Judith

    Reply
  22. review

    Hey! I realize this is kind of off-topic but I had to ask.

    Does building a well-established blog like yours require a lot
    of work? I am brand new to blogging however I
    do write in my diary daily. I’d like to start a blog so I will
    be able to share my own experience and feelings
    online. Please let me know if you have any recommendations or tips for brand
    new aspiring bloggers. Thankyou!

    Reply
  23. Кракен сайт Кракен надежный источник *)(* ๑˘˘๑говли в даркнете

    Почему пользователи выбирают площадку KRAKEN?

    Маркетплейс KRAKEN заслужил доверие многочисленной аудитории благодаря сочетанию ключевых факторов.

    Во-первых, это широкий и разнообразный ассортимент, представленный
    сотнями продавцов. Во-вторых, интуитивно понятный интерфейс KRAKEN, который упрощает навигацию, поиск
    товаров и управление заказами даже
    для новых пользователей. В-третьих,
    продуманная система безопасных транзакций,
    включающая механизмы разрешения споров (диспутов)
    и возможность использования условного депонирования, что минимизирует риски для обеих сторон сделки.
    На KRAKEN функциональность сочетается с внимательным отношением к
    безопасности клиентов, что делает процесс покупок
    более предсказуемым, защищенным и, как
    следствие, популярным среди пользователей, ценящих анонимность и надежность.

    Reply
  24. نمایندگی تعمیرات جنرال

    Right here is the perfect web site for everyone who would like to understand this topic.

    You know a whole lot its almost hard to argue with you (not that I really
    would want to…HaHa). You certainly put a new spin on a subject which has been written about
    for years. Excellent stuff, just excellent!

    Reply
  25. review

    Hello, Neat post. There’s an issue together with your web site in internet explorer, would check this?

    IE still is the marketplace chief and a huge component of folks will miss your fantastic writing because of this problem.

    Reply
  26. guardium инструкция

    Guardium
    Капсулы Guardium представляют собой
    инновационное средство нового поколения для борьбы с паразитарными infestations.

    В наше время мир полон скрытых угроз, способных
    негативно сказаться на здоровье человека — к
    ним относятся пища, вода, воздух и даже предметы в нашем быту.
    Паразиты занимают значительное место среди факторов, вызывающих такие проблемы,
    как хроническая усталость, дерматологические заболевания, снижение иммунитета и расстройства
    пищеварения. Однако наука предлагает ответ на эту проблему — капсулы Guardium.
    Этот современный продукт был разработан для
    глубокого и безопасного очищения организма,
    не причиняя вреда полезной микрофлоре и печени.guardium инструкция

    Reply
  27. xem sex miễn phí không che

    Hello there! Quick question that’s completely off topic.

    Do you know how to make your site mobile friendly?
    My web site looks weird when viewing from my iphone4.
    I’m trying to find a theme or plugin that might be able to resolve this issue.

    If you have any recommendations, please share. Thank you!

    Reply
  28. pakistan-super-league.com

    I don’t comment often, but after reading this I couldn’t resist
    writing. The engaging way you cover the topic makes a real difference compared to
    other content.

    The most remarkable thing is that you make complex topics accessible.
    You raised points that I’ll be thinking
    about for a long time.

    I’m following from today and can’t wait to explore more!
    I’ve already shared the article with three friends who I know will
    love it.

    Reply
  29. review

    Hey this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you
    have to manually code with HTML. I’m starting a blog soon but have
    no coding knowledge so I wanted to get guidance from someone with experience.
    Any help would be enormously appreciated!

    Reply
  30. Uk88

    Greate post. Keep writing such kind of info on your page.
    Im really impressed by your site.
    Hello there, You’ve performed an excellent
    job. I’ll certainly digg it and personally suggest to my friends.
    I’m sure they will be benefited from this site.

    Reply
  31. ラブドール 最新

    記事の内容がとても分かりやすくて 、大変勉強になりました。 日常のちょっとした場面で 同じような悩みを抱えていたので、 細かい解説が 非常に役立ちます。今回紹介されている方法を 早速試してみたいと思います。今後もこういった有益な情報を
    たくさん投稿していただけると嬉しいです。

    Reply
  32. Кракен купить - Выбор продавца для кракен купить: критерии надежности и репутации

    Почему пользователи выбирают площадку KRAKEN?

    Маркетплейс KRAKEN заслужил доверие многочисленной аудитории благодаря сочетанию ключевых факторов.
    Во-первых, это широкий и разнообразный ассортимент, представленный сотнями продавцов.
    Во-вторых, интуитивно понятный интерфейс KRAKEN, который упрощает навигацию, поиск товаров и управление заказами даже для новых пользователей.
    В-третьих, продуманная система безопасных транзакций,
    включающая механизмы разрешения споров (диспутов) и
    возможность использования условного
    депонирования, что минимизирует риски для обеих сторон
    сделки. На KRAKEN функциональность сочетается с внимательным отношением к безопасности клиентов, что делает
    процесс покупок более предсказуемым, защищенным и,
    как следствие, популярным среди пользователей, ценящих
    анонимность и надежность.

    Reply
  33. A片

    Hi there exceptional website! Does running a blog such as this
    require a lot of work? I have virtually no understanding of programming but I was hoping to start my own blog in the near future.
    Anyhow, should you have any suggestions or tips for new blog owners please share.
    I know this is off subject but I just needed to ask. Thanks!

    Look into my website; A片

    Reply

Leave a Reply

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