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

  1. betvisa

    What i do not understood is in reality how you’re not actually a lot more well-favored
    than you may be now. You’re very intelligent. You
    already know thus significantly on the subject of this matter, made me
    personally imagine it from numerous varied angles. Its like men and women aren’t involved unless it is one thing to
    accomplish with Girl gaga! Your personal stuffs great.
    At all times deal with it up!

    Reply
  2. Narkologicheskii stacionar_uvpr

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

    Reply
  3. boost server ranking

    Hi there, I found your website by means of Google while looking for a comparable matter,
    your website got here up, it seems great. I have bookmarked it
    in my google bookmarks.
    Hello there, simply changed into alert to your weblog via Google, and found that it
    is truly informative. I am going to watch out for brussels.
    I will be grateful if you happen to proceed this in future.
    Lots of other people will be benefited from your writing.

    Cheers!

    Reply
  4. aviator-demo

    Hi! I’m at work browsing your blog from my new apple iphone!

    Just wanted to say I love reading your blog and look forward to all your posts!

    Carry on the great work!

    Reply
  5. international betting sites in kenya

    A person essentially help to make significantly posts I’d state.
    That is the very first time I frequented your web page
    and thus far? I surprised with the research you made to create this particular post extraordinary.
    Fantastic process!

    Reply
  6. Narkologicheskii stacionar_klpa

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

    Reply
  7. web page

    Hi there! This post couldn’t be written any better!
    Reading this post reminds me of my old room mate!
    He always kept talking about this. I will forward this write-up to him.

    Pretty sure he will have a good read. Thank you for sharing!

    Reply
  8. Narkologicheskii stacionar_hoEt

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

    Reply
  9. health11

    Thanks for this helpful article! I’ve been looking for natural ways to support
    balanced daily wellness and my overall wellness and this gave me some useful ideas to think about.
    Appreciate you sharing it.

    Reply
  10. Narkologicheskii stacionar_fnSl

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

    Reply
  11. Narkologicheskii stacionar_xkSt

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

    Reply
  12. primary maths tuition

    OMT’s exclusive educational program рresents enjoyable challenges
    tһat mirror examination inquiries, stimulating love fоr math and the motivation to execute remarkably.

    Dive іnto ѕelf-paced math mastery ԝith OMT’s 12-month e-learning courses, tօtal with practice worksheets annd
    recorded sessions fоr comprehensive revision.

    Singapore’ѕ ԝorld-renowned mathematics curriculum highlights conceptual understanding օveг simple calculation, mɑking math tuition іmportant foг students to comprehend deep concepts аnd master national tests ⅼike PSLE and O-Levels.

    Wіth PSLE math concerns frequently involving real-ѡorld applications, tuition supplies targeted practice t᧐ establish
    іmportant believing skills vital fⲟr hіgh scores.

    Connecting mathematics ideas to real-ѡorld situations
    throսgh tuition strengthens understanding, makinng О Level
    application-based concerns mогe friendly.

    Math tuition аt tһe junior college degree highlights theoretical clearness оver memorizing memorization, vital fⲟr tаking օn application-based A Level questions.

    OMT sets іtself apɑrt ԝith an educational program tһat enhances MOE syllabus
    tһrough joint on-lіne discussion forums fߋr ցoing over exclusive mathematics difficulties.

    Tape-recorded webinars provide deep dives lah, equipping уou ѡith innovative abilities for superior math marks.

    Math tuition helps Singapore trainees overcome typical mistakes іn computations, causing fewer negligent
    errors іn examinations.

    Μy webpage :: primary maths tuition

    Reply
  13. VertAid

    Thanks for this insightful article! I’ve been looking for natural ways to support my overall wellness and
    this gave me some useful ideas. VertAid is something I’ve been reading about lately.
    Appreciate the info. https://us-vertaid.com/

    Reply
  14. Narkologicheskii stacionar_voer

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

    Reply
  15. Narkologicheskii stacionar_cbel

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

    Reply
  16. budaya4d

    I’ve been exploring for a little bit for any high
    quality articles or weblog posts in this sort of house . Exploring in Yahoo I eventually stumbled upon this website.
    Studying this info So i’m satisfied to exhibit that I’ve
    a very excellent uncanny feeling I came upon just what I needed.
    I such a lot indubitably will make sure to do not forget this website and give it a look regularly.

    Reply
  17. Narkologicheskii stacionar_ijPt

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

    Reply
  18. check my site

    I like the helpful information you provide in your articles.
    I’ll bookmark your weblog and check again here frequently.

    I am quite certain I’ll learn a lot of new stuff right here!
    Best of luck for the next!

    Reply
  19. Anneliese

    Do you mind if I quote a few of your posts as long as I provide credit
    and sources back to your weblog? My blog is in the exact same area of interest as yours
    and my users would really benefit from a lot
    of the information you provide here. Please let me know if this ok with
    you. Thanks!

    Reply
  20. Narkologicheskii stacionar_jhpi

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

    Reply
  21. 비아그라

    Wow, amazing weblog structure! How lengthy have you been running a blog for?
    you make running a blog look easy. The whole glance
    of your web site is wonderful, as neatly as the content!

    Reply
  22. Narkologicheskii stacionar_laSl

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

    Reply
  23. Narkologicheskii stacionar_baSt

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

    Reply
  24. Narkologicheskii stacionar_nwEt

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

    Reply
  25. Narkologicheskii stacionar_ckpr

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

    Reply
  26. TheOption 入出金方法

    TheOption デモトレード – 本番前に必ず活用しよう.
    デモ口座は無料で何度でも使える. 初心者でも直感的に操作可能.
    負けてもダメージなし
    暗号資産 バイナリー – ビットコインやイーサリアムで取引.
    暗号資産のチャート分析が重要.
    ザオプションでも暗号資産ペアが取引可能.
    ボラティリティが高い分チャンスも大きい
    TheOption 入出金方法 – クレジットカード・銀行送金・電子ウォレット.

    初回出金は特に審査が厳しめ.
    スムーズな入出金が好評. 出金拒否を避けるために条件を把握
    ザオプション 評判 – 使いやすいアプリが評価を集めている.
    ボーナス条件が明確で分かりやすい.
    ザオプションは総合的に信頼できる業者. デモで確かめてから本登録

    http://www.krglive.com

    Reply
  27. asteroidsathome.net

    Truly, I had no idea how transformative a genuine Tantric Massage session could be before I actually booked one last month after ages searching for a reputable Tantric Massage Practitioner locally, and honestly, the Tantra Massage Therapy totally changed my perspective in a manner that regular massage never could, so if you’re on the fence, please consider booking a experienced Tantric Massage Practitioner or maybe signing up for a Tantra Massage Therapy program to better understand what this practice truly offers for overall holistic sensory healing [https://asteroidsathome.net/boinc/view_profile.php?userid=1261238].

    Reply
  28. Narkologicheskii stacionar_erer

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

    Reply
  29. Narkologicheskii stacionar_elPt

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

    Reply

Leave a Reply

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