io_export_ogreDotScene.py 293 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339
  1. # Copyright (C) 2010 Brett Hartshorn
  2. #
  3. # This library is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU Lesser General Public
  5. # License as published by the Free Software Foundation; either
  6. # version 2.1 of the License, or (at your option) any later version.
  7. #
  8. # This library is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. # Lesser General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU Lesser General Public
  14. # License along with this library; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. VERSION = '0.5.8'
  17. '''
  18. CHANGELOG
  19. 0.5.8
  20. * Added silent auto update checks if blender2ogre was installed using
  21. the .exe installer. This will keep people up to date when new versions are out.
  22. * Fix tracker issue 48: Needs to check if outputting to /tmp or
  23. ~/.wine/drive_c/tmp on Linux. Thanks to vax456 for providing the patch,
  24. added him to contributors. Preview mesh's are now placed under /tmp
  25. on Linux systems if the OgreMeshy executable ends with .exe
  26. * Fix tracker issue 46: add operationtype to <submesh>
  27. * Implement a modal dialog that reports if material names have invalid
  28. characters and cant be saved on disk. This small popup will show until
  29. user presses left or right mouse (anywhere).
  30. * Fix tracker issue 44: XML Attributes not properly escaped in .scene file
  31. * Implemented reading OgreXmlConverter path from windows registry.
  32. The .exe installer will ship with certain tools so we can stop guessing
  33. and making the user install tools separately and setting up paths.
  34. * Fix bug that .mesh files were not generated while doing a .txml export.
  35. This was result of the late 2.63 mods that forgot to update object
  36. facecount before determining if mesh should be exported.
  37. * Fix bug that changed settings in the export dialog were forgotten when you
  38. re-exported without closing blender. Now settings should persist always
  39. from the last export. They are also stored to disk so the same settings
  40. are in use when if you restart Blender.
  41. * Fix bug that once you did a export, the next time the export location was
  42. forgotten. Now on sequential exports, the last export path is remembered in
  43. the export dialog.
  44. * Remove all local:// from asset refs and make them relative in .txml export.
  45. Having relative refs is the best for local preview and importing the txml
  46. to existing scenes.
  47. * Make .material generate what version of this plugins was used to generate
  48. the material file. Will be helpful in production to catch things.
  49. Added pretty printing line endings so the raw .material data is easier to read.
  50. * Improve console logging for the export stages. Run Blender from
  51. cmd prompt to see this information.
  52. * Clean/fix documentation in code for future development
  53. * Add todo to code for future development
  54. * Restructure/move code for easier readability
  55. * Remove extra white spaces and convert tabs to space
  56. 0.5.7
  57. * Update to Blender 2.6.3.
  58. * Fixed xz-y Skeleton rotation (again)
  59. * Added additional Keyframe at the end of each animation to prevent
  60. ogre from interpolating back to the start
  61. * Added option to ignore non-deformable bones
  62. * Added option to export nla-strips independently from each other
  63. TODO
  64. * Remove this section and integrate below with code :)
  65. * Fix terrain collision offset bug
  66. * Add realtime transform (rotation is missing)
  67. * Fix camera rotated -90 ogre-dot-scene
  68. * Set description field for all pyRNA
  69. '''
  70. bl_info = {
  71. "name": "OGRE Exporter (.scene, .mesh, .skeleton) and RealXtend (.txml)",
  72. "author": "Brett, S.Rombauts, F00bar, Waruck, Mind Calamity, Mr.Magne, Jonne Nauha, vax456",
  73. "version": (0, 5, 8),
  74. "blender": (2, 6, 3),
  75. "location": "File > Export...",
  76. "description": "Export to Ogre xml and binary formats",
  77. "wiki_url": "http://code.google.com/p/blender2ogre/w/list",
  78. "tracker_url": "http://code.google.com/p/blender2ogre/issues/list",
  79. "category": "Import-Export"
  80. }
  81. ## Public API
  82. ## Search for "Public API" to find more
  83. UI_CLASSES = []
  84. def UI(cls):
  85. ''' Toggles the Ogre interface panels '''
  86. if cls not in UI_CLASSES:
  87. UI_CLASSES.append(cls)
  88. return cls
  89. def hide_user_interface():
  90. for cls in UI_CLASSES:
  91. bpy.utils.unregister_class( cls )
  92. def uid(ob):
  93. if ob.uid == 0:
  94. high = 0
  95. multires = 0
  96. for o in bpy.data.objects:
  97. if o.uid > high: high = o.uid
  98. if o.use_multires_lod: multires += 1
  99. high += 1 + (multires*10)
  100. if high < 100: high = 100 # start at 100
  101. ob.uid = high
  102. return ob.uid
  103. ## Imports
  104. import os, sys, time, array, ctypes, math
  105. try:
  106. # Inside blender
  107. import bpy, mathutils
  108. from bpy.props import *
  109. except ImportError:
  110. # If we end up here we are outside blender (compile optional C module)
  111. assert __name__ == '__main__'
  112. print('Trying to compile Rpython C-library')
  113. assert sys.version_info.major == 2 # rpython only works from Python2
  114. print('...searching for rpythonic...')
  115. sys.path.append('../rpythonic')
  116. import rpythonic
  117. rpythonic.set_pypy_root( '../pypy' )
  118. import pypy.rpython.lltypesystem.rffi as rffi
  119. from pypy.rlib import streamio
  120. rpy = rpythonic.RPython( 'blender2ogre' )
  121. @rpy.bind(
  122. path=str,
  123. facesAddr=int,
  124. facesSmoothAddr=int,
  125. facesMatAddr=int,
  126. vertsPosAddr=int,
  127. vertsNorAddr=int,
  128. numFaces=int,
  129. numVerts=int,
  130. materialNames=str, # [str] is too tricky to convert py-list to rpy-list
  131. )
  132. def dotmesh( path, facesAddr, facesSmoothAddr, facesMatAddr, vertsPosAddr, vertsNorAddr, numFaces, numVerts, materialNames ):
  133. print('PATH----------------', path)
  134. materials = []
  135. for matname in materialNames.split(';'):
  136. print( 'Material Name: %s' %matname )
  137. materials.append( matname )
  138. file = streamio.open_file_as_stream( path, 'w')
  139. faces = rffi.cast( rffi.UINTP, facesAddr ) # face vertex indices
  140. facesSmooth = rffi.cast( rffi.CCHARP, facesSmoothAddr )
  141. facesMat = rffi.cast( rffi.USHORTP, facesMatAddr )
  142. vertsPos = rffi.cast( rffi.FLOATP, vertsPosAddr )
  143. vertsNor = rffi.cast( rffi.FLOATP, vertsNorAddr )
  144. VB = [
  145. '<sharedgeometry>',
  146. '<vertexbuffer positions="true" normals="true">'
  147. ]
  148. fastlookup = {}
  149. ogre_vert_index = 0
  150. triangles = []
  151. for fidx in range( numFaces ):
  152. smooth = ord( facesSmooth[ fidx ] ) # ctypes.c_bool > char > int
  153. matidx = facesMat[ fidx ]
  154. i = fidx*4
  155. ai = faces[ i ]; bi = faces[ i+1 ]
  156. ci = faces[ i+2 ]; di = faces[ i+3 ]
  157. triangle = []
  158. for J in [ai, bi, ci]:
  159. i = J*3
  160. x = rffi.cast( rffi.DOUBLE, vertsPos[ i ] )
  161. y = rffi.cast( rffi.DOUBLE, vertsPos[ i+1 ] )
  162. z = rffi.cast( rffi.DOUBLE, vertsPos[ i+2 ] )
  163. pos = (x,y,z)
  164. #if smooth:
  165. x = rffi.cast( rffi.DOUBLE, vertsNor[ i ] )
  166. y = rffi.cast( rffi.DOUBLE, vertsNor[ i+1 ] )
  167. z = rffi.cast( rffi.DOUBLE, vertsNor[ i+2 ] )
  168. nor = (x,y,z)
  169. SIG = (pos,nor)#, matidx)
  170. skip = False
  171. if J in fastlookup:
  172. for otherSIG in fastlookup[ J ]:
  173. if SIG == otherSIG:
  174. triangle.append( fastlookup[J][otherSIG] )
  175. skip = True
  176. break
  177. if not skip:
  178. triangle.append( ogre_vert_index )
  179. fastlookup[ J ][ SIG ] = ogre_vert_index
  180. else:
  181. triangle.append( ogre_vert_index )
  182. fastlookup[ J ] = { SIG : ogre_vert_index }
  183. if skip: continue
  184. xml = [
  185. '<vertex>',
  186. '<position x="%s" y="%s" z="%s" />' %pos, # funny that tuple is valid here
  187. '<normal x="%s" y="%s" z="%s" />' %nor,
  188. '</vertex>'
  189. ]
  190. VB.append( '\n'.join(xml) )
  191. ogre_vert_index += 1
  192. triangles.append( triangle )
  193. VB.append( '</vertexbuffer>' )
  194. VB.append( '</sharedgeometry>' )
  195. file.write( '\n'.join(VB) )
  196. del VB # free memory
  197. SMS = ['<submeshes>']
  198. #for matidx, matname in ...:
  199. SM = [
  200. '<submesh usesharedvertices="true" use32bitindexes="true" material="%s" operationtype="triangle_list">' % 'somemat',
  201. '<faces count="%s">' %'100',
  202. ]
  203. for tri in triangles:
  204. #x,y,z = tri # rpython bug, when in a new 'block' need to unpack/repack tuple
  205. #s = '<face v1="%s" v2="%s" v3="%s" />' %(x,y,z)
  206. assert isinstance(tri,tuple) #and len(tri)==3 # this also works
  207. s = '<face v1="%s" v2="%s" v3="%s" />' %tri # but tuple is not valid here
  208. SM.append( s )
  209. SM.append( '</faces>' )
  210. SM.append( '</submesh>' )
  211. file.write( '\n'.join(SM) )
  212. file.close()
  213. rpy.cache(refresh=1)
  214. sys.exit('OK: module compiled and cached')
  215. ## More imports now that Blender is imported
  216. import hashlib, getpass, tempfile, configparser, subprocess, pickle
  217. from xml.sax.saxutils import XMLGenerator, quoteattr
  218. class CMesh(object):
  219. def __init__(self, data):
  220. self.numVerts = N = len( data.vertices )
  221. self.numFaces = Nfaces = len(data.tessfaces)
  222. self.vertex_positions = (ctypes.c_float * (N * 3))()
  223. data.vertices.foreach_get( 'co', self.vertex_positions )
  224. v = self.vertex_positions
  225. self.vertex_normals = (ctypes.c_float * (N * 3))()
  226. data.vertices.foreach_get( 'normal', self.vertex_normals )
  227. self.faces = (ctypes.c_uint * (Nfaces * 4))()
  228. data.tessfaces.foreach_get( 'vertices_raw', self.faces )
  229. self.faces_normals = (ctypes.c_float * (Nfaces * 3))()
  230. data.tessfaces.foreach_get( 'normal', self.faces_normals )
  231. self.faces_smooth = (ctypes.c_bool * Nfaces)()
  232. data.tessfaces.foreach_get( 'use_smooth', self.faces_smooth )
  233. self.faces_material_index = (ctypes.c_ushort * Nfaces)()
  234. data.tessfaces.foreach_get( 'material_index', self.faces_material_index )
  235. self.vertex_colors = []
  236. if len( data.vertex_colors ):
  237. vc = data.vertex_colors[0]
  238. n = len(vc.data)
  239. # no colors_raw !!?
  240. self.vcolors1 = (ctypes.c_float * (n * 3))() # face1
  241. vc.data.foreach_get( 'color1', self.vcolors1 )
  242. self.vertex_colors.append( self.vcolors1 )
  243. self.vcolors2 = (ctypes.c_float * (n * 3))() # face2
  244. vc.data.foreach_get( 'color2', self.vcolors2 )
  245. self.vertex_colors.append( self.vcolors2 )
  246. self.vcolors3 = (ctypes.c_float * (n * 3))() # face3
  247. vc.data.foreach_get( 'color3', self.vcolors3 )
  248. self.vertex_colors.append( self.vcolors3 )
  249. self.vcolors4 = (ctypes.c_float * (n * 3))() # face4
  250. vc.data.foreach_get( 'color4', self.vcolors4 )
  251. self.vertex_colors.append( self.vcolors4 )
  252. self.uv_textures = []
  253. if data.uv_textures.active:
  254. for layer in data.uv_textures:
  255. n = len(layer.data) * 8
  256. a = (ctypes.c_float * n)()
  257. layer.data.foreach_get( 'uv_raw', a ) # 4 faces
  258. self.uv_textures.append( a )
  259. def save( blenderobject, path ):
  260. cmesh = Mesh( blenderobject.data )
  261. start = time.time()
  262. dotmesh(
  263. path,
  264. ctypes.addressof( cmesh.faces ),
  265. ctypes.addressof( cmesh.faces_smooth ),
  266. ctypes.addressof( cmesh.faces_material_index ),
  267. ctypes.addressof( cmesh.vertex_positions ),
  268. ctypes.addressof( cmesh.vertex_normals ),
  269. cmesh.numFaces,
  270. cmesh.numVerts,
  271. )
  272. print('Mesh dumped in %s seconds' % (time.time()-start))
  273. ## Make sure we can import from same directory
  274. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  275. if SCRIPT_DIR not in sys.path:
  276. sys.path.append( SCRIPT_DIR )
  277. ## Avatar
  278. bpy.types.Object.use_avatar = BoolProperty(
  279. name='enable avatar',
  280. description='enables EC_Avatar',
  281. default=False)
  282. bpy.types.Object.avatar_reference = StringProperty(
  283. name='avatar reference',
  284. description='sets avatar reference URL',
  285. maxlen=128,
  286. default='')
  287. BoolProperty( name='enable avatar', description='enables EC_Avatar', default=False) # todo: is this used?
  288. # Tundra IDs
  289. bpy.types.Object.uid = IntProperty(
  290. name="unique ID",
  291. description="unique ID for Tundra",
  292. default=0, min=0, max=2**14)
  293. # Rendering
  294. bpy.types.Object.use_draw_distance = BoolProperty(
  295. name='enable draw distance',
  296. description='use LOD draw distance',
  297. default=False)
  298. bpy.types.Object.draw_distance = FloatProperty(
  299. name='draw distance',
  300. description='distance at which to begin drawing object',
  301. default=0.0, min=0.0, max=10000.0)
  302. bpy.types.Object.cast_shadows = BoolProperty(
  303. name='cast shadows',
  304. description='cast shadows',
  305. default=False)
  306. bpy.types.Object.use_multires_lod = BoolProperty(
  307. name='Enable Multires LOD',
  308. description='enables multires LOD',
  309. default=False)
  310. bpy.types.Object.multires_lod_range = FloatProperty(
  311. name='multires LOD range',
  312. description='far distance at which multires is set to base level',
  313. default=30.0, min=0.0, max=10000.0)
  314. ## Physics
  315. _physics_modes = [
  316. ('NONE', 'NONE', 'no physics'),
  317. ('RIGID_BODY', 'RIGID_BODY', 'rigid body'),
  318. ('SOFT_BODY', 'SOFT_BODY', 'soft body'),
  319. ]
  320. _collision_modes = [
  321. ('NONE', 'NONE', 'no collision'),
  322. ('PRIMITIVE', 'PRIMITIVE', 'primitive collision type'),
  323. ('MESH', 'MESH', 'triangle-mesh or convex-hull collision type'),
  324. ('DECIMATED', 'DECIMATED', 'auto-decimated collision type'),
  325. ('COMPOUND', 'COMPOUND', 'children primitive compound collision type'),
  326. ('TERRAIN', 'TERRAIN', 'terrain (height map) collision type'),
  327. ]
  328. bpy.types.Object.physics_mode = EnumProperty(
  329. items = _physics_modes,
  330. name = 'physics mode',
  331. description='physics mode',
  332. default='NONE')
  333. bpy.types.Object.physics_friction = FloatProperty(
  334. name='Simple Friction',
  335. description='physics friction',
  336. default=0.1, min=0.0, max=1.0)
  337. bpy.types.Object.physics_bounce = FloatProperty(
  338. name='Simple Bounce',
  339. description='physics bounce',
  340. default=0.01, min=0.0, max=1.0)
  341. bpy.types.Object.collision_terrain_x_steps = IntProperty(
  342. name="Ogre Terrain: x samples",
  343. description="resolution in X of height map",
  344. default=64, min=4, max=8192)
  345. bpy.types.Object.collision_terrain_y_steps = IntProperty(
  346. name="Ogre Terrain: y samples",
  347. description="resolution in Y of height map",
  348. default=64, min=4, max=8192)
  349. bpy.types.Object.collision_mode = EnumProperty(
  350. items = _collision_modes,
  351. name = 'primary collision mode',
  352. description='collision mode',
  353. default='NONE')
  354. bpy.types.Object.subcollision = BoolProperty(
  355. name="collision compound",
  356. description="member of a collision compound",
  357. default=False)
  358. ## Sound
  359. bpy.types.Speaker.play_on_load = BoolProperty(
  360. name='play on load',
  361. default=False)
  362. bpy.types.Speaker.loop = BoolProperty(
  363. name='loop sound',
  364. default=False)
  365. bpy.types.Speaker.use_spatial = BoolProperty(
  366. name='3D spatial sound',
  367. default=True)
  368. ## ImageMagick
  369. _IMAGE_FORMATS = [
  370. ('NONE','NONE', 'do not convert image'),
  371. ('bmp', 'bmp', 'bitmap format'),
  372. ('jpg', 'jpg', 'jpeg format'),
  373. ('gif', 'gif', 'gif format'),
  374. ('png', 'png', 'png format'),
  375. ('tga', 'tga', 'targa format'),
  376. ('dds', 'dds', 'nvidia dds format'),
  377. ]
  378. bpy.types.Image.use_convert_format = BoolProperty(
  379. name='use convert format',
  380. default=False
  381. )
  382. bpy.types.Image.convert_format = EnumProperty(
  383. name='convert to format',
  384. description='converts to image format using imagemagick',
  385. items=_IMAGE_FORMATS,
  386. default='NONE')
  387. bpy.types.Image.jpeg_quality = IntProperty(
  388. name="jpeg quality",
  389. description="quality of jpeg",
  390. default=80, min=0, max=100)
  391. bpy.types.Image.use_color_quantize = BoolProperty(
  392. name='use color quantize',
  393. default=False)
  394. bpy.types.Image.use_color_quantize_dither = BoolProperty(
  395. name='use color quantize dither',
  396. default=True)
  397. bpy.types.Image.color_quantize = IntProperty(
  398. name="color quantize",
  399. description="reduce to N colors (requires ImageMagick)",
  400. default=32, min=2, max=256)
  401. bpy.types.Image.use_resize_half = BoolProperty(
  402. name='resize by 1/2',
  403. default=False)
  404. bpy.types.Image.use_resize_absolute = BoolProperty(
  405. name='force image resize',
  406. default=False)
  407. bpy.types.Image.resize_x = IntProperty(
  408. name='resize X',
  409. description='only if image is larger than defined, use ImageMagick to resize it down',
  410. default=256, min=2, max=4096)
  411. bpy.types.Image.resize_y = IntProperty(
  412. name='resize Y',
  413. description='only if image is larger than defined, use ImageMagick to resize it down',
  414. default=256, min=2, max=4096)
  415. # Materials
  416. bpy.types.Material.ogre_depth_write = BoolProperty(
  417. # Material.ogre_depth_write = AUTO|ON|OFF
  418. name='depth write',
  419. default=True)
  420. bpy.types.Material.ogre_depth_check = BoolProperty(
  421. # If depth-buffer checking is on, whenever a pixel is about to be written to
  422. # the frame buffer the depth buffer is checked to see if the pixel is in front
  423. # of all other pixels written at that point. If not, the pixel is not written.
  424. # If depth checking is off, pixels are written no matter what has been rendered before.
  425. name='depth check',
  426. default=True)
  427. bpy.types.Material.ogre_alpha_to_coverage = BoolProperty(
  428. # Sets whether this pass will use 'alpha to coverage', a way to multisample alpha
  429. # texture edges so they blend more seamlessly with the background. This facility
  430. # is typically only available on cards from around 2006 onwards, but it is safe to
  431. # enable it anyway - Ogre will just ignore it if the hardware does not support it.
  432. # The common use for alpha to coverage is foliage rendering and chain-link fence style textures.
  433. name='multisample alpha edges',
  434. default=False)
  435. bpy.types.Material.ogre_light_scissor = BoolProperty(
  436. # This option is usually only useful if this pass is an additive lighting pass, and is
  437. # at least the second one in the technique. Ie areas which are not affected by the current
  438. # light(s) will never need to be rendered. If there is more than one light being passed to
  439. # the pass, then the scissor is defined to be the rectangle which covers all lights in screen-space.
  440. # Directional lights are ignored since they are infinite. This option does not need to be specified
  441. # if you are using a standard additive shadow mode, i.e. SHADOWTYPE_STENCIL_ADDITIVE or
  442. # SHADOWTYPE_TEXTURE_ADDITIVE, since it is the default behaviour to use a scissor for each additive
  443. # shadow pass. However, if you're not using shadows, or you're using Integrated Texture Shadows
  444. # where passes are specified in a custom manner, then this could be of use to you.
  445. name='light scissor',
  446. default=False)
  447. bpy.types.Material.ogre_light_clip_planes = BoolProperty(
  448. name='light clip planes',
  449. default=False)
  450. bpy.types.Material.ogre_normalise_normals = BoolProperty(
  451. name='normalise normals',
  452. default=False,
  453. description="Scaling objects causes normals to also change magnitude, which can throw off your lighting calculations. By default, the SceneManager detects this and will automatically re-normalise normals for any scaled object, but this has a cost. If you'd prefer to control this manually, call SceneManager::setNormaliseNormalsOnScale(false) and then use this option on materials which are sensitive to normals being resized.")
  454. bpy.types.Material.ogre_lighting = BoolProperty(
  455. # Sets whether or not dynamic lighting is turned on for this pass or not. If lighting is turned off,
  456. # all objects rendered using the pass will be fully lit. This attribute has no effect if a vertex program is used.
  457. name='dynamic lighting',
  458. default=True)
  459. bpy.types.Material.ogre_colour_write = BoolProperty(
  460. # If colour writing is off no visible pixels are written to the screen during this pass. You might think
  461. # this is useless, but if you render with colour writing off, and with very minimal other settings,
  462. # you can use this pass to initialise the depth buffer before subsequently rendering other passes which
  463. # fill in the colour data. This can give you significant performance boosts on some newer cards, especially
  464. # when using complex fragment programs, because if the depth check fails then the fragment program is never run.
  465. name='color-write',
  466. default=True)
  467. bpy.types.Material.use_fixed_pipeline = BoolProperty(
  468. # Fixed pipeline is oldschool
  469. # todo: whats the meaning of this?
  470. name='fixed pipeline',
  471. default=True)
  472. bpy.types.Material.use_material_passes = BoolProperty(
  473. # hidden option - gets turned on by operator
  474. # todo: What is a hidden option, is this needed?
  475. name='use ogre extra material passes (layers)',
  476. default=False)
  477. bpy.types.Material.use_in_ogre_material_pass = BoolProperty(
  478. name='Layer Toggle',
  479. default=True)
  480. bpy.types.Material.use_ogre_advanced_options = BoolProperty(
  481. name='Show Advanced Options',
  482. default=False)
  483. bpy.types.Material.use_ogre_parent_material = BoolProperty(
  484. name='Use Script Inheritance',
  485. default=False)
  486. bpy.types.Material.ogre_parent_material = EnumProperty(
  487. name="Script Inheritence",
  488. description='ogre parent material class', #default='NONE',
  489. items=[])
  490. bpy.types.Material.ogre_polygon_mode = EnumProperty(
  491. name='faces draw type',
  492. description="ogre face draw mode",
  493. items=[ ('solid', 'solid', 'SOLID'),
  494. ('wireframe', 'wireframe', 'WIREFRAME'),
  495. ('points', 'points', 'POINTS') ],
  496. default='solid')
  497. bpy.types.Material.ogre_shading = EnumProperty(
  498. name='hardware shading',
  499. description="Sets the kind of shading which should be used for representing dynamic lighting for this pass.",
  500. items=[ ('flat', 'flat', 'FLAT'),
  501. ('gouraud', 'gouraud', 'GOURAUD'),
  502. ('phong', 'phong', 'PHONG') ],
  503. default='gouraud')
  504. bpy.types.Material.ogre_cull_hardware = EnumProperty(
  505. name='hardware culling',
  506. description="If the option 'cull_hardware clockwise' is set, all triangles whose vertices are viewed in clockwise order from the camera will be culled by the hardware.",
  507. items=[ ('clockwise', 'clockwise', 'CLOCKWISE'),
  508. ('anticlockwise', 'anticlockwise', 'COUNTER CLOCKWISE'),
  509. ('none', 'none', 'NONE') ],
  510. default='clockwise')
  511. bpy.types.Material.ogre_transparent_sorting = EnumProperty(
  512. name='transparent sorting',
  513. description="By default all transparent materials are sorted such that renderables furthest away from the camera are rendered first. This is usually the desired behaviour but in certain cases this depth sorting may be unnecessary and undesirable. If for example it is necessary to ensure the rendering order does not change from one frame to the next. In this case you could set the value to 'off' to prevent sorting.",
  514. items=[ ('on', 'on', 'ON'),
  515. ('off', 'off', 'OFF'),
  516. ('force', 'force', 'FORCE ON') ],
  517. default='on')
  518. bpy.types.Material.ogre_illumination_stage = EnumProperty(
  519. name='illumination stage',
  520. description='When using an additive lighting mode (SHADOWTYPE_STENCIL_ADDITIVE or SHADOWTYPE_TEXTURE_ADDITIVE), the scene is rendered in 3 discrete stages, ambient (or pre-lighting), per-light (once per light, with shadowing) and decal (or post-lighting). Usually OGRE figures out how to categorise your passes automatically, but there are some effects you cannot achieve without manually controlling the illumination.',
  521. items=[ ('', '', 'autodetect'),
  522. ('ambient', 'ambient', 'ambient'),
  523. ('per_light', 'per_light', 'lights'),
  524. ('decal', 'decal', 'decal') ],
  525. default=''
  526. )
  527. _ogre_depth_func = [
  528. ('less_equal', 'less_equal', '<='),
  529. ('less', 'less', '<'),
  530. ('equal', 'equal', '=='),
  531. ('not_equal', 'not_equal', '!='),
  532. ('greater_equal', 'greater_equal', '>='),
  533. ('greater', 'greater', '>'),
  534. ('always_fail', 'always_fail', 'false'),
  535. ('always_pass', 'always_pass', 'true'),
  536. ]
  537. bpy.types.Material.ogre_depth_func = EnumProperty(
  538. items=_ogre_depth_func,
  539. name='depth buffer function',
  540. description='If depth checking is enabled (see depth_check) a comparison occurs between the depth value of the pixel to be written and the current contents of the buffer. This comparison is normally less_equal, i.e. the pixel is written if it is closer (or at the same distance) than the current contents',
  541. default='less_equal')
  542. _ogre_scene_blend_ops = [
  543. ('add', 'add', 'DEFAULT'),
  544. ('subtract', 'subtract', 'SUBTRACT'),
  545. ('reverse_subtract', 'reverse_subtract', 'REVERSE SUBTRACT'),
  546. ('min', 'min', 'MIN'),
  547. ('max', 'max', 'MAX'),
  548. ]
  549. bpy.types.Material.ogre_scene_blend_op = EnumProperty(
  550. items=_ogre_scene_blend_ops,
  551. name='scene blending operation',
  552. description='This directive changes the operation which is applied between the two components of the scene blending equation',
  553. default='add')
  554. _ogre_scene_blend_types = [
  555. ('one zero', 'one zero', 'DEFAULT'),
  556. ('alpha_blend', 'alpha_blend', "The alpha value of the rendering output is used as a mask. Equivalent to 'scene_blend src_alpha one_minus_src_alpha'"),
  557. ('add', 'add', "The colour of the rendering output is added to the scene. Good for explosions, flares, lights, ghosts etc. Equivalent to 'scene_blend one one'."),
  558. ('modulate', 'modulate', "The colour of the rendering output is multiplied with the scene contents. Generally colours and darkens the scene, good for smoked glass, semi-transparent objects etc. Equivalent to 'scene_blend dest_colour zero'"),
  559. ('colour_blend', 'colour_blend', 'Colour the scene based on the brightness of the input colours, but dont darken. Equivalent to "scene_blend src_colour one_minus_src_colour"'),
  560. ]
  561. for mode in 'dest_colour src_colour one_minus_dest_colour dest_alpha src_alpha one_minus_dest_alpha one_minus_src_alpha'.split():
  562. _ogre_scene_blend_types.append( ('one %s'%mode, 'one %s'%mode, '') )
  563. del mode
  564. bpy.types.Material.ogre_scene_blend = EnumProperty(
  565. items=_ogre_scene_blend_types,
  566. name='scene blend',
  567. description='blending operation of material to scene',
  568. default='one zero')
  569. ## FAQ
  570. _faq_ = '''
  571. Q: I have hundres of objects, is there a way i can merge them on export only?
  572. A: Yes, just add them to a group named starting with "merge", or link the group.
  573. Q: Can i use subsurf or multi-res on a mesh with an armature?
  574. A: Yes.
  575. Q: Can i use subsurf or multi-res on a mesh with shape animation?
  576. A: No.
  577. Q: I don't see any objects when i export?
  578. A: You must select the objects you wish to export.
  579. Q: I don't see my animations when exported?
  580. A: Make sure you created an NLA strip on the armature.
  581. Q: Do i need to bake my IK and other constraints into FK on my armature before export?
  582. A: No.
  583. '''
  584. ## DOCUMENTATION
  585. ''' todo: Update the nonsense C:\Tundra2 paths from defaul config and fix this doc.
  586. Additionally point to some doc how to build opengl only version on windows if that really is needed and
  587. remove the old Tundra 7z link. '''
  588. _doc_installing_ = '''
  589. Installing:
  590. Installing the Addon:
  591. You can simply copy io_export_ogreDotScene.py to your blender installation under blender/2.6x/scripts/addons/
  592. and enable it in the user-prefs interface (CTRL+ALT+U)
  593. Or you can use blenders interface, under user-prefs, click addons, and click 'install-addon'
  594. (its a good idea to delete the old version first)
  595. Required:
  596. 1. Blender 2.63
  597. 2. Install Ogre Command Line tools to the default path: C:\\OgreCommandLineTools from http://www.ogre3d.org/download/tools
  598. * These tools are used to create the binary Mesh from the .xml mesh generated by this plugin.
  599. * Linux users may use above and Wine, or install from source, or install via apt-get install ogre-tools.
  600. Optional:
  601. 3. Install NVIDIA DDS Legacy Utilities - Install them to default path.
  602. * http://developer.nvidia.com/object/dds_utilities_legacy.html
  603. * Linux users will need to use Wine.
  604. 4. Install Image Magick
  605. * http://www.imagemagick.org
  606. 5. Copy OgreMeshy to C:\\OgreMeshy
  607. * If your using 64bit Windows, you may need to download a 64bit OgreMeshy
  608. * Linux copy to your home folder.
  609. 6. realXtend Tundra
  610. * For latest Tundra releases see http://code.google.com/p/realxtend-naali/downloads/list
  611. - You may need to tweak the config to tell your Tundra path or install to C:\Tundra2
  612. * Old OpenGL only build can be found from http://blender2ogre.googlecode.com/files/realxtend-Tundra-2.1.2-OpenGL.7z
  613. - Windows: extract to C:\Tundra2
  614. - Linux: extract to ~/Tundra2
  615. '''
  616. ## Options
  617. AXIS_MODES = [
  618. ('xyz', 'xyz', 'no swapping'),
  619. ('xz-y', 'xz-y', 'ogre standard'),
  620. ('-xzy', '-xzy', 'non standard'),
  621. ]
  622. def swap(vec):
  623. if CONFIG['SWAP_AXIS'] == 'xyz': return vec
  624. elif CONFIG['SWAP_AXIS'] == 'xzy':
  625. if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, vec.y] )
  626. elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, vec.y] )
  627. elif CONFIG['SWAP_AXIS'] == '-xzy':
  628. if len(vec) == 3: return mathutils.Vector( [-vec.x, vec.z, vec.y] )
  629. elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, -vec.x, vec.z, vec.y] )
  630. elif CONFIG['SWAP_AXIS'] == 'xz-y':
  631. if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, -vec.y] )
  632. elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, -vec.y] )
  633. else:
  634. print( 'unknown swap axis mode', CONFIG['SWAP_AXIS'] )
  635. assert 0
  636. ## Config
  637. CONFIG_PATH = bpy.utils.user_resource('CONFIG', path='scripts', create=True)
  638. CONFIG_FILENAME = 'blender2ogre.pickle'
  639. CONFIG_FILEPATH = os.path.join(CONFIG_PATH, CONFIG_FILENAME)
  640. _CONFIG_DEFAULTS_ALL = {
  641. 'TUNDRA_STREAMING' : True,
  642. 'COPY_SHADER_PROGRAMS' : True,
  643. 'MAX_TEXTURE_SIZE' : 4096,
  644. 'SWAP_AXIS' : 'xz-y', # ogre standard
  645. 'ONLY_ANIMATED_BONES' : False,
  646. 'ONLY_DEFORMABLE_BONES' : False,
  647. 'INDEPENDENT_ANIM' : False,
  648. 'FORCE_IMAGE_FORMAT' : 'NONE',
  649. 'TOUCH_TEXTURES' : True,
  650. 'SEP_MATS' : True,
  651. 'SCENE' : True,
  652. 'SELONLY' : True,
  653. 'FORCE_CAMERA' : True,
  654. 'FORCE_LAMPS' : True,
  655. 'MESH' : True,
  656. 'MESH_OVERWRITE' : True,
  657. 'ARM_ANIM' : True,
  658. 'SHAPE_ANIM' : True,
  659. 'ARRAY' : True,
  660. 'MATERIALS' : True,
  661. 'DDS_MIPS' : True,
  662. 'TRIM_BONE_WEIGHTS' : 0.01,
  663. 'lodLevels' : 0,
  664. 'lodDistance' : 300,
  665. 'lodPercent' : 40,
  666. 'nuextremityPoints' : 0,
  667. 'generateEdgeLists' : False,
  668. 'generateTangents' : True, # this is now safe - ignored if mesh is missing UVs
  669. 'tangentSemantic' : 'uvw',
  670. 'tangentUseParity' : 4,
  671. 'tangentSplitMirrored' : False,
  672. 'tangentSplitRotated' : False,
  673. 'reorganiseBuffers' : True,
  674. 'optimiseAnimations' : True,
  675. }
  676. _CONFIG_TAGS_ = 'OGRETOOLS_XML_CONVERTER OGRETOOLS_MESH_MAGICK TUNDRA_ROOT OGRE_MESHY IMAGE_MAGICK_CONVERT NVCOMPRESS NVIDIATOOLS_EXE USER_MATERIALS SHADER_PROGRAMS TUNDRA_STREAMING'.split()
  677. ''' todo: Change pretty much all of these windows ones. Make a smarter way of detecting
  678. Ogre tools and Tundra from various default folders. Also consider making a installer that
  679. ships Ogre cmd line tools to ease the setup steps for end users. '''
  680. _CONFIG_DEFAULTS_WINDOWS = {
  681. 'OGRETOOLS_XML_CONVERTER' : 'C:\\OgreCommandLineTools\\OgreXmlConverter.exe',
  682. 'OGRETOOLS_MESH_MAGICK' : 'C:\\OgreCommandLineTools\\MeshMagick.exe',
  683. 'TUNDRA_ROOT' : 'C:\\Tundra2',
  684. 'OGRE_MESHY' : 'C:\\OgreMeshy\\Ogre Meshy.exe',
  685. 'IMAGE_MAGICK_CONVERT' : 'C:\\Program Files\\ImageMagick\\convert.exe',
  686. 'NVIDIATOOLS_EXE' : 'C:\\Program Files\\NVIDIA Corporation\\DDS Utilities\\nvdxt.exe',
  687. 'USER_MATERIALS' : 'C:\\Tundra2\\media\\materials',
  688. 'SHADER_PROGRAMS' : 'C:\\Tundra2\\media\\materials\\programs',
  689. 'NVCOMPRESS' : 'C:\\nvcompress.exe'
  690. }
  691. _CONFIG_DEFAULTS_UNIX = {
  692. 'OGRETOOLS_XML_CONVERTER' : '/usr/local/bin/OgreXMLConverter', # source build is better
  693. 'OGRETOOLS_MESH_MAGICK' : '/usr/local/bin/MeshMagick',
  694. 'TUNDRA_ROOT' : '~/Tundra2',
  695. 'OGRE_MESHY' : '~/OgreMeshy/Ogre Meshy.exe',
  696. 'IMAGE_MAGICK_CONVERT' : '/usr/bin/convert',
  697. 'NVIDIATOOLS_EXE' : '~/.wine/drive_c/Program Files/NVIDIA Corporation/DDS Utilities',
  698. 'USER_MATERIALS' : '~/Tundra2/media/materials',
  699. 'SHADER_PROGRAMS' : '~/Tundra2/media/materials/programs',
  700. #'USER_MATERIALS' : '~/ogre_src_v1-7-3/Samples/Media/materials',
  701. #'SHADER_PROGRAMS' : '~/ogre_src_v1-7-3/Samples/Media/materials/programs',
  702. 'NVCOMPRESS' : '/usr/local/bin/nvcompress'
  703. }
  704. # Unix: Replace ~ with absolute home dir path
  705. if sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
  706. for tag in _CONFIG_DEFAULTS_UNIX:
  707. path = _CONFIG_DEFAULTS_UNIX[ tag ]
  708. if path.startswith('~'):
  709. _CONFIG_DEFAULTS_UNIX[ tag ] = os.path.expanduser( path )
  710. elif tag.startswith('OGRETOOLS') and not os.path.isfile( path ):
  711. _CONFIG_DEFAULTS_UNIX[ tag ] = os.path.join( '/usr/bin', os.path.split( path )[-1] )
  712. del tag
  713. del path
  714. ## PUBLIC API continues
  715. CONFIG = {}
  716. def load_config():
  717. global CONFIG
  718. if os.path.isfile( CONFIG_FILEPATH ):
  719. try:
  720. with open( CONFIG_FILEPATH, 'rb' ) as f:
  721. CONFIG = pickle.load( f )
  722. except:
  723. print('[ERROR]: Can not read config from %s' %CONFIG_FILEPATH)
  724. for tag in _CONFIG_DEFAULTS_ALL:
  725. if tag not in CONFIG:
  726. CONFIG[ tag ] = _CONFIG_DEFAULTS_ALL[ tag ]
  727. for tag in _CONFIG_TAGS_:
  728. if tag not in CONFIG:
  729. if sys.platform.startswith('win'):
  730. CONFIG[ tag ] = _CONFIG_DEFAULTS_WINDOWS[ tag ]
  731. elif sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
  732. CONFIG[ tag ] = _CONFIG_DEFAULTS_UNIX[ tag ]
  733. else:
  734. print( 'ERROR: unknown platform' )
  735. assert 0
  736. try:
  737. if sys.platform.startswith('win'):
  738. import winreg
  739. # Find the blender2ogre install path from windows registry
  740. registry_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Software\blender2ogre', 0, winreg.KEY_READ)
  741. exe_install_dir = winreg.QueryValueEx(registry_key, "Path")[0]
  742. if exe_install_dir != "":
  743. # OgreXmlConverter
  744. if os.path.isfile(exe_install_dir + "OgreXmlConverter.exe"):
  745. print ("Using OgreXmlConverter from install path:", exe_install_dir + "OgreXmlConverter.exe")
  746. CONFIG['OGRETOOLS_XML_CONVERTER'] = exe_install_dir + "OgreXmlConverter.exe"
  747. # Run auto updater as silent. Notifies user if there is a new version out.
  748. # This will not show any UI if there are no update and will go to network
  749. # only once per 2 days so it wont be spending much resources either.
  750. # todo: Move this to a more appropriate place than load_config()
  751. if os.path.isfile(exe_install_dir + "check-for-updates.exe"):
  752. subprocess.Popen([exe_install_dir + "check-for-updates.exe", "/silent"])
  753. except Exception as e:
  754. print("Exception while reading windows registry:", e)
  755. # Setup temp hidden RNA to expose the file paths
  756. for tag in _CONFIG_TAGS_:
  757. default = CONFIG[ tag ]
  758. func = eval( 'lambda self,con: CONFIG.update( {"%s" : self.%s} )' %(tag,tag) )
  759. if type(default) is bool:
  760. prop = BoolProperty(
  761. name=tag, description='updates bool setting', default=default,
  762. options={'SKIP_SAVE'}, update=func
  763. )
  764. else:
  765. prop = StringProperty(
  766. name=tag, description='updates path setting', maxlen=128, default=default,
  767. options={'SKIP_SAVE'}, update=func
  768. )
  769. setattr( bpy.types.WindowManager, tag, prop )
  770. return CONFIG
  771. CONFIG = load_config()
  772. def save_config():
  773. #for key in CONFIG: print( '%s = %s' %(key, CONFIG[key]) )
  774. if os.path.isdir( CONFIG_PATH ):
  775. try:
  776. with open( CONFIG_FILEPATH, 'wb' ) as f:
  777. pickle.dump( CONFIG, f, -1 )
  778. except:
  779. print('[ERROR]: Can not write to %s' %CONFIG_FILEPATH)
  780. else:
  781. print('[ERROR:] Config directory does not exist %s' %CONFIG_PATH)
  782. class Blender2Ogre_ConfigOp(bpy.types.Operator):
  783. '''operator: saves current b2ogre configuration'''
  784. bl_idname = "ogre.save_config"
  785. bl_label = "save config file"
  786. bl_options = {'REGISTER'}
  787. @classmethod
  788. def poll(cls, context):
  789. return True
  790. def invoke(self, context, event):
  791. save_config()
  792. Report.reset()
  793. Report.messages.append('SAVED %s' %CONFIG_FILEPATH)
  794. Report.show()
  795. return {'FINISHED'}
  796. # Make default material for missing materials:
  797. # * Red flags for users so they can quickly see what they forgot to assign a material to.
  798. # * Do not crash if no material on object - thats annoying for the user.
  799. MISSING_MATERIAL = '''
  800. material _missing_material_
  801. {
  802. receive_shadows off
  803. technique
  804. {
  805. pass
  806. {
  807. ambient 0.1 0.1 0.1 1.0
  808. diffuse 0.8 0.0 0.0 1.0
  809. specular 0.5 0.5 0.5 1.0 12.5
  810. emissive 0.3 0.3 0.3 1.0
  811. }
  812. }
  813. }
  814. '''
  815. ## Helper functions
  816. def timer_diff_str(start):
  817. return "%0.2f" % (time.time()-start)
  818. def find_bone_index( ob, arm, groupidx): # sometimes the groups are out of order, this finds the right index.
  819. if groupidx < len(ob.vertex_groups): # reported by Slacker
  820. vg = ob.vertex_groups[ groupidx ]
  821. j = 0
  822. for i,bone in enumerate(arm.pose.bones):
  823. if not bone.bone.use_deform and CONFIG['ONLY_DEFORMABLE_BONES']:
  824. j+=1 # if we skip bones we need to adjust the id
  825. if bone.name == vg.name:
  826. return i-j
  827. else:
  828. print('WARNING: object vertex groups not in sync with armature', ob, arm, groupidx)
  829. def mesh_is_smooth( mesh ):
  830. for face in mesh.tessfaces:
  831. if face.use_smooth: return True
  832. def find_uv_layer_index( uvname, material=None ):
  833. # This breaks if users have uv layers with same name with different indices over different objects
  834. idx = 0
  835. for mesh in bpy.data.meshes:
  836. if material is None or material.name in mesh.materials:
  837. if mesh.uv_textures:
  838. names = [ uv.name for uv in mesh.uv_textures ]
  839. if uvname in names:
  840. idx = names.index( uvname )
  841. break # should we check all objects using material and enforce the same index?
  842. return idx
  843. def has_custom_property( a, name ):
  844. for prop in a.items():
  845. n,val = prop
  846. if n == name:
  847. return True
  848. def is_strictly_simple_terrain( ob ):
  849. # A default plane, with simple-subsurf and displace modifier on Z
  850. if len(ob.data.vertices) != 4 and len(ob.data.tessfaces) != 1:
  851. return False
  852. elif len(ob.modifiers) < 2:
  853. return False
  854. elif ob.modifiers[0].type != 'SUBSURF' or ob.modifiers[1].type != 'DISPLACE':
  855. return False
  856. elif ob.modifiers[0].subdivision_type != 'SIMPLE':
  857. return False
  858. elif ob.modifiers[1].direction != 'Z':
  859. return False # disallow NORMAL and other modes
  860. else:
  861. return True
  862. def get_image_textures( mat ):
  863. r = []
  864. for s in mat.texture_slots:
  865. if s and s.texture.type == 'IMAGE':
  866. r.append( s )
  867. return r
  868. def indent( level, *args ):
  869. if not args:
  870. return ' ' * level
  871. else:
  872. a = ''
  873. for line in args:
  874. a += ' ' * level
  875. a += line
  876. a += '\n'
  877. return a
  878. def gather_instances():
  879. instances = {}
  880. for ob in bpy.context.scene.objects:
  881. if ob.data and ob.data.users > 1:
  882. if ob.data not in instances:
  883. instances[ ob.data ] = []
  884. instances[ ob.data ].append( ob )
  885. return instances
  886. def select_instances( context, name ):
  887. for ob in bpy.context.scene.objects:
  888. ob.select = False
  889. ob = bpy.context.scene.objects[ name ]
  890. if ob.data:
  891. inst = gather_instances()
  892. for ob in inst[ ob.data ]: ob.select = True
  893. bpy.context.scene.objects.active = ob
  894. def select_group( context, name, options={} ):
  895. for ob in bpy.context.scene.objects:
  896. ob.select = False
  897. for grp in bpy.data.groups:
  898. if grp.name == name:
  899. # context.scene.objects.active = grp.objects
  900. # Note that the context is read-only. These values cannot be modified directly,
  901. # though they may be changed by running API functions or by using the data API.
  902. # So bpy.context.object = obj will raise an error. But bpy.context.scene.objects.active = obj
  903. # will work as expected. - http://wiki.blender.org/index.php?title=Dev:2.5/Py/API/Intro&useskin=monobook
  904. bpy.context.scene.objects.active = grp.objects[0]
  905. for ob in grp.objects:
  906. ob.select = True
  907. else:
  908. pass
  909. def get_objects_using_materials( mats ):
  910. obs = []
  911. for ob in bpy.data.objects:
  912. if ob.type == 'MESH':
  913. for mat in ob.data.materials:
  914. if mat in mats:
  915. if ob not in obs:
  916. obs.append( ob )
  917. break
  918. return obs
  919. def get_materials_using_image( img ):
  920. mats = []
  921. for mat in bpy.data.materials:
  922. for slot in get_image_textures( mat ):
  923. if slot.texture.image == img:
  924. if mat not in mats:
  925. mats.append( mat )
  926. return mats
  927. def get_parent_matrix( ob, objects ):
  928. if not ob.parent:
  929. return mathutils.Matrix(((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1))) # Requiered for Blender SVN > 2.56
  930. else:
  931. if ob.parent in objects:
  932. return ob.parent.matrix_world.copy()
  933. else:
  934. return get_parent_matrix(ob.parent, objects)
  935. def merge_group( group ):
  936. print('--------------- merge group ->', group )
  937. copies = []
  938. for ob in group.objects:
  939. if ob.type == 'MESH':
  940. print( '\t group member', ob.name )
  941. o2 = ob.copy(); copies.append( o2 )
  942. o2.data = o2.to_mesh(bpy.context.scene, True, "PREVIEW") # collaspe modifiers
  943. while o2.modifiers:
  944. o2.modifiers.remove( o2.modifiers[0] )
  945. bpy.context.scene.objects.link( o2 ) #; o2.select = True
  946. merged = merge( copies )
  947. merged.name = group.name
  948. merged.data.name = group.name
  949. return merged
  950. def merge_objects( objects, name='_temp_', transform=None ):
  951. assert objects
  952. copies = []
  953. for ob in objects:
  954. ob.select = False
  955. if ob.type == 'MESH':
  956. o2 = ob.copy(); copies.append( o2 )
  957. o2.data = o2.to_mesh(bpy.context.scene, True, "PREVIEW") # collaspe modifiers
  958. while o2.modifiers:
  959. o2.modifiers.remove( o2.modifiers[0] )
  960. if transform:
  961. o2.matrix_world = transform * o2.matrix_local
  962. bpy.context.scene.objects.link( o2 ) #; o2.select = True
  963. merged = merge( copies )
  964. merged.name = name
  965. merged.data.name = name
  966. return merged
  967. def merge( objects ):
  968. print('MERGE', objects)
  969. for ob in bpy.context.selected_objects:
  970. ob.select = False
  971. for ob in objects:
  972. print('\t'+ob.name)
  973. ob.select = True
  974. assert not ob.library
  975. bpy.context.scene.objects.active = ob
  976. bpy.ops.object.join()
  977. return bpy.context.active_object
  978. def get_merge_group( ob, prefix='merge' ):
  979. m = []
  980. for grp in ob.users_group:
  981. if grp.name.lower().startswith(prefix): m.append( grp )
  982. if len(m)==1:
  983. #if ob.data.users != 1:
  984. # print( 'WARNING: an instance can not be in a merge group' )
  985. # return
  986. return m[0]
  987. elif m:
  988. print('WARNING: an object can not be in two merge groups at the same time', ob)
  989. return
  990. def wordwrap( txt ):
  991. r = ['']
  992. for word in txt.split(' '): # do not split on tabs
  993. word = word.replace('\t', ' '*3)
  994. r[-1] += word + ' '
  995. if len(r[-1]) > 90:
  996. r.append( '' )
  997. return r
  998. ## RPython xml dom
  999. class RElement(object):
  1000. def appendChild( self, child ):
  1001. self.childNodes.append( child )
  1002. def setAttribute( self, name, value ):
  1003. self.attributes[name]=value
  1004. def __init__(self, tag):
  1005. self.tagName = tag
  1006. self.childNodes = []
  1007. self.attributes = {}
  1008. def toprettyxml(self, lines, indent ):
  1009. s = '<%s ' % self.tagName
  1010. for name in self.attributes:
  1011. value = self.attributes[name]
  1012. if not isinstance(value, str):
  1013. value = str(value)
  1014. s += '%s=%s ' % (name, quoteattr(value))
  1015. if not self.childNodes:
  1016. s += '/>'; lines.append( (' '*indent)+s )
  1017. else:
  1018. s += '>'; lines.append( (' '*indent)+s )
  1019. indent += 1
  1020. for child in self.childNodes:
  1021. child.toprettyxml( lines, indent )
  1022. indent -= 1
  1023. lines.append((' '*indent) + '</%s>' % self.tagName )
  1024. class RDocument(object):
  1025. def __init__(self):
  1026. self.documentElement = None
  1027. def appendChild(self, root):
  1028. self.documentElement = root
  1029. def createElement(self, tag):
  1030. e = RElement(tag)
  1031. e.document = self
  1032. return e
  1033. def toprettyxml(self):
  1034. indent = 0
  1035. lines = []
  1036. self.documentElement.toprettyxml(lines, indent)
  1037. return '\n'.join(lines)
  1038. class SimpleSaxWriter():
  1039. def __init__(self, output, encoding, top_level_tag, attrs):
  1040. xml_writer = XMLGenerator(output, encoding, True)
  1041. xml_writer.startDocument()
  1042. xml_writer.startElement(top_level_tag, attrs)
  1043. self._xml_writer = xml_writer
  1044. self.top_level_tag = top_level_tag
  1045. self.ident=4
  1046. self._xml_writer.characters('\n')
  1047. def start_tag(self, name, attrs):
  1048. self._xml_writer.characters(" " * self.ident)
  1049. self._xml_writer.startElement(name, attrs)
  1050. self.ident += 4
  1051. self._xml_writer.characters('\n')
  1052. def end_tag(self, name):
  1053. self.ident -= 4
  1054. self._xml_writer.characters(" " * self.ident)
  1055. self._xml_writer.endElement(name)
  1056. self._xml_writer.characters('\n')
  1057. def leaf_tag(self, name, attrs):
  1058. self._xml_writer.characters(" " * self.ident)
  1059. self._xml_writer.startElement(name, attrs)
  1060. self._xml_writer.endElement(name)
  1061. self._xml_writer.characters('\n')
  1062. def close(self):
  1063. self._xml_writer.endElement(self.top_level_tag)
  1064. self._xml_writer.endDocument()
  1065. ## Report Hack
  1066. class ReportSingleton(object):
  1067. def __init__(self):
  1068. self.reset()
  1069. def show(self):
  1070. bpy.ops.wm.call_menu( name='MiniReport' )
  1071. def reset(self):
  1072. self.materials = []
  1073. self.meshes = []
  1074. self.lights = []
  1075. self.cameras = []
  1076. self.armatures = []
  1077. self.armature_animations = []
  1078. self.shape_animations = []
  1079. self.textures = []
  1080. self.vertices = 0
  1081. self.orig_vertices = 0
  1082. self.faces = 0
  1083. self.triangles = 0
  1084. self.warnings = []
  1085. self.errors = []
  1086. self.messages = []
  1087. self.paths = []
  1088. def report(self):
  1089. r = ['Report:']
  1090. ex = ['Extended Report:']
  1091. if self.errors:
  1092. r.append( ' ERRORS:' )
  1093. for a in self.errors: r.append( ' - %s' %a )
  1094. #if not bpy.context.selected_objects:
  1095. # self.warnings.append('YOU DID NOT SELECT ANYTHING TO EXPORT')
  1096. if self.warnings:
  1097. r.append( ' WARNINGS:' )
  1098. for a in self.warnings: r.append( ' - %s' %a )
  1099. if self.messages:
  1100. r.append( ' MESSAGES:' )
  1101. for a in self.messages: r.append( ' - %s' %a )
  1102. if self.paths:
  1103. r.append( ' PATHS:' )
  1104. for a in self.paths: r.append( ' - %s' %a )
  1105. if self.vertices:
  1106. r.append( ' Original Vertices: %s' %self.orig_vertices)
  1107. r.append( ' Exported Vertices: %s' %self.vertices )
  1108. r.append( ' Original Faces: %s' %self.faces )
  1109. r.append( ' Exported Triangles: %s' %self.triangles )
  1110. ## TODO report file sizes, meshes and textures
  1111. for tag in 'meshes lights cameras armatures armature_animations shape_animations materials textures'.split():
  1112. attr = getattr(self, tag)
  1113. if attr:
  1114. name = tag.replace('_',' ').upper()
  1115. r.append( ' %s: %s' %(name, len(attr)) )
  1116. if attr:
  1117. ex.append( ' %s:' %name )
  1118. for a in attr: ex.append( ' . %s' %a )
  1119. txt = '\n'.join( r )
  1120. ex = '\n'.join( ex ) # console only - extended report
  1121. print('_'*80)
  1122. print(txt)
  1123. print(ex)
  1124. print('_'*80)
  1125. return txt
  1126. Report = ReportSingleton()
  1127. class MiniReport(bpy.types.Menu):
  1128. bl_label = "Mini-Report | (see console for full report)"
  1129. def draw(self, context):
  1130. layout = self.layout
  1131. txt = Report.report()
  1132. for line in txt.splitlines():
  1133. layout.label(text=line)
  1134. ## RPython xml dom ends
  1135. def _get_proxy_decimate_mod( ob ):
  1136. proxy = None
  1137. for child in ob.children:
  1138. if child.subcollision and child.name.startswith('DECIMATED'):
  1139. for mod in child.modifiers:
  1140. if mod.type == 'DECIMATE':
  1141. return mod
  1142. def bake_terrain( ob, normalize=True ):
  1143. assert ob.collision_mode == 'TERRAIN'
  1144. terrain = None
  1145. for child in ob.children:
  1146. if child.subcollision and child.name.startswith('TERRAIN'):
  1147. terrain = child
  1148. break
  1149. assert terrain
  1150. data = terrain.to_mesh(bpy.context.scene, True, "PREVIEW")
  1151. raw = [ v.co.z for v in data.vertices ]
  1152. Zmin = min( raw )
  1153. Zmax = max( raw )
  1154. depth = Zmax-Zmin
  1155. m = 1.0 / depth
  1156. rows = []
  1157. i = 0
  1158. for x in range( ob.collision_terrain_x_steps ):
  1159. row = []
  1160. for y in range( ob.collision_terrain_y_steps ):
  1161. v = data.vertices[ i ]
  1162. if normalize:
  1163. z = (v.co.z - Zmin) * m
  1164. else:
  1165. z = v.co.z
  1166. row.append( z )
  1167. i += 1
  1168. if x%2:
  1169. row.reverse() # blender grid prim zig-zags
  1170. rows.append( row )
  1171. return {'data':rows, 'min':Zmin, 'max':Zmax, 'depth':depth}
  1172. def save_terrain_as_NTF( path, ob ): # Tundra format - hardcoded 16x16 patch format
  1173. info = bake_terrain( ob )
  1174. url = os.path.join( path, '%s.ntf'%ob.data.name )
  1175. f = open(url, "wb")
  1176. # Header
  1177. buf = array.array("I")
  1178. xs = ob.collision_terrain_x_steps
  1179. ys = ob.collision_terrain_y_steps
  1180. xpatches = int(xs/16)
  1181. ypatches = int(ys/16)
  1182. header = [ xpatches, ypatches ]
  1183. buf.fromlist( header )
  1184. buf.tofile(f)
  1185. # Body
  1186. rows = info['data']
  1187. for x in range( xpatches ):
  1188. for y in range( ypatches ):
  1189. patch = []
  1190. for i in range(16):
  1191. for j in range(16):
  1192. v = rows[ (x*16)+i ][ (y*16)+j ]
  1193. patch.append( v )
  1194. buf = array.array("f")
  1195. buf.fromlist( patch )
  1196. buf.tofile(f)
  1197. f.close()
  1198. path,name = os.path.split(url)
  1199. R = {
  1200. 'url':url, 'min':info['min'], 'max':info['max'], 'path':path, 'name':name,
  1201. 'xpatches': xpatches, 'ypatches': ypatches,
  1202. 'depth':info['depth'],
  1203. }
  1204. return R
  1205. class OgreCollisionOp(bpy.types.Operator):
  1206. '''Ogre Collision'''
  1207. bl_idname = "ogre.set_collision"
  1208. bl_label = "modify collision"
  1209. bl_options = {'REGISTER'}
  1210. MODE = StringProperty(name="toggle mode", maxlen=32, default="disable")
  1211. @classmethod
  1212. def poll(cls, context):
  1213. if context.active_object and context.active_object.type == 'MESH':
  1214. return True
  1215. def get_subcollisions( self, ob, create=True ):
  1216. r = get_subcollisions( ob )
  1217. if not r and create:
  1218. method = getattr(self, 'create_%s'%ob.collision_mode)
  1219. p = method(ob)
  1220. p.name = '%s.%s' %(ob.collision_mode, ob.name)
  1221. p.subcollision = True
  1222. r.append( p )
  1223. return r
  1224. def create_DECIMATED(self, ob):
  1225. child = ob.copy()
  1226. bpy.context.scene.objects.link( child )
  1227. child.matrix_local = mathutils.Matrix()
  1228. child.parent = ob
  1229. child.hide_select = True
  1230. child.draw_type = 'WIRE'
  1231. #child.select = False
  1232. child.lock_location = [True]*3
  1233. child.lock_rotation = [True]*3
  1234. child.lock_scale = [True]*3
  1235. decmod = child.modifiers.new('proxy', type='DECIMATE')
  1236. decmod.ratio = 0.5
  1237. return child
  1238. def create_TERRAIN(self, ob):
  1239. x = ob.collision_terrain_x_steps
  1240. y = ob.collision_terrain_y_steps
  1241. #################################
  1242. #pos = ob.matrix_world.to_translation()
  1243. bpy.ops.mesh.primitive_grid_add(
  1244. x_subdivisions=x,
  1245. y_subdivisions=y,
  1246. size=1.0 ) #, location=pos )
  1247. grid = bpy.context.active_object
  1248. assert grid.name.startswith('Grid')
  1249. grid.collision_terrain_x_steps = x
  1250. grid.collision_terrain_y_steps = y
  1251. #############################
  1252. x,y,z = ob.dimensions
  1253. sx,sy,sz = ob.scale
  1254. x *= 1.0/sx
  1255. y *= 1.0/sy
  1256. z *= 1.0/sz
  1257. grid.scale.x = x/2
  1258. grid.scale.y = y/2
  1259. grid.location.z -= z/2
  1260. grid.data.show_all_edges = True
  1261. grid.draw_type = 'WIRE'
  1262. grid.hide_select = True
  1263. #grid.select = False
  1264. grid.lock_location = [True]*3
  1265. grid.lock_rotation = [True]*3
  1266. grid.lock_scale = [True]*3
  1267. grid.parent = ob
  1268. bpy.context.scene.objects.active = ob
  1269. mod = grid.modifiers.new(name='temp', type='SHRINKWRAP')
  1270. mod.wrap_method = 'PROJECT'
  1271. mod.use_project_z = True
  1272. mod.target = ob
  1273. mod.cull_face = 'FRONT'
  1274. return grid
  1275. def invoke(self, context, event):
  1276. ob = context.active_object
  1277. game = ob.game
  1278. subtype = None
  1279. if ':' in self.MODE:
  1280. mode, subtype = self.MODE.split(':')
  1281. ##BLENDERBUG##ob.game.collision_bounds_type = subtype # BUG this can not come before
  1282. if subtype in 'BOX SPHERE CYLINDER CONE CAPSULE'.split():
  1283. ob.draw_bounds_type = subtype
  1284. else:
  1285. ob.draw_bounds_type = 'POLYHEDRON'
  1286. ob.game.collision_bounds_type = subtype # BLENDERBUG - this must come after draw_bounds_type assignment
  1287. else:
  1288. mode = self.MODE
  1289. ob.collision_mode = mode
  1290. if ob.data.show_all_edges:
  1291. ob.data.show_all_edges = False
  1292. if ob.show_texture_space:
  1293. ob.show_texture_space = False
  1294. if ob.show_bounds:
  1295. ob.show_bounds = False
  1296. if ob.show_wire:
  1297. ob.show_wire = False
  1298. for child in ob.children:
  1299. if child.subcollision and not child.hide:
  1300. child.hide = True
  1301. if mode == 'NONE':
  1302. game.use_ghost = True
  1303. game.use_collision_bounds = False
  1304. elif mode == 'PRIMITIVE':
  1305. game.use_ghost = False
  1306. game.use_collision_bounds = True
  1307. ob.show_bounds = True
  1308. elif mode == 'MESH':
  1309. game.use_ghost = False
  1310. game.use_collision_bounds = True
  1311. ob.show_wire = True
  1312. if game.collision_bounds_type == 'CONVEX_HULL':
  1313. ob.show_texture_space = True
  1314. else:
  1315. ob.data.show_all_edges = True
  1316. elif mode == 'DECIMATED':
  1317. game.use_ghost = True
  1318. game.use_collision_bounds = False
  1319. game.use_collision_compound = True
  1320. proxy = self.get_subcollisions(ob)[0]
  1321. if proxy.hide: proxy.hide = False
  1322. ob.game.use_collision_compound = True # proxy
  1323. mod = _get_proxy_decimate_mod( ob )
  1324. mod.show_viewport = True
  1325. if not proxy.select: # ugly (but works)
  1326. proxy.hide_select = False
  1327. proxy.select = True
  1328. proxy.hide_select = True
  1329. if game.collision_bounds_type == 'CONVEX_HULL':
  1330. ob.show_texture_space = True
  1331. elif mode == 'TERRAIN':
  1332. game.use_ghost = True
  1333. game.use_collision_bounds = False
  1334. game.use_collision_compound = True
  1335. proxy = self.get_subcollisions(ob)[0]
  1336. if proxy.hide:
  1337. proxy.hide = False
  1338. elif mode == 'COMPOUND':
  1339. game.use_ghost = True
  1340. game.use_collision_bounds = False
  1341. game.use_collision_compound = True
  1342. else:
  1343. assert 0 # unknown mode
  1344. return {'FINISHED'}
  1345. # UI panels
  1346. @UI
  1347. class PANEL_Physics(bpy.types.Panel):
  1348. bl_space_type = 'VIEW_3D'
  1349. bl_region_type = 'UI'
  1350. bl_label = "Physics"
  1351. @classmethod
  1352. def poll(cls, context):
  1353. if context.active_object:
  1354. return True
  1355. else:
  1356. return False
  1357. def draw(self, context):
  1358. layout = self.layout
  1359. ob = context.active_object
  1360. game = ob.game
  1361. if ob.type != 'MESH':
  1362. return
  1363. elif ob.subcollision == True:
  1364. box = layout.box()
  1365. if ob.parent:
  1366. box.label(text='object is a collision proxy for: %s' %ob.parent.name)
  1367. else:
  1368. box.label(text='WARNING: collision proxy missing parent')
  1369. return
  1370. box = layout.box()
  1371. box.prop(ob, 'physics_mode')
  1372. if ob.physics_mode != 'NONE':
  1373. box.prop(game, 'mass', text='Mass')
  1374. box.prop(ob, 'physics_friction', text='Friction', slider=True)
  1375. box.prop(ob, 'physics_bounce', text='Bounce', slider=True)
  1376. box.label(text="Damping:")
  1377. box.prop(game, 'damping', text='Translation', slider=True)
  1378. box.prop(game, 'rotation_damping', text='Rotation', slider=True)
  1379. box.label(text="Velocity:")
  1380. box.prop(game, "velocity_min", text="Minimum")
  1381. box.prop(game, "velocity_max", text="Maximum")
  1382. @UI
  1383. class PANEL_Collision(bpy.types.Panel):
  1384. bl_space_type = 'VIEW_3D'
  1385. bl_region_type = 'UI'
  1386. bl_label = "Collision"
  1387. @classmethod
  1388. def poll(cls, context):
  1389. if context.active_object:
  1390. return True
  1391. else:
  1392. return False
  1393. def draw(self, context):
  1394. layout = self.layout
  1395. ob = context.active_object
  1396. game = ob.game
  1397. if ob.type != 'MESH':
  1398. return
  1399. elif ob.subcollision == True:
  1400. box = layout.box()
  1401. if ob.parent:
  1402. box.label(text='object is a collision proxy for: %s' %ob.parent.name)
  1403. else:
  1404. box.label(text='WARNING: collision proxy missing parent')
  1405. return
  1406. mode = ob.collision_mode
  1407. if mode == 'NONE':
  1408. box = layout.box()
  1409. op = box.operator( 'ogre.set_collision', text='Enable Collision', icon='PHYSICS' )
  1410. op.MODE = 'PRIMITIVE:%s' %game.collision_bounds_type
  1411. else:
  1412. prim = game.collision_bounds_type
  1413. box = layout.box()
  1414. op = box.operator( 'ogre.set_collision', text='Disable Collision', icon='X' )
  1415. op.MODE = 'NONE'
  1416. box.prop(game, "collision_margin", text="Collision Margin", slider=True)
  1417. box = layout.box()
  1418. if mode == 'PRIMITIVE':
  1419. box.label(text='Primitive: %s' %prim)
  1420. else:
  1421. box.label(text='Primitive')
  1422. row = box.row()
  1423. _icons = {
  1424. 'BOX':'MESH_CUBE', 'SPHERE':'MESH_UVSPHERE', 'CYLINDER':'MESH_CYLINDER',
  1425. 'CONE':'MESH_CONE', 'CAPSULE':'META_CAPSULE'}
  1426. for a in 'BOX SPHERE CYLINDER CONE CAPSULE'.split():
  1427. if prim == a and mode == 'PRIMITIVE':
  1428. op = row.operator( 'ogre.set_collision', text='', icon=_icons[a], emboss=True )
  1429. op.MODE = 'PRIMITIVE:%s' %a
  1430. else:
  1431. op = row.operator( 'ogre.set_collision', text='', icon=_icons[a], emboss=False )
  1432. op.MODE = 'PRIMITIVE:%s' %a
  1433. box = layout.box()
  1434. if mode == 'MESH': box.label(text='Mesh: %s' %prim.split('_')[0] )
  1435. else: box.label(text='Mesh')
  1436. row = box.row()
  1437. row.label(text='- - - - - - - - - - - - - -')
  1438. _icons = {'TRIANGLE_MESH':'MESH_ICOSPHERE', 'CONVEX_HULL':'SURFACE_NCURVE'}
  1439. for a in 'TRIANGLE_MESH CONVEX_HULL'.split():
  1440. if prim == a and mode == 'MESH':
  1441. op = row.operator( 'ogre.set_collision', text='', icon=_icons[a], emboss=True )
  1442. op.MODE = 'MESH:%s' %a
  1443. else:
  1444. op = row.operator( 'ogre.set_collision', text='', icon=_icons[a], emboss=False )
  1445. op.MODE = 'MESH:%s' %a
  1446. box = layout.box()
  1447. if mode == 'DECIMATED':
  1448. box.label(text='Decimate: %s' %prim.split('_')[0] )
  1449. row = box.row()
  1450. mod = _get_proxy_decimate_mod( ob )
  1451. assert mod # decimate modifier is missing
  1452. row.label(text='Faces: %s' %mod.face_count )
  1453. box.prop( mod, 'ratio', text='' )
  1454. else:
  1455. box.label(text='Decimate')
  1456. row = box.row()
  1457. row.label(text='- - - - - - - - - - - - - -')
  1458. _icons = {'TRIANGLE_MESH':'MESH_ICOSPHERE', 'CONVEX_HULL':'SURFACE_NCURVE'}
  1459. for a in 'TRIANGLE_MESH CONVEX_HULL'.split():
  1460. if prim == a and mode == 'DECIMATED':
  1461. op = row.operator( 'ogre.set_collision', text='', icon=_icons[a], emboss=True )
  1462. op.MODE = 'DECIMATED:%s' %a
  1463. else:
  1464. op = row.operator( 'ogre.set_collision', text='', icon=_icons[a], emboss=False )
  1465. op.MODE = 'DECIMATED:%s' %a
  1466. box = layout.box()
  1467. if mode == 'TERRAIN':
  1468. terrain = get_subcollisions( ob )[0]
  1469. if ob.collision_terrain_x_steps != terrain.collision_terrain_x_steps or ob.collision_terrain_y_steps != terrain.collision_terrain_y_steps:
  1470. op = box.operator( 'ogre.set_collision', text='Rebuild Terrain', icon='MESH_GRID' )
  1471. op.MODE = 'TERRAIN'
  1472. else:
  1473. box.label(text='Terrain:')
  1474. row = box.row()
  1475. row.prop( ob, 'collision_terrain_x_steps', 'X' )
  1476. row.prop( ob, 'collision_terrain_y_steps', 'Y' )
  1477. #box.prop( terrain.modifiers[0], 'offset' ) # gets normalized away
  1478. box.prop( terrain.modifiers[0], 'cull_face', text='Cull' )
  1479. box.prop( terrain, 'location' ) # TODO hide X and Y
  1480. else:
  1481. op = box.operator( 'ogre.set_collision', text='Terrain Collision', icon='MESH_GRID' )
  1482. op.MODE = 'TERRAIN'
  1483. box = layout.box()
  1484. if mode == 'COMPOUND':
  1485. op = box.operator( 'ogre.set_collision', text='Compound Collision', icon='ROTATECOLLECTION' )
  1486. else:
  1487. op = box.operator( 'ogre.set_collision', text='Compound Collision', icon='ROTATECOLLECTION' )
  1488. op.MODE = 'COMPOUND'
  1489. @UI
  1490. class PANEL_Configure(bpy.types.Panel):
  1491. bl_space_type = 'PROPERTIES'
  1492. bl_region_type = 'WINDOW'
  1493. bl_context = "scene"
  1494. bl_label = "Ogre Configuration File"
  1495. def draw(self, context):
  1496. layout = self.layout
  1497. op = layout.operator( 'ogre.save_config', text='update config file', icon='FILE' )
  1498. for tag in _CONFIG_TAGS_:
  1499. layout.prop( context.window_manager, tag )
  1500. ## Pop up dialog for various info/error messages
  1501. popup_message = ""
  1502. class PopUpDialogOperator(bpy.types.Operator):
  1503. bl_idname = "object.popup_dialog_operator"
  1504. bl_label = "blender2ogre"
  1505. def __init__(self):
  1506. print("dialog Start")
  1507. def __del__(self):
  1508. print("dialog End")
  1509. def execute(self, context):
  1510. print ("execute")
  1511. return {'RUNNING_MODAL'}
  1512. def draw(self, context):
  1513. # todo: Make this bigger and center on screen.
  1514. # Blender UI stuff seems quite complex, would
  1515. # think that showing a dialog with a message thath
  1516. # does not hide when mouse is moved would be simpler!
  1517. global popup_message
  1518. layout = self.layout
  1519. col = layout.column()
  1520. col.label(popup_message, 'ERROR')
  1521. def invoke(self, context, event):
  1522. wm = context.window_manager
  1523. wm.invoke_popup(self)
  1524. wm.modal_handler_add(self)
  1525. return {'RUNNING_MODAL'}
  1526. def modal(self, context, event):
  1527. # Close
  1528. if event.type == 'LEFTMOUSE':
  1529. print ("Left mouse")
  1530. return {'FINISHED'}
  1531. # Close
  1532. elif event.type in ('RIGHTMOUSE', 'ESC'):
  1533. print ("right mouse")
  1534. return {'FINISHED'}
  1535. print("running modal")
  1536. return {'RUNNING_MODAL'}
  1537. def show_dialog(message):
  1538. global popup_message
  1539. popup_message = message
  1540. bpy.ops.object.popup_dialog_operator('INVOKE_DEFAULT')
  1541. ## Game Logic Documentation
  1542. _game_logic_intro_doc_ = '''
  1543. Hijacking the BGE
  1544. Blender contains a fully functional game engine (BGE) that is highly useful for learning the concepts of game programming by breaking it down into three simple parts: Sensor, Controller, and Actuator. An Ogre based game engine will likely have similar concepts in its internal API and game logic scripting. Without a custom interface to define game logic, very often game designers may have to resort to having programmers implement their ideas in purely handwritten script. This is prone to breakage because object names then end up being hard-coded. Not only does this lead to non-reusable code, its also a slow process. Why should we have to resort to this when Blender already contains a very rich interface for game logic? By hijacking a subset of the BGE interface we can make this workflow between game designer and game programmer much better.
  1545. The OgreDocScene format can easily be extened to include extra game logic data. While the BGE contains some features that can not be easily mapped to other game engines, there are many are highly useful generic features we can exploit, including many of the Sensors and Actuators. Blender uses the paradigm of: 1. Sensor -> 2. Controller -> 3. Actuator. In pseudo-code, this can be thought of as: 1. on-event -> 2. conditional logic -> 3. do-action. The designer is most often concerned with the on-events (the Sensors), and the do-actions (the Actuators); and the BGE interface provides a clear way for defining and editing those. Its a harder task to provide a good interface for the conditional logic (Controller), that is flexible enough to fit everyones different Ogre engine and requirements, so that is outside the scope of this exporter at this time. A programmer will still be required to fill the gap between Sensor and Actuator, but hopefully his work is greatly reduced and can write more generic/reuseable code.
  1546. The rules for which Sensors trigger which Actuators is left undefined, as explained above we are hijacking the BGE interface not trying to export and reimplement everything. BGE Controllers and all links are ignored by the exporter, so whats the best way to define Sensor/Actuator relationships? One convention that seems logical is to group Sensors and Actuators by name. More complex syntax could be used in Sensor/Actuators names, or they could be completely ignored and instead all the mapping is done by the game programmer using other rules. This issue is not easily solved so designers and the engine programmers will have to decide upon their own conventions, there is no one size fits all solution.
  1547. '''
  1548. _ogre_logic_types_doc_ = '''
  1549. Supported Sensors:
  1550. . Collision
  1551. . Near
  1552. . Radar
  1553. . Touching
  1554. . Raycast
  1555. . Message
  1556. Supported Actuators:
  1557. . Shape Action*
  1558. . Edit Object
  1559. . Camera
  1560. . Constraint
  1561. . Message
  1562. . Motion
  1563. . Sound
  1564. . Visibility
  1565. *note: Shape Action
  1566. The most common thing a designer will want to do is have an event trigger an animation. The BGE contains an Actuator called "Shape Action", with useful properties like: start/end frame, and blending. It also contains a property called "Action" but this is hidden because the exporter ignores action names and instead uses the names of NLA strips when exporting Ogre animation tracks. The current workaround is to hijack the "Frame Property" attribute and change its name to "animation". The designer can then simply type the name of the animation track (NLA strip). Any custom syntax could actually be implemented here for calling animations, its up to the engine programmer to define how this field will be used. For example: "*.explode" could be implemented to mean "on all objects" play the "explode" animation.
  1567. '''
  1568. class _WrapLogic(object):
  1569. SwapName = { 'frame_property' : 'animation' } # custom name hacks
  1570. def __init__(self, node):
  1571. self.node = node
  1572. self.name = node.name
  1573. self.type = node.type
  1574. def widget(self, layout):
  1575. box = layout.box()
  1576. row = box.row()
  1577. row.label( text=self.type )
  1578. row.separator()
  1579. row.prop( self.node, 'name', text='' )
  1580. if self.type in self.TYPES:
  1581. for name in self.TYPES[ self.type ]:
  1582. if name in self.SwapName:
  1583. box.prop( self.node, name, text=self.SwapName[name] )
  1584. else:
  1585. box.prop( self.node, name )
  1586. def xml( self, doc ):
  1587. g = doc.createElement( self.LogicType )
  1588. g.setAttribute('name', self.name)
  1589. g.setAttribute('type', self.type)
  1590. if self.type in self.TYPES:
  1591. for name in self.TYPES[ self.type ]:
  1592. attr = getattr( self.node, name )
  1593. if name in self.SwapName: name = self.SwapName[name]
  1594. a = doc.createElement( 'component' )
  1595. g.appendChild(a)
  1596. a.setAttribute('name', name)
  1597. if attr is None: a.setAttribute('type', 'POINTER' )
  1598. else: a.setAttribute('type', type(attr).__name__)
  1599. if type(attr) in (float, int, str, bool): a.setAttribute('value', str(attr))
  1600. elif not attr: a.setAttribute('value', '') # None case
  1601. elif hasattr(attr,'filepath'): a.setAttribute('value', attr.filepath)
  1602. elif hasattr(attr,'name'): a.setAttribute('value', attr.name)
  1603. elif hasattr(attr,'x') and hasattr(attr,'y') and hasattr(attr,'z'):
  1604. a.setAttribute('value', '%s %s %s' %(attr.x, attr.y, attr.z))
  1605. else:
  1606. print('ERROR: unknown type', attr)
  1607. return g
  1608. class WrapSensor( _WrapLogic ):
  1609. LogicType = 'sensor'
  1610. TYPES = {
  1611. 'COLLISION': ['property'],
  1612. 'MESSAGE' : ['subject'],
  1613. 'NEAR' : ['property', 'distance', 'reset_distance'],
  1614. 'RADAR' : ['property', 'axis', 'angle', 'distance' ],
  1615. 'RAY' : ['ray_type', 'property', 'material', 'axis', 'range', 'use_x_ray'],
  1616. 'TOUCH' : ['material'],
  1617. }
  1618. class WrapActuator( _WrapLogic ):
  1619. LogicType = 'actuator'
  1620. TYPES = {
  1621. 'CAMERA' : ['object', 'height', 'min', 'max', 'axis'],
  1622. 'CONSTRAINT' : ['mode', 'limit', 'limit_min', 'limit_max', 'damping'],
  1623. 'MESSAGE' : ['to_property', 'subject', 'body_message'], #skipping body_type
  1624. 'OBJECT' : 'damping derivate_coefficient force force_max_x force_max_y force_max_z force_min_x force_min_y force_min_z integral_coefficient linear_velocity mode offset_location offset_rotation proportional_coefficient reference_object torque use_local_location use_local_rotation use_local_torque use_servo_limit_x use_servo_limit_y use_servo_limit_z'.split(),
  1625. 'SOUND' : 'cone_inner_angle_3d cone_outer_angle_3d cone_outer_gain_3d distance_3d_max distance_3d_reference gain_3d_max gain_3d_min mode pitch rolloff_factor_3d sound use_sound_3d volume'.split(), # note .sound contains .filepath
  1626. 'VISIBILITY' : 'apply_to_children use_occlusion use_visible'.split(),
  1627. 'SHAPE_ACTION' : 'frame_blend_in frame_end frame_property frame_start mode property use_continue_last_frame'.split(),
  1628. 'EDIT_OBJECT' : 'dynamic_operation linear_velocity mass mesh mode object time track_object use_3d_tracking use_local_angular_velocity use_local_linear_velocity use_replace_display_mesh use_replace_physics_mesh'.split(),
  1629. }
  1630. class _OgreMatPass( object ):
  1631. bl_space_type = 'PROPERTIES'
  1632. bl_region_type = 'WINDOW'
  1633. bl_context = "material"
  1634. @classmethod
  1635. def poll(cls, context):
  1636. if context.active_object and context.active_object.active_material and context.active_object.active_material.use_material_passes:
  1637. return True
  1638. def draw(self, context):
  1639. if not hasattr(context, "material"):
  1640. return
  1641. if not context.active_object:
  1642. return
  1643. if not context.active_object.active_material:
  1644. return
  1645. mat = context.material
  1646. ob = context.object
  1647. slot = context.material_slot
  1648. layout = self.layout
  1649. #layout.label(text=str(self.INDEX))
  1650. if mat.use_material_passes:
  1651. db = layout.box()
  1652. nodes = bpyShaders.get_or_create_material_passes( mat )
  1653. node = nodes[ self.INDEX ]
  1654. split = db.row()
  1655. if node.material: split.prop( node.material, 'use_in_ogre_material_pass', text='' )
  1656. split.prop( node, 'material' )
  1657. if not node.material:
  1658. op = split.operator( 'ogre.helper_create_attach_material_layer', icon="PLUS", text='' )
  1659. op.INDEX = self.INDEX
  1660. if node.material and node.material.use_in_ogre_material_pass:
  1661. dbb = db.box()
  1662. ogre_material_panel( dbb, node.material, parent=mat )
  1663. ogre_material_panel_extra( dbb, node.material )
  1664. class _create_new_material_layer_helper(bpy.types.Operator):
  1665. '''helper to create new material layer'''
  1666. bl_idname = "ogre.helper_create_attach_material_layer"
  1667. bl_label = "creates and assigns new material to layer"
  1668. bl_options = {'REGISTER'}
  1669. INDEX = IntProperty(name="material layer index", description="index", default=0, min=0, max=8)
  1670. @classmethod
  1671. def poll(cls, context):
  1672. if context.active_object and context.active_object.active_material and context.active_object.active_material.use_material_passes:
  1673. return True
  1674. def execute(self, context):
  1675. mat = context.active_object.active_material
  1676. nodes = bpyShaders.get_or_create_material_passes( mat )
  1677. node = nodes[ self.INDEX ]
  1678. node.material = bpy.data.materials.new( name='%s.LAYER%s'%(mat.name,self.INDEX) )
  1679. node.material.use_fixed_pipeline = False
  1680. node.material.offset_z = (self.INDEX*2) + 2 # nudge each pass by 2
  1681. return {'FINISHED'}
  1682. # UI panels continues
  1683. @UI
  1684. class PANEL_properties_window_ogre_material( bpy.types.Panel ):
  1685. bl_space_type = 'PROPERTIES'
  1686. bl_region_type = 'WINDOW'
  1687. bl_context = "material"
  1688. bl_label = "Ogre Material (base pass)"
  1689. @classmethod
  1690. def poll( self, context ):
  1691. if not hasattr(context, "material"): return False
  1692. if not context.active_object: return False
  1693. if not context.active_object.active_material: return False
  1694. return True
  1695. def draw(self, context):
  1696. mat = context.material
  1697. ob = context.object
  1698. slot = context.material_slot
  1699. layout = self.layout
  1700. if not mat.use_material_passes:
  1701. box = layout.box()
  1702. box.operator( 'ogre.force_setup_material_passes', text="Ogre Material Layers", icon='SCENE_DATA' )
  1703. ogre_material_panel( layout, mat )
  1704. ogre_material_panel_extra( layout, mat )
  1705. @UI
  1706. class MatPass1( _OgreMatPass, bpy.types.Panel ): INDEX = 0; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1707. @UI
  1708. class MatPass2( _OgreMatPass, bpy.types.Panel ): INDEX = 1; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1709. @UI
  1710. class MatPass3( _OgreMatPass, bpy.types.Panel ): INDEX = 2; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1711. @UI
  1712. class MatPass4( _OgreMatPass, bpy.types.Panel ): INDEX = 3; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1713. @UI
  1714. class MatPass5( _OgreMatPass, bpy.types.Panel ): INDEX = 4; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1715. @UI
  1716. class MatPass6( _OgreMatPass, bpy.types.Panel ): INDEX = 5; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1717. @UI
  1718. class MatPass7( _OgreMatPass, bpy.types.Panel ): INDEX = 6; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1719. @UI
  1720. class MatPass8( _OgreMatPass, bpy.types.Panel ): INDEX = 7; bl_label = "Ogre Material (pass%s)"%str(INDEX+1)
  1721. @UI
  1722. class PANEL_Textures(bpy.types.Panel):
  1723. bl_space_type = 'PROPERTIES'
  1724. bl_region_type = 'WINDOW'
  1725. bl_context = "texture"
  1726. bl_label = "Ogre Texture"
  1727. @classmethod
  1728. def poll(cls, context):
  1729. if not hasattr(context, "texture_slot"):
  1730. return False
  1731. else: return True
  1732. def draw(self, context):
  1733. #if not hasattr(context, "texture_slot"):
  1734. # return False
  1735. layout = self.layout
  1736. #idblock = context_tex_datablock(context)
  1737. slot = context.texture_slot
  1738. if not slot or not slot.texture:
  1739. return
  1740. btype = slot.blend_type # todo: fix this hack if/when slots support pyRNA
  1741. ex = False; texop = None
  1742. if btype in TextureUnit.colour_op:
  1743. if btype=='MIX' and slot.use_map_alpha and not slot.use_stencil:
  1744. if slot.diffuse_color_factor >= 1.0:
  1745. texop = 'alpha_blend'
  1746. else:
  1747. texop = TextureUnit.colour_op_ex[ btype ]
  1748. ex = True
  1749. elif btype=='MIX' and slot.use_map_alpha and slot.use_stencil:
  1750. texop = 'blend_current_alpha'; ex=True
  1751. elif btype=='MIX' and not slot.use_map_alpha and slot.use_stencil:
  1752. texop = 'blend_texture_alpha'; ex=True
  1753. else:
  1754. texop = TextureUnit.colour_op[ btype ]
  1755. elif btype in TextureUnit.colour_op_ex:
  1756. texop = TextureUnit.colour_op_ex[ btype ]
  1757. ex = True
  1758. box = layout.box()
  1759. row = box.row()
  1760. if texop:
  1761. if ex:
  1762. row.prop(slot, "blend_type", text=texop, icon='NEW')
  1763. else:
  1764. row.prop(slot, "blend_type", text=texop)
  1765. else:
  1766. row.prop(slot, "blend_type", text='(invalid option)')
  1767. if btype == 'MIX':
  1768. row.prop(slot, "use_stencil", text="")
  1769. row.prop(slot, "use_map_alpha", text="")
  1770. if texop == 'blend_manual':
  1771. row = box.row()
  1772. row.label(text="Alpha:")
  1773. row.prop(slot, "diffuse_color_factor", text="")
  1774. if hasattr(slot.texture, 'image') and slot.texture.image:
  1775. row = box.row()
  1776. n = '(invalid option)'
  1777. if slot.texture.extension in TextureUnit.tex_address_mode:
  1778. n = TextureUnit.tex_address_mode[ slot.texture.extension ]
  1779. row.prop(slot.texture, "extension", text=n)
  1780. if slot.texture.extension == 'CLIP':
  1781. row.prop(slot, "color", text="Border Color")
  1782. row = box.row()
  1783. if slot.texture_coords == 'UV':
  1784. row.prop(slot, "texture_coords", text="", icon='GROUP_UVS')
  1785. row.prop(slot, "uv_layer", text='Layer')
  1786. elif slot.texture_coords == 'REFLECTION':
  1787. row.prop(slot, "texture_coords", text="", icon='MOD_UVPROJECT')
  1788. n = '(invalid option)'
  1789. if slot.mapping in 'FLAT SPHERE'.split(): n = ''
  1790. row.prop(slot, "mapping", text=n)
  1791. else:
  1792. row.prop(slot, "texture_coords", text="(invalid mapping option)")
  1793. # Animation and offset options
  1794. split = layout.row()
  1795. box = split.box()
  1796. box.prop(slot, "offset", text="XY=offset, Z=rotation")
  1797. box = split.box()
  1798. box.prop(slot, "scale", text="XY=scale (Z ignored)")
  1799. box = layout.box()
  1800. row = box.row()
  1801. row.label(text='scrolling animation')
  1802. # Can't use if its enabled by default row.prop(slot, "use_map_density", text="")
  1803. row.prop(slot, "use_map_scatter", text="")
  1804. row = box.row()
  1805. row.prop(slot, "density_factor", text="X")
  1806. row.prop(slot, "emission_factor", text="Y")
  1807. box = layout.box()
  1808. row = box.row()
  1809. row.label(text='rotation animation')
  1810. row.prop(slot, "emission_color_factor", text="")
  1811. row.prop(slot, "use_from_dupli", text="")
  1812. ## Image magick
  1813. if hasattr(slot.texture, 'image') and slot.texture.image:
  1814. img = slot.texture.image
  1815. box = layout.box()
  1816. row = box.row()
  1817. row.prop( img, 'use_convert_format' )
  1818. if img.use_convert_format:
  1819. row.prop( img, 'convert_format' )
  1820. if img.convert_format == 'jpg':
  1821. box.prop( img, 'jpeg_quality' )
  1822. row = box.row()
  1823. row.prop( img, 'use_color_quantize', text='Reduce Colors' )
  1824. if img.use_color_quantize:
  1825. row.prop( img, 'use_color_quantize_dither', text='dither' )
  1826. row.prop( img, 'color_quantize', text='colors' )
  1827. row = box.row()
  1828. row.prop( img, 'use_resize_half' )
  1829. if not img.use_resize_half:
  1830. row.prop( img, 'use_resize_absolute' )
  1831. if img.use_resize_absolute:
  1832. row = box.row()
  1833. row.prop( img, 'resize_x' )
  1834. row.prop( img, 'resize_y' )
  1835. ## OgreMeshy
  1836. class OgreMeshyPreviewOp(bpy.types.Operator):
  1837. '''helper to open ogremeshy'''
  1838. bl_idname = 'ogremeshy.preview'
  1839. bl_label = "opens ogremeshy in a subprocess"
  1840. bl_options = {'REGISTER'}
  1841. preview = BoolProperty(name="preview", description="fast preview", default=True)
  1842. groups = BoolProperty(name="preview merge groups", description="use merge groups", default=False)
  1843. mesh = BoolProperty(name="update mesh", description="update mesh (disable for fast material preview", default=True)
  1844. @classmethod
  1845. def poll(cls, context):
  1846. if context.active_object and context.active_object.type in ('MESH','EMPTY') and context.mode != 'EDIT_MESH':
  1847. if context.active_object.type == 'EMPTY' and context.active_object.dupli_type != 'GROUP':
  1848. return False
  1849. else:
  1850. return True
  1851. def execute(self, context):
  1852. Report.reset()
  1853. Report.messages.append('running %s' %CONFIG['OGRE_MESHY'])
  1854. if sys.platform.startswith('linux'):
  1855. # If OgreMeshy ends with .exe, set the path for preview meshes to
  1856. # the user's wine directory, otherwise to /tmp.
  1857. if CONFIG['OGRE_MESHY'].endswith('.exe'):
  1858. path = '%s/.wine/drive_c/tmp' % os.environ['HOME']
  1859. else:
  1860. path = '/tmp'
  1861. elif sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
  1862. path = '/tmp'
  1863. else:
  1864. path = 'C:\\tmp'
  1865. mat = None
  1866. mgroup = merged = None
  1867. umaterials = []
  1868. if context.active_object.type == 'MESH':
  1869. mat = context.active_object.active_material
  1870. elif context.active_object.type == 'EMPTY': # assume group
  1871. obs = []
  1872. for e in context.selected_objects:
  1873. if e.type != 'EMPTY' and e.dupli_group: continue
  1874. grp = e.dupli_group
  1875. subs = []
  1876. for o in grp.objects:
  1877. if o.type=='MESH': subs.append( o )
  1878. if subs:
  1879. m = merge_objects( subs, transform=e.matrix_world )
  1880. obs.append( m )
  1881. if obs:
  1882. merged = merge_objects( obs )
  1883. umaterials = dot_mesh( merged, path=path, force_name='preview' )
  1884. for o in obs: context.scene.objects.unlink(o)
  1885. if not self.mesh:
  1886. for ob in context.selected_objects:
  1887. if ob.type == 'MESH':
  1888. for mat in ob.data.materials:
  1889. if mat and mat not in umaterials: umaterials.append( mat )
  1890. if not merged:
  1891. mgroup = MeshMagick.get_merge_group( context.active_object )
  1892. if not mgroup and self.groups:
  1893. group = get_merge_group( context.active_object )
  1894. if group:
  1895. print('--------------- has merge group ---------------' )
  1896. merged = merge_group( group )
  1897. else:
  1898. print('--------------- NO merge group ---------------' )
  1899. elif len(context.selected_objects)>1 and context.selected_objects:
  1900. merged = merge_objects( context.selected_objects )
  1901. if mgroup:
  1902. for ob in mgroup.objects:
  1903. nmats = dot_mesh( ob, path=path )
  1904. for m in nmats:
  1905. if m not in umaterials: umaterials.append( m )
  1906. MeshMagick.merge( mgroup, path=path, force_name='preview' )
  1907. elif merged:
  1908. umaterials = dot_mesh( merged, path=path, force_name='preview' )
  1909. else:
  1910. umaterials = dot_mesh( context.active_object, path=path, force_name='preview' )
  1911. if mat or umaterials:
  1912. #CONFIG['TOUCH_TEXTURES'] = True
  1913. #CONFIG['PATH'] = path # TODO deprecate
  1914. data = ''
  1915. for umat in umaterials:
  1916. data += generate_material( umat, path=path, copy_programs=True, touch_textures=True ) # copies shader programs to path
  1917. f=open( os.path.join( path, 'preview.material' ), 'wb' )
  1918. f.write( bytes(data,'utf-8') ); f.close()
  1919. if merged: context.scene.objects.unlink( merged )
  1920. if sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
  1921. if CONFIG['OGRE_MESHY'].endswith('.exe'):
  1922. cmd = ['wine', CONFIG['OGRE_MESHY'], 'c:\\tmp\\preview.mesh' ]
  1923. else:
  1924. cmd = [CONFIG['OGRE_MESHY'], '/tmp/preview.mesh']
  1925. print( cmd )
  1926. #subprocess.call(cmd)
  1927. subprocess.Popen(cmd)
  1928. else:
  1929. #subprocess.call([CONFIG_OGRE_MESHY, 'C:\\tmp\\preview.mesh'])
  1930. subprocess.Popen( [CONFIG['OGRE_MESHY'], 'C:\\tmp\\preview.mesh'] )
  1931. Report.show()
  1932. return {'FINISHED'}
  1933. ## Ogre Documentation to UI
  1934. _OGRE_DOCS_ = []
  1935. def ogredoc( cls ):
  1936. tag = cls.__name__.split('_ogredoc_')[-1]
  1937. cls.bl_label = tag.replace('_', ' ')
  1938. _OGRE_DOCS_.append( cls )
  1939. return cls
  1940. class INFO_MT_ogre_helper(bpy.types.Menu):
  1941. bl_label = '_overloaded_'
  1942. def draw(self, context):
  1943. layout = self.layout
  1944. #row = self.layout.box().split(percentage=0.05)
  1945. #col = row.column(align=False)
  1946. #print(dir(col))
  1947. #row.scale_x = 0.1
  1948. #row.alignment = 'RIGHT'
  1949. for line in self.mydoc.splitlines():
  1950. if line.strip():
  1951. for ww in wordwrap( line ): layout.label(text=ww)
  1952. layout.separator()
  1953. class INFO_MT_ogre_docs(bpy.types.Menu):
  1954. bl_label = "Ogre Help"
  1955. def draw(self, context):
  1956. layout = self.layout
  1957. for cls in _OGRE_DOCS_:
  1958. layout.menu( cls.__name__ )
  1959. layout.separator()
  1960. layout.separator()
  1961. layout.label(text='bug reports to: [email protected]')
  1962. class INFO_MT_ogre_shader_pass_attributes(bpy.types.Menu):
  1963. bl_label = "Shader-Pass"
  1964. def draw(self, context):
  1965. layout = self.layout
  1966. for cls in _OGRE_SHADER_REF_:
  1967. layout.menu( cls.__name__ )
  1968. class INFO_MT_ogre_shader_texture_attributes(bpy.types.Menu):
  1969. bl_label = "Shader-Texture"
  1970. def draw(self, context):
  1971. layout = self.layout
  1972. for cls in _OGRE_SHADER_REF_TEX_:
  1973. layout.menu( cls.__name__ )
  1974. @ogredoc
  1975. class _ogredoc_Installing( INFO_MT_ogre_helper ):
  1976. mydoc = _doc_installing_
  1977. @ogredoc
  1978. class _ogredoc_FAQ( INFO_MT_ogre_helper ):
  1979. mydoc = _faq_
  1980. @ogredoc
  1981. class _ogredoc_Animation_System( INFO_MT_ogre_helper ):
  1982. mydoc = '''
  1983. Armature Animation System | OgreDotSkeleton
  1984. Quick Start:
  1985. 1. select your armature and set a single keyframe on the object (loc,rot, or scl)
  1986. . note, this step is just a hack for creating an action so you can then create an NLA track.
  1987. . do not key in pose mode, unless you want to only export animation on the keyed bones.
  1988. 2. open the NLA, and convert the action into an NLA strip
  1989. 3. name the NLA strip(s)
  1990. 4. set the in and out frames for each strip ( the strip name becomes the Ogre track name )
  1991. How it Works:
  1992. The NLA strips can be blank, they are only used to define Ogre track names, and in and out frame ranges. You are free to animate the armature with constraints (no baking required), or you can used baked animation and motion capture. Blending that is driven by the NLA is also supported, if you don't want blending, put space between each strip.
  1993. The OgreDotSkeleton (.skeleton) format supports multiple named tracks that can contain some or all of the bones of an armature. This feature can be exploited by a game engine for segmenting and animation blending. For example: lets say we want to animate the upper torso independently of the lower body while still using a single armature. This can be done by hijacking the NLA of the armature.
  1994. Advanced NLA Hijacking (selected-bones-animation):
  1995. . define an action and keyframe only the bones you want to 'group', ie. key all the upper torso bones
  1996. . import the action into the NLA
  1997. . name the strip (this becomes the track name in Ogre)
  1998. . adjust the start and end frames of each strip
  1999. ( you may use multiple NLA tracks, multiple strips per-track is ok, and strips may overlap in time )
  2000. '''
  2001. @ogredoc
  2002. class _ogredoc_Physics( INFO_MT_ogre_helper ):
  2003. mydoc = '''
  2004. Ogre Dot Scene + BGE Physics
  2005. extended format including external collision mesh, and BGE physics settings
  2006. <node name="...">
  2007. <entity name="..." meshFile="..." collisionFile="..." collisionPrim="..." [and all BGE physics attributes] />
  2008. </node>
  2009. collisionFile : sets path to .mesh that is used for collision (ignored if collisionPrim is set)
  2010. collisionPrim : sets optimal collision type [ cube, sphere, capsule, cylinder ]
  2011. *these collisions are static meshes, animated deforming meshes should give the user a warning that they have chosen a static mesh collision type with an object that has an armature
  2012. Blender Collision Setup:
  2013. 1. If a mesh object has a child mesh with a name starting with 'collision', then the child becomes the collision mesh for the parent mesh.
  2014. 2. If 'Collision Bounds' game option is checked, the bounds type [box, sphere, etc] is used. This will override above rule.
  2015. 3. Instances (and instances generated by optimal array modifier) will share the same collision type of the first instance, you DO NOT need to set the collision type for each instance.
  2016. '''
  2017. @ogredoc
  2018. class _ogredoc_Bugs( INFO_MT_ogre_helper ):
  2019. mydoc = '''
  2020. Known Issues:
  2021. . shape animation breaks when using modifiers that change the vertex count
  2022. (Any modifier that changes the vertex count is bad with shape anim or armature anim)
  2023. . never rename the nodes created by enabling Ogre-Material-Layers
  2024. . never rename collision proxy meshes created by the Collision Panel
  2025. . lighting in Tundra is not excatly the same as in Blender
  2026. Tundra Streaming:
  2027. . only supports streaming transform of up to 10 objects selected objects
  2028. . the 3D view must be shown at the time you open Tundra
  2029. . the same 3D view must be visible to stream data to Tundra
  2030. . only position and scale are updated, a bug on the Tundra side prevents rotation update
  2031. . animation playback is broken if you rename your NLA strips after opening Tundra
  2032. '''
  2033. # Ogre v1.7 Doc
  2034. def _mesh_entity_helper( doc, ob, o ):
  2035. ## extended format - BGE Physics ##
  2036. o.setAttribute('mass', str(ob.game.mass))
  2037. o.setAttribute('mass_radius', str(ob.game.radius))
  2038. o.setAttribute('physics_type', ob.game.physics_type)
  2039. o.setAttribute('actor', str(ob.game.use_actor))
  2040. o.setAttribute('ghost', str(ob.game.use_ghost))
  2041. o.setAttribute('velocity_min', str(ob.game.velocity_min))
  2042. o.setAttribute('velocity_max', str(ob.game.velocity_max))
  2043. o.setAttribute('lock_trans_x', str(ob.game.lock_location_x))
  2044. o.setAttribute('lock_trans_y', str(ob.game.lock_location_y))
  2045. o.setAttribute('lock_trans_z', str(ob.game.lock_location_z))
  2046. o.setAttribute('lock_rot_x', str(ob.game.lock_rotation_x))
  2047. o.setAttribute('lock_rot_y', str(ob.game.lock_rotation_y))
  2048. o.setAttribute('lock_rot_z', str(ob.game.lock_rotation_z))
  2049. o.setAttribute('anisotropic_friction', str(ob.game.use_anisotropic_friction))
  2050. x,y,z = ob.game.friction_coefficients
  2051. o.setAttribute('friction_x', str(x))
  2052. o.setAttribute('friction_y', str(y))
  2053. o.setAttribute('friction_z', str(z))
  2054. o.setAttribute('damping_trans', str(ob.game.damping))
  2055. o.setAttribute('damping_rot', str(ob.game.rotation_damping))
  2056. o.setAttribute('inertia_tensor', str(ob.game.form_factor))
  2057. mesh = ob.data
  2058. # custom user props
  2059. for prop in mesh.items():
  2060. propname, propvalue = prop
  2061. if not propname.startswith('_'):
  2062. user = doc.createElement('user_data')
  2063. o.appendChild( user )
  2064. user.setAttribute( 'name', propname )
  2065. user.setAttribute( 'value', str(propvalue) )
  2066. user.setAttribute( 'type', type(propvalue).__name__ )
  2067. #class _type(bpy.types.IDPropertyGroup):
  2068. # name = StringProperty(name="jpeg format", description="", maxlen=64, default="")
  2069. def get_lights_by_type( T ):
  2070. r = []
  2071. for ob in bpy.context.scene.objects:
  2072. if ob.type=='LAMP':
  2073. if ob.data.type==T: r.append( ob )
  2074. return r
  2075. class _TXML_(object):
  2076. '''
  2077. <component type="EC_Script" sync="1" name="myscript">
  2078. <attribute value="" name="Script ref"/>
  2079. <attribute value="false" name="Run on load"/>
  2080. <attribute value="0" name="Run mode"/>
  2081. <attribute value="" name="Script application name"/>
  2082. <attribute value="" name="Script class name"/>
  2083. </component>
  2084. '''
  2085. def create_tundra_document( self, context ):
  2086. # todo: Make a way in the gui to give prefix for the refs
  2087. # This can be very useful if you want to give deployment URL
  2088. # eg. "http://www.myassets.com/myscene/". By default this needs
  2089. # to be an empty string, it will operate best for local preview
  2090. # and importing the scene content to existing scenes with relative refs.
  2091. proto = ''
  2092. doc = RDocument()
  2093. scn = doc.createElement('scene')
  2094. doc.appendChild( scn )
  2095. # EC_Script
  2096. if 0: # todo: tundra bug (what does this mean?)
  2097. e = doc.createElement( 'entity' )
  2098. doc.documentElement.appendChild( e )
  2099. e.setAttribute('id', len(doc.documentElement.childNodes)+1 )
  2100. c = doc.createElement( 'component' ); e.appendChild( c )
  2101. c.setAttribute( 'type', 'EC_Script' )
  2102. c.setAttribute( 'sync', '1' )
  2103. c.setAttribute( 'name', 'myscript' )
  2104. a = doc.createElement('attribute'); c.appendChild( a )
  2105. a.setAttribute('name', 'Script ref')
  2106. #a.setAttribute('value', "%s%s"%(proto,TUNDRA_GEN_SCRIPT_PATH) )
  2107. a = doc.createElement('attribute'); c.appendChild( a )
  2108. a.setAttribute('name', 'Run on load')
  2109. a.setAttribute('value', 'true' )
  2110. a = doc.createElement('attribute'); c.appendChild( a )
  2111. a.setAttribute('name', 'Run mode')
  2112. a.setAttribute('value', '0' )
  2113. a = doc.createElement('attribute'); c.appendChild( a )
  2114. a.setAttribute('name', 'Script application name')
  2115. a.setAttribute('value', 'blender2ogre' )
  2116. # Check lighting settings
  2117. sun = hemi = None
  2118. if get_lights_by_type('SUN'):
  2119. sun = get_lights_by_type('SUN')[0]
  2120. if get_lights_by_type('HEMI'):
  2121. hemi = get_lights_by_type('HEMI')[0]
  2122. # Environment
  2123. if bpy.context.scene.world.mist_settings.use_mist or sun or hemi:
  2124. # Entity for environment components
  2125. e = doc.createElement( 'entity' )
  2126. doc.documentElement.appendChild( e )
  2127. e.setAttribute('id', len(doc.documentElement.childNodes)+1 )
  2128. # EC_Fog
  2129. c = doc.createElement( 'component' ); e.appendChild( c )
  2130. c.setAttribute( 'type', 'EC_Fog' )
  2131. c.setAttribute( 'sync', '1' )
  2132. c.setAttribute( 'name', 'Fog' )
  2133. a = doc.createElement('attribute'); c.appendChild( a )
  2134. a.setAttribute('name', 'Color')
  2135. if bpy.context.scene.world.mist_settings.use_mist:
  2136. A = bpy.context.scene.world.mist_settings.intensity
  2137. R,G,B = bpy.context.scene.world.horizon_color
  2138. a.setAttribute('value', '%s %s %s %s'%(R,G,B,A))
  2139. else:
  2140. a.setAttribute('value', '0.4 0.4 0.4 1.0')
  2141. if bpy.context.scene.world.mist_settings.use_mist:
  2142. mist = bpy.context.scene.world.mist_settings
  2143. a = doc.createElement('attribute'); c.appendChild( a )
  2144. a.setAttribute('name', 'Start distance')
  2145. a.setAttribute('value', mist.start)
  2146. a = doc.createElement('attribute'); c.appendChild( a )
  2147. a.setAttribute('name', 'End distance')
  2148. a.setAttribute('value', mist.start+mist.depth)
  2149. a = doc.createElement('attribute'); c.appendChild( a )
  2150. a.setAttribute('name', 'Exponential density')
  2151. a.setAttribute('value', 0.001)
  2152. # EC_EnvironmentLight
  2153. c = doc.createElement( 'component' ); e.appendChild( c )
  2154. c.setAttribute( 'type', 'EC_EnvironmentLight' )
  2155. c.setAttribute( 'sync', '1' )
  2156. c.setAttribute( 'name', 'Environment Light' )
  2157. a = doc.createElement('attribute'); c.appendChild( a )
  2158. a.setAttribute('name', 'Sunlight color')
  2159. if sun:
  2160. R,G,B = sun.data.color
  2161. a.setAttribute('value', '%s %s %s 1' %(R,G,B))
  2162. else:
  2163. a.setAttribute('value', '0 0 0 1')
  2164. a = doc.createElement('attribute'); c.appendChild( a )
  2165. a.setAttribute('name', 'Brightness') # brightness of sunlight
  2166. if sun:
  2167. a.setAttribute('value', sun.data.energy*10) # 10=magic
  2168. else:
  2169. a.setAttribute('value', '0')
  2170. a = doc.createElement('attribute'); c.appendChild( a )
  2171. a.setAttribute('name', 'Ambient light color')
  2172. if hemi:
  2173. R,G,B = hemi.data.color * hemi.data.energy * 3.0
  2174. if R>1.0: R=1.0
  2175. if G>1.0: G=1.0
  2176. if B>1.0: B=1.0
  2177. a.setAttribute('value', '%s %s %s 1' %(R,G,B))
  2178. else:
  2179. a.setAttribute('value', '0 0 0 1')
  2180. a = doc.createElement('attribute'); c.appendChild( a )
  2181. a.setAttribute('name', 'Sunlight direction vector')
  2182. a.setAttribute('value', '-0.25 -1.0 -0.25') # TODO, get the sun rotation from blender
  2183. a = doc.createElement('attribute'); c.appendChild( a )
  2184. a.setAttribute('name', 'Sunlight cast shadows')
  2185. a.setAttribute('value', 'true')
  2186. # EC_SkyX
  2187. if context.scene.world.ogre_skyX:
  2188. c = doc.createElement( 'component' ); e.appendChild( c )
  2189. c.setAttribute( 'type', 'EC_SkyX' )
  2190. c.setAttribute( 'sync', '1' )
  2191. c.setAttribute( 'name', 'SkyX' )
  2192. a = doc.createElement('attribute'); a.setAttribute('name', 'Weather (volumetric clouds only)')
  2193. den = (
  2194. context.scene.world.ogre_skyX_cloud_density_x,
  2195. context.scene.world.ogre_skyX_cloud_density_y
  2196. )
  2197. a.setAttribute('value', '%s %s' %den)
  2198. c.appendChild( a )
  2199. config = (
  2200. ('time', 'Time multiplier'),
  2201. ('volumetric_clouds','Volumetric clouds'),
  2202. ('wind','Wind direction'),
  2203. )
  2204. for bname, aname in config:
  2205. a = doc.createElement('attribute')
  2206. a.setAttribute('name', aname)
  2207. s = str( getattr(context.scene.world, 'ogre_skyX_'+bname) )
  2208. a.setAttribute('value', s.lower())
  2209. c.appendChild( a )
  2210. return doc
  2211. # Creates new Tundra entity
  2212. def tundra_entity( self, doc, ob, path='/tmp', collision_proxies=[], parent=None, matrix=None,visible=True ):
  2213. assert not ob.subcollision
  2214. # Tundra TRANSFORM
  2215. if not matrix:
  2216. matrix = ob.matrix_world.copy()
  2217. # todo: Make a way in the gui to give prefix for the refs
  2218. # This can be very useful if you want to give deployment URL
  2219. # eg. "http://www.myassets.com/myscene/". By default this needs
  2220. # to be an empty string, it will operate best for local preview
  2221. # and importing the scene content to existing scenes with relative refs.
  2222. proto = ''
  2223. # Entity
  2224. entityid = uid(ob)
  2225. print(" Creating Tundra Enitity with ID", entityid)
  2226. e = doc.createElement( 'entity' )
  2227. doc.documentElement.appendChild( e )
  2228. e.setAttribute('id', entityid)
  2229. # EC_Name
  2230. print (" - EC_Name with", ob.name)
  2231. c = doc.createElement('component'); e.appendChild( c )
  2232. c.setAttribute('type', "EC_Name")
  2233. c.setAttribute('sync', '1')
  2234. a = doc.createElement('attribute'); c.appendChild(a)
  2235. a.setAttribute('name', "name" )
  2236. a.setAttribute('value', ob.name )
  2237. a = doc.createElement('attribute'); c.appendChild(a)
  2238. a.setAttribute('name', "description" )
  2239. a.setAttribute('value', "" )
  2240. # EC_Placeable
  2241. print (" - EC_Placeable ")
  2242. c = doc.createElement('component'); e.appendChild( c )
  2243. c.setAttribute('type', "EC_Placeable")
  2244. c.setAttribute('sync', '1')
  2245. a = doc.createElement('attribute'); c.appendChild(a)
  2246. a.setAttribute('name', "Transform" )
  2247. x,y,z = swap(matrix.to_translation())
  2248. loc = '%6f,%6f,%6f' %(x,y,z)
  2249. x,y,z = swap(matrix.to_euler())
  2250. x = math.degrees( x ); y = math.degrees( y ); z = math.degrees( z )
  2251. if ob.type == 'CAMERA':
  2252. x -= 90
  2253. elif ob.type == 'LAMP':
  2254. x += 90
  2255. rot = '%6f,%6f,%6f' %(x,y,z)
  2256. x,y,z = swap(matrix.to_scale())
  2257. scl = '%6f,%6f,%6f' %(abs(x),abs(y),abs(z)) # Tundra2 clamps any negative to zero
  2258. a.setAttribute('value', "%s,%s,%s" %(loc,rot,scl) )
  2259. a = doc.createElement('attribute'); c.appendChild(a)
  2260. a.setAttribute('name', "Show bounding box" )
  2261. a.setAttribute('value', "false" )
  2262. # Don't mark bounding boxes to show in Tundra!
  2263. #if ob.show_bounds or ob.type != 'MESH':
  2264. # a.setAttribute('value', "true" )
  2265. #else:
  2266. # a.setAttribute('value', "false" )
  2267. a = doc.createElement('attribute'); c.appendChild(a)
  2268. a.setAttribute('name', "Visible" )
  2269. if visible:
  2270. a.setAttribute('value', 'true') # overrides children's setting - not good!
  2271. else:
  2272. a.setAttribute('value', 'false')
  2273. a = doc.createElement('attribute'); c.appendChild(a)
  2274. a.setAttribute('name', "Selection layer" )
  2275. a.setAttribute('value', 1)
  2276. # Tundra parenting to EC_Placeable.
  2277. # todo: Verify this inserts correct ent name or id here.
  2278. # <attribute value="" name="Parent entity ref"/>
  2279. # <attribute value="" name="Parent bone name"/>
  2280. if parent:
  2281. a = doc.createElement('attribute'); c.appendChild(a)
  2282. a.setAttribute('name', "Parent entity ref" )
  2283. a.setAttribute('value', parent)
  2284. if ob.type != 'MESH':
  2285. c = doc.createElement('component'); e.appendChild( c )
  2286. c.setAttribute('type', 'EC_Name')
  2287. c.setAttribute('sync', '1')
  2288. a = doc.createElement('attribute'); c.appendChild(a)
  2289. a.setAttribute('name', "name" )
  2290. a.setAttribute('value', ob.name)
  2291. # EC_Sound: Supports wav and ogg
  2292. if ob.type == 'SPEAKER':
  2293. print (" - EC_Sound")
  2294. c = doc.createElement('component'); e.appendChild( c )
  2295. c.setAttribute('type', 'EC_Sound')
  2296. c.setAttribute('sync', '1')
  2297. if ob.data.sound:
  2298. abspath = bpy.path.abspath( ob.data.sound.filepath )
  2299. soundpath, soundfile = os.path.split( abspath )
  2300. soundref = "%s%s" % (proto, soundfile)
  2301. print (" Sounds ref:", soundref)
  2302. a = doc.createElement('attribute'); c.appendChild(a)
  2303. a.setAttribute('name', 'Sound ref' )
  2304. a.setAttribute('value', soundref)
  2305. if not os.path.isfile( os.path.join(path,soundfile) ):
  2306. open( os.path.join(path,soundfile), 'wb' ).write( open(abspath,'rb').read() )
  2307. a = doc.createElement('attribute'); c.appendChild(a)
  2308. a.setAttribute('name', 'Sound radius inner' )
  2309. a.setAttribute('value', ob.data.cone_angle_inner)
  2310. a = doc.createElement('attribute'); c.appendChild(a)
  2311. a.setAttribute('name', 'Sound radius outer' )
  2312. a.setAttribute('value', ob.data.cone_angle_outer)
  2313. a = doc.createElement('attribute'); c.appendChild(a)
  2314. a.setAttribute('name', 'Sound gain' )
  2315. a.setAttribute('value', ob.data.volume)
  2316. a = doc.createElement('attribute'); c.appendChild(a)
  2317. a.setAttribute('name', 'Play on load' )
  2318. if ob.data.play_on_load:
  2319. a.setAttribute('value', 'true')
  2320. else:
  2321. a.setAttribute('value', 'false')
  2322. a = doc.createElement('attribute'); c.appendChild(a)
  2323. a.setAttribute('name', 'Loop sound' )
  2324. if ob.data.loop:
  2325. a.setAttribute('value', 'true')
  2326. else:
  2327. a.setAttribute('value', 'false')
  2328. a = doc.createElement('attribute'); c.appendChild(a)
  2329. a.setAttribute('name', 'Spatial' )
  2330. if ob.data.use_spatial:
  2331. a.setAttribute('value', 'true')
  2332. else:
  2333. a.setAttribute('value', 'false')
  2334. # EC_Camera
  2335. ''' todo: This is really not very helpful. Apps define
  2336. camera logic in Tundra. By default you will have
  2337. a freecamera to move around the scene etc. This created
  2338. camera wont be activated except if a script does so.
  2339. Best leave camera (creation) logic for the inworld apps.
  2340. At least remove the default "export cameras" for txml. '''
  2341. if ob.type == 'CAMERA':
  2342. print (" - EC_Camera")
  2343. c = doc.createElement('component'); e.appendChild( c )
  2344. c.setAttribute('type', 'EC_Camera')
  2345. c.setAttribute('sync', '1')
  2346. a = doc.createElement('attribute'); c.appendChild(a)
  2347. a.setAttribute('name', "Up vector" )
  2348. a.setAttribute('value', '0.0 1.0 0.0')
  2349. a = doc.createElement('attribute'); c.appendChild(a)
  2350. a.setAttribute('name', "Near plane" )
  2351. a.setAttribute('value', '0.01')
  2352. a = doc.createElement('attribute'); c.appendChild(a)
  2353. a.setAttribute('name', "Far plane" )
  2354. a.setAttribute('value', '2000')
  2355. a = doc.createElement('attribute'); c.appendChild(a)
  2356. a.setAttribute('name', "Vertical FOV" )
  2357. a.setAttribute('value', '45')
  2358. a = doc.createElement('attribute'); c.appendChild(a)
  2359. a.setAttribute('name', "Aspect ratio" )
  2360. a.setAttribute('value', '')
  2361. NTF = None
  2362. # EC_Rigidbody
  2363. # Any object can have physics, although it needs
  2364. # EC_Placeable to have position etc.
  2365. if ob.physics_mode != 'NONE' or ob.collision_mode != 'NONE':
  2366. TundraTypes = {
  2367. 'BOX' : 0,
  2368. 'SPHERE' : 1,
  2369. 'CYLINDER' : 2,
  2370. 'CONE' : 0, # Missing in Tundra
  2371. 'CAPSULE' : 3,
  2372. 'TRIANGLE_MESH' : 4,
  2373. #'HEIGHT_FIELD': 5, # Missing in Blender
  2374. 'CONVEX_HULL' : 6
  2375. }
  2376. com = doc.createElement('component'); e.appendChild( com )
  2377. com.setAttribute('type', 'EC_RigidBody')
  2378. com.setAttribute('sync', '1')
  2379. # Mass
  2380. # * Does not affect static collision types (TriMesh and ConvexHull)
  2381. # * You can have working collisions with mass 0
  2382. a = doc.createElement('attribute'); com.appendChild( a )
  2383. a.setAttribute('name', 'Mass')
  2384. if ob.physics_mode == 'RIGID_BODY':
  2385. a.setAttribute('value', ob.game.mass)
  2386. else:
  2387. a.setAttribute('value', '0.0')
  2388. SHAPE = a = doc.createElement('attribute'); com.appendChild( a )
  2389. a.setAttribute('name', 'Shape type')
  2390. a.setAttribute('value', TundraTypes[ ob.game.collision_bounds_type ] )
  2391. print (" - EC_RigidBody with shape type", TundraTypes[ob.game.collision_bounds_type])
  2392. M = ob.game.collision_margin
  2393. a = doc.createElement('attribute'); com.appendChild( a )
  2394. a.setAttribute('name', 'Size')
  2395. if ob.game.collision_bounds_type in 'TRIANGLE_MESH CONVEX_HULL'.split():
  2396. a.setAttribute('value', '%s %s %s' %(1.0+M, 1.0+M, 1.0+M) )
  2397. else:
  2398. #x,y,z = swap(ob.matrix_world.to_scale())
  2399. x,y,z = swap(ob.dimensions)
  2400. a.setAttribute('value', '%s %s %s' %(abs(x)+M,abs(y)+M,abs(z)+M) )
  2401. a = doc.createElement('attribute'); com.appendChild( a )
  2402. a.setAttribute('name', 'Collision mesh ref')
  2403. #if ob.game.use_collision_compound:
  2404. if ob.collision_mode == 'DECIMATED':
  2405. proxy = None
  2406. for child in ob.children:
  2407. if child.subcollision and child.name.startswith('DECIMATED'):
  2408. proxy = child; break
  2409. if proxy:
  2410. collisionref = "%s_collision_%s.mesh" % (proto, proxy.data.name)
  2411. a.setAttribute('value', collisionref)
  2412. if proxy not in collision_proxies:
  2413. collision_proxies.append( proxy )
  2414. else:
  2415. print('[WARNINIG]: Collision proxy mesh not found' )
  2416. assert 0
  2417. elif ob.collision_mode == 'TERRAIN':
  2418. NTF = save_terrain_as_NTF( path, ob )
  2419. SHAPE.setAttribute( 'value', '5' ) # HEIGHT_FIELD
  2420. elif ob.type == 'MESH':
  2421. # todo: Remove this. There is no need to set mesh collision ref
  2422. # if TriMesh or ConvexHull is used, it will be auto picked from EC_Mesh
  2423. # in the same Entity.
  2424. collisionref = "%s%s.mesh" % (proto, ob.data.name)
  2425. a.setAttribute('value', collisionref)
  2426. a = doc.createElement('attribute'); com.appendChild( a )
  2427. a.setAttribute('name', 'Friction')
  2428. #avg = sum( ob.game.friction_coefficients ) / 3.0
  2429. a.setAttribute('value', ob.physics_friction)
  2430. a = doc.createElement('attribute'); com.appendChild( a )
  2431. a.setAttribute('name', 'Restitution')
  2432. a.setAttribute('value', ob.physics_bounce)
  2433. a = doc.createElement('attribute'); com.appendChild( a )
  2434. a.setAttribute('name', 'Linear damping')
  2435. a.setAttribute('value', ob.game.damping)
  2436. a = doc.createElement('attribute'); com.appendChild( a )
  2437. a.setAttribute('name', 'Angular damping')
  2438. a.setAttribute('value', ob.game.rotation_damping)
  2439. a = doc.createElement('attribute'); com.appendChild( a )
  2440. a.setAttribute('name', 'Linear factor')
  2441. a.setAttribute('value', '1.0 1.0 1.0')
  2442. a = doc.createElement('attribute'); com.appendChild( a )
  2443. a.setAttribute('name', 'Angular factor')
  2444. a.setAttribute('value', '1.0 1.0 1.0')
  2445. a = doc.createElement('attribute'); com.appendChild( a )
  2446. a.setAttribute('name', 'Kinematic')
  2447. a.setAttribute('value', 'false' )
  2448. # todo: Find out what Phantom actually means and if this
  2449. # needs to be set for NONE collision rigids. I don't actually
  2450. # see any reason to make EC_RigidBody if collision is NONE
  2451. a = doc.createElement('attribute'); com.appendChild( a )
  2452. a.setAttribute('name', 'Phantom')
  2453. if ob.collision_mode == 'NONE':
  2454. a.setAttribute('value', 'true' )
  2455. else:
  2456. a.setAttribute('value', 'false' )
  2457. a = doc.createElement('attribute'); com.appendChild( a )
  2458. a.setAttribute('name', 'Draw Debug')
  2459. a.setAttribute('value', 'false' )
  2460. # Never mark rigids to have draw debug, it can
  2461. # be toggled in tundra for visual debugging.
  2462. #if ob.collision_mode == 'NONE':
  2463. # a.setAttribute('value', 'false' )
  2464. #else:
  2465. # a.setAttribute('value', 'true' )
  2466. a = doc.createElement('attribute'); com.appendChild( a )
  2467. a.setAttribute('name', 'Linear velocity')
  2468. a.setAttribute('value', '0.0 0.0 0.0')
  2469. a = doc.createElement('attribute'); com.appendChild( a )
  2470. a.setAttribute('name', 'Angular velocity')
  2471. a.setAttribute('value', '0.0 0.0 0.0')
  2472. a = doc.createElement('attribute'); com.appendChild( a )
  2473. a.setAttribute('name', 'Collision Layer')
  2474. a.setAttribute('value', -1)
  2475. a = doc.createElement('attribute'); com.appendChild( a )
  2476. a.setAttribute('name', 'Collision Mask')
  2477. a.setAttribute('value', -1)
  2478. # EC_Terrain
  2479. if NTF:
  2480. xp = NTF['xpatches']
  2481. yp = NTF['ypatches']
  2482. depth = NTF['depth']
  2483. print (" - EC_Terrain")
  2484. com = doc.createElement('component'); e.appendChild( com )
  2485. com.setAttribute('type', 'EC_Terrain')
  2486. com.setAttribute('sync', '1')
  2487. a = doc.createElement('attribute'); com.appendChild( a )
  2488. a.setAttribute('name', 'Transform')
  2489. x,y,z = ob.dimensions
  2490. sx,sy,sz = ob.scale
  2491. x *= 1.0/sx
  2492. y *= 1.0/sy
  2493. z *= 1.0/sz
  2494. #trans = '%s,%s,%s,' %(-xp/4, -z/2, -yp/4)
  2495. trans = '%s,%s,%s,' %(-xp/4, -depth, -yp/4)
  2496. # scaling in Tundra happens after translation
  2497. nx = x/(xp*16)
  2498. ny = y/(yp*16)
  2499. trans += '0,0,0,%s,%s,%s' %(nx,depth, ny)
  2500. a.setAttribute('value', trans )
  2501. a = doc.createElement('attribute'); com.appendChild( a )
  2502. a.setAttribute('name', 'Grid Width')
  2503. a.setAttribute('value', xp)
  2504. a = doc.createElement('attribute'); com.appendChild( a )
  2505. a.setAttribute('name', 'Grid Height')
  2506. a.setAttribute('value', yp)
  2507. a = doc.createElement('attribute'); com.appendChild( a )
  2508. a.setAttribute('name', 'Tex. U scale')
  2509. a.setAttribute('value', 1.0)
  2510. a = doc.createElement('attribute'); com.appendChild( a )
  2511. a.setAttribute('name', 'Tex. V scale')
  2512. a.setAttribute('value', 1.0)
  2513. a = doc.createElement('attribute'); com.appendChild( a )
  2514. a.setAttribute('name', 'Material')
  2515. a.setAttribute('value', '')
  2516. for i in range(4):
  2517. a = doc.createElement('attribute'); com.appendChild( a )
  2518. a.setAttribute('name', 'Texture %s' %i)
  2519. a.setAttribute('value', '')
  2520. # todo: Check that NTF['name'] is the actual valid asset ref
  2521. # and not the disk path.
  2522. heightmapref = "%s%s" % (proto, NTF['name'])
  2523. print (" Heightmap ref:", heightmapref)
  2524. a = doc.createElement('attribute'); com.appendChild( a )
  2525. a.setAttribute('name', 'Heightmap')
  2526. a.setAttribute('value', heightmapref )
  2527. # Enitity XML generation done, return the element.
  2528. return e
  2529. # EC_Mesh
  2530. def tundra_mesh( self, e, ob, url, exported_meshes ):
  2531. # todo: Make a way in the gui to give prefix for the refs
  2532. # This can be very useful if you want to give deployment URL
  2533. # eg. "http://www.myassets.com/myscene/". By default this needs
  2534. # to be an empty string, it will operate best for local preview
  2535. # and importing the scene content to existing scenes with relative refs.
  2536. proto = ''
  2537. meshref = "%s%s.mesh" % (proto, ob.data.name)
  2538. print (" - EC_Mesh")
  2539. print (" - Mesh ref:", meshref)
  2540. if self.EX_MESH:
  2541. murl = os.path.join( os.path.split(url)[0], '%s.mesh'%ob.data.name )
  2542. exists = os.path.isfile( murl )
  2543. if not exists or (exists and self.EX_MESH_OVERWRITE):
  2544. if ob.data.name not in exported_meshes:
  2545. exported_meshes.append( ob.data.name )
  2546. self.dot_mesh( ob, os.path.split(url)[0] )
  2547. doc = e.document
  2548. if ob.find_armature():
  2549. print (" - EC_AnimationController")
  2550. c = doc.createElement('component'); e.appendChild( c )
  2551. c.setAttribute('type', "EC_AnimationController")
  2552. c.setAttribute('sync', '1')
  2553. c = doc.createElement('component'); e.appendChild( c )
  2554. c.setAttribute('type', "EC_Mesh")
  2555. c.setAttribute('sync', '1')
  2556. a = doc.createElement('attribute'); c.appendChild(a)
  2557. a.setAttribute('name', "Mesh ref" )
  2558. a.setAttribute('value', meshref)
  2559. a = doc.createElement('attribute'); c.appendChild(a)
  2560. a.setAttribute('name', "Mesh materials" )
  2561. # Query object its materials and make a proper material ref string of it.
  2562. # note: We assume blindly here that the 'submesh' indexes are correct in the material list.
  2563. mymaterials = ob.data.materials
  2564. if mymaterials is not None and len(mymaterials) > 0:
  2565. mymatstring = '' # generate ; separated material list
  2566. for mymat in mymaterials:
  2567. if mymat is None:
  2568. continue
  2569. mymatstring += proto + material_name(mymat) + '.material;'
  2570. mymatstring = mymatstring[:-1] # strip ending ;
  2571. a.setAttribute('value', mymatstring )
  2572. else:
  2573. # default to nothing to avoid error prints in .txml import
  2574. a.setAttribute('value', "" )
  2575. if ob.find_armature():
  2576. skeletonref = "%s%s.skeleton" % (proto, ob.data.name)
  2577. print (" Skeleton ref:", skeletonref)
  2578. a = doc.createElement('attribute'); c.appendChild(a)
  2579. a.setAttribute('name', "Skeleton ref" )
  2580. a.setAttribute('value', skeletonref)
  2581. a = doc.createElement('attribute'); c.appendChild(a)
  2582. a.setAttribute('name', "Draw distance" )
  2583. if ob.use_draw_distance:
  2584. a.setAttribute('value', ob.draw_distance )
  2585. else:
  2586. a.setAttribute('value', "0" )
  2587. a = doc.createElement('attribute'); c.appendChild(a)
  2588. a.setAttribute('name', 'Cast shadows' )
  2589. if ob.cast_shadows:
  2590. a.setAttribute('value', 'true' )
  2591. else:
  2592. a.setAttribute('value', 'false' )
  2593. # EC_Light
  2594. def tundra_light( self, e, ob ):
  2595. '''
  2596. <component type="EC_Light" sync="1">
  2597. <attribute value="1" name="light type"/>
  2598. <attribute value="1 1 1 1" name="diffuse color"/>
  2599. <attribute value="1 1 1 1" name="specular color"/>
  2600. <attribute value="true" name="cast shadows"/>
  2601. <attribute value="29.9999828" name="light range"/>
  2602. <attribute value="1" name="brightness"/>
  2603. <attribute value="0" name="constant atten"/>
  2604. <attribute value="1" name="linear atten"/>
  2605. <attribute value="0" name="quadratic atten"/>
  2606. <attribute value="30" name="light inner angle"/>
  2607. <attribute value="40" name="light outer angle"/>
  2608. </component>
  2609. '''
  2610. if ob.data.type not in 'POINT SPOT'.split():
  2611. return
  2612. doc = e.document
  2613. c = doc.createElement('component'); e.appendChild( c )
  2614. c.setAttribute('type', "EC_Light")
  2615. c.setAttribute('sync', '1')
  2616. a = doc.createElement('attribute'); c.appendChild(a)
  2617. a.setAttribute('name', 'light type' )
  2618. if ob.data.type=='POINT':
  2619. a.setAttribute('value', '0' )
  2620. elif ob.data.type=='SPOT':
  2621. a.setAttribute('value', '1' )
  2622. #2 = directional light. blender has no directional light?
  2623. R,G,B = ob.data.color
  2624. a = doc.createElement('attribute'); c.appendChild(a)
  2625. a.setAttribute('name', 'diffuse color' )
  2626. if ob.data.use_diffuse:
  2627. a.setAttribute('value', '%s %s %s 1' %(R,G,B) )
  2628. else:
  2629. a.setAttribute('value', '0 0 0 1' )
  2630. a = doc.createElement('attribute'); c.appendChild(a)
  2631. a.setAttribute('name', 'specular color' )
  2632. if ob.data.use_specular:
  2633. a.setAttribute('value', '%s %s %s 1' %(R,G,B) )
  2634. else:
  2635. a.setAttribute('value', '0 0 0 1' )
  2636. a = doc.createElement('attribute'); c.appendChild(a)
  2637. a.setAttribute('name', 'cast shadows' )
  2638. if ob.data.type=='HEMI':
  2639. a.setAttribute('value', 'false' ) # HEMI no .shadow_method
  2640. elif ob.data.shadow_method != 'NOSHADOW':
  2641. a.setAttribute('value', 'true' )
  2642. else:
  2643. a.setAttribute('value', 'false' )
  2644. a = doc.createElement('attribute'); c.appendChild(a)
  2645. a.setAttribute('name', 'light range' )
  2646. a.setAttribute('value', ob.data.distance*2 )
  2647. a = doc.createElement('attribute'); c.appendChild(a)
  2648. a.setAttribute('name', 'brightness' )
  2649. a.setAttribute('value', ob.data.energy )
  2650. a = doc.createElement('attribute'); c.appendChild(a)
  2651. a.setAttribute('name', 'constant atten' )
  2652. a.setAttribute('value', '0' )
  2653. a = doc.createElement('attribute'); c.appendChild(a)
  2654. a.setAttribute('name', 'linear atten' )
  2655. energy = ob.data.energy
  2656. if energy <= 0.0:
  2657. energy = 0.001
  2658. a.setAttribute('value', (1.0/energy)*0.25 )
  2659. a = doc.createElement('attribute'); c.appendChild(a)
  2660. a.setAttribute('name', 'quadratic atten' )
  2661. a.setAttribute('value', '0.0' )
  2662. if ob.data.type=='SPOT':
  2663. outer = math.degrees(ob.data.spot_size) / 2.0
  2664. inner = outer * (1.0-ob.data.spot_blend)
  2665. a = doc.createElement('attribute'); c.appendChild(a)
  2666. a.setAttribute('name', 'light inner angle' )
  2667. a.setAttribute('value', '%s'%inner )
  2668. a = doc.createElement('attribute'); c.appendChild(a)
  2669. a.setAttribute('name', 'light outer angle' )
  2670. a.setAttribute('value', '%s' %outer )
  2671. ## UI export panel
  2672. last_export_filepath = ""
  2673. class _OgreCommonExport_(_TXML_):
  2674. @classmethod
  2675. def poll(cls, context):
  2676. if context.active_object and context.mode != 'EDIT_MESH':
  2677. return True
  2678. def invoke(self, context, event):
  2679. # Resolve path from opened .blend if available. It's not if
  2680. # blender normally was opened with "last open scene".
  2681. # After export is done once, remember that path when re-exporting.
  2682. global last_export_filepath
  2683. if last_export_filepath == "":
  2684. # First export during this blender run
  2685. if self.filepath == "" and context.blend_data.filepath != "":
  2686. path, name = os.path.split(context.blend_data.filepath)
  2687. self.filepath = os.path.join(path, name.split('.')[0])
  2688. if self.filepath == "":
  2689. self.filepath = "blender2ogre-export"
  2690. if self.EXPORT_TYPE == "OGRE":
  2691. self.filepath += ".scene"
  2692. elif self.EXPORT_TYPE == "REX":
  2693. self.filepath += ".txml"
  2694. else:
  2695. # Sequential export, use the previous path
  2696. self.filepath = last_export_filepath
  2697. # Replace file extension if we have swapped dialogs.
  2698. if self.EXPORT_TYPE == "OGRE":
  2699. self.filepath = self.filepath.replace(".txml", ".scene")
  2700. elif self.EXPORT_TYPE == "REX":
  2701. self.filepath = self.filepath.replace(".scene", ".txml")
  2702. # Update ui setting from the last export, or file config.
  2703. self.update_ui()
  2704. wm = context.window_manager
  2705. fs = wm.fileselect_add(self) # writes to filepath
  2706. return {'RUNNING_MODAL'}
  2707. def execute(self, context):
  2708. # Store this path for later re-export
  2709. global last_export_filepath
  2710. last_export_filepath = self.filepath
  2711. # Run the .scene or .txml export
  2712. self.ogre_export(self.filepath, context)
  2713. return {'FINISHED'}
  2714. def update_ui(self):
  2715. self.EX_SWAP_AXIS = CONFIG['SWAP_AXIS']
  2716. self.EX_SEP_MATS = CONFIG['SEP_MATS']
  2717. self.EX_ONLY_DEFORMABLE_BONES = CONFIG['ONLY_DEFORMABLE_BONES']
  2718. self.EX_ONLY_ANIMATED_BONES = CONFIG['ONLY_ANIMATED_BONES']
  2719. self.EX_SCENE = CONFIG['SCENE']
  2720. self.EX_SELONLY = CONFIG['SELONLY']
  2721. self.EX_FORCE_CAMERA = CONFIG['FORCE_CAMERA']
  2722. self.EX_FORCE_LAMPS = CONFIG['FORCE_LAMPS']
  2723. self.EX_MESH = CONFIG['MESH']
  2724. self.EX_MESH_OVERWRITE = CONFIG['MESH_OVERWRITE']
  2725. self.EX_ARM_ANIM = CONFIG['ARM_ANIM']
  2726. self.EX_SHAPE_ANIM = CONFIG['SHAPE_ANIM']
  2727. self.EX_INDEPENDENT_ANIM = CONFIG['INDEPENDENT_ANIM']
  2728. self.EX_TRIM_BONE_WEIGHTS = CONFIG['TRIM_BONE_WEIGHTS']
  2729. self.EX_ARRAY = CONFIG['ARRAY']
  2730. self.EX_MATERIALS = CONFIG['MATERIALS']
  2731. self.EX_FORCE_IMAGE_FORMAT = CONFIG['FORCE_IMAGE_FORMAT']
  2732. self.EX_DDS_MIPS = CONFIG['DDS_MIPS']
  2733. self.EX_COPY_SHADER_PROGRAMS = CONFIG['COPY_SHADER_PROGRAMS']
  2734. self.EX_lodLevels = CONFIG['lodLevels']
  2735. self.EX_lodDistance = CONFIG['lodDistance']
  2736. self.EX_lodPercent = CONFIG['lodPercent']
  2737. self.EX_nuextremityPoints = CONFIG['nuextremityPoints']
  2738. self.EX_generateEdgeLists = CONFIG['generateEdgeLists']
  2739. self.EX_generateTangents = CONFIG['generateTangents']
  2740. self.EX_tangentSemantic = CONFIG['tangentSemantic']
  2741. self.EX_tangentUseParity = CONFIG['tangentUseParity']
  2742. self.EX_tangentSplitMirrored = CONFIG['tangentSplitMirrored']
  2743. self.EX_tangentSplitRotated = CONFIG['tangentSplitRotated']
  2744. self.EX_reorganiseBuffers = CONFIG['reorganiseBuffers']
  2745. self.EX_optimiseAnimations = CONFIG['optimiseAnimations']
  2746. # Basic options
  2747. EX_SWAP_AXIS = EnumProperty(
  2748. items=AXIS_MODES,
  2749. name='swap axis',
  2750. description='axis swapping mode',
  2751. default= CONFIG['SWAP_AXIS'])
  2752. EX_SEP_MATS = BoolProperty(
  2753. name="Separate Materials",
  2754. description="exports a .material for each material (rather than putting all materials in a single .material file)",
  2755. default=CONFIG['SEP_MATS'])
  2756. EX_ONLY_DEFORMABLE_BONES = BoolProperty(
  2757. name="Only Deformable Bones",
  2758. description="only exports bones that are deformable. Useful for hiding IK-Bones used in Blender. Warning: Will cause trouble if a deformable bone has a non-deformable parent",
  2759. default=CONFIG['ONLY_DEFORMABLE_BONES'])
  2760. EX_ONLY_ANIMATED_BONES = BoolProperty(
  2761. name="Only Animated Bones",
  2762. description="only exports bones that have been keyframed, useful for run-time animation blending (example: upper/lower torso split)",
  2763. default=CONFIG['ONLY_ANIMATED_BONES'])
  2764. EX_SCENE = BoolProperty(
  2765. name="Export Scene",
  2766. description="export current scene (OgreDotScene xml)",
  2767. default=CONFIG['SCENE'])
  2768. EX_SELONLY = BoolProperty(
  2769. name="Export Selected Only",
  2770. description="export selected",
  2771. default=CONFIG['SELONLY'])
  2772. EX_FORCE_CAMERA = BoolProperty(
  2773. name="Force Camera",
  2774. description="export active camera",
  2775. default=CONFIG['FORCE_CAMERA'])
  2776. EX_FORCE_LAMPS = BoolProperty(
  2777. name="Force Lamps",
  2778. description="export all lamps",
  2779. default=CONFIG['FORCE_LAMPS'])
  2780. EX_MESH = BoolProperty(
  2781. name="Export Meshes",
  2782. description="export meshes",
  2783. default=CONFIG['MESH'])
  2784. EX_MESH_OVERWRITE = BoolProperty(
  2785. name="Export Meshes (overwrite)",
  2786. description="export meshes (overwrite existing files)",
  2787. default=CONFIG['MESH_OVERWRITE'])
  2788. EX_ARM_ANIM = BoolProperty(
  2789. name="Armature Animation",
  2790. description="export armature animations - updates the .skeleton file",
  2791. default=CONFIG['ARM_ANIM'])
  2792. EX_SHAPE_ANIM = BoolProperty(
  2793. name="Shape Animation",
  2794. description="export shape animations - updates the .mesh file",
  2795. default=CONFIG['SHAPE_ANIM'])
  2796. EX_INDEPENDENT_ANIM = BoolProperty(
  2797. name="Independent Animations",
  2798. description="Export each NLA-Strip independently. If unchecked NLA-Strips that overlap influence each other.",
  2799. default=CONFIG['INDEPENDENT_ANIM'])
  2800. EX_TRIM_BONE_WEIGHTS = FloatProperty(
  2801. name="Trim Weights",
  2802. description="ignore bone weights below this value (Ogre supports 4 bones per vertex)",
  2803. min=0.0, max=0.5, default=CONFIG['TRIM_BONE_WEIGHTS'] )
  2804. EX_ARRAY = BoolProperty(
  2805. name="Optimize Arrays",
  2806. description="optimize array modifiers as instances (constant offset only)",
  2807. default=CONFIG['ARRAY'])
  2808. EX_MATERIALS = BoolProperty(
  2809. name="Export Materials",
  2810. description="exports .material script",
  2811. default=CONFIG['MATERIALS'])
  2812. EX_FORCE_IMAGE_FORMAT = EnumProperty(
  2813. items=_IMAGE_FORMATS,
  2814. name='Convert Images',
  2815. description='convert all textures to format',
  2816. default=CONFIG['FORCE_IMAGE_FORMAT'] )
  2817. EX_DDS_MIPS = IntProperty(
  2818. name="DDS Mips",
  2819. description="number of mip maps (DDS)",
  2820. min=0, max=16,
  2821. default=CONFIG['DDS_MIPS'])
  2822. # Mesh options
  2823. EX_lodLevels = IntProperty(
  2824. name="LOD Levels",
  2825. description="MESH number of LOD levels",
  2826. min=0, max=32,
  2827. default=CONFIG['lodLevels'])
  2828. EX_lodDistance = IntProperty(
  2829. name="LOD Distance",
  2830. description="MESH distance increment to reduce LOD",
  2831. min=0, max=2000, default=CONFIG['lodDistance'])
  2832. EX_lodPercent = IntProperty(
  2833. name="LOD Percentage",
  2834. description="LOD percentage reduction",
  2835. min=0, max=99,
  2836. default=CONFIG['lodPercent'])
  2837. EX_nuextremityPoints = IntProperty(
  2838. name="Extremity Points",
  2839. description="MESH Extremity Points",
  2840. min=0, max=65536,
  2841. default=CONFIG['nuextremityPoints'])
  2842. EX_generateEdgeLists = BoolProperty(
  2843. name="Edge Lists",
  2844. description="MESH generate edge lists (for stencil shadows)",
  2845. default=CONFIG['generateEdgeLists'])
  2846. EX_generateTangents = BoolProperty(
  2847. name="Tangents",
  2848. description="MESH generate tangents",
  2849. default=CONFIG['generateTangents'])
  2850. EX_tangentSemantic = StringProperty(
  2851. name="Tangent Semantic",
  2852. description="MESH tangent semantic",
  2853. maxlen=3,
  2854. default=CONFIG['tangentSemantic'])
  2855. EX_tangentUseParity = IntProperty(
  2856. name="Tangent Parity",
  2857. description="MESH tangent use parity",
  2858. min=0, max=16,
  2859. default=CONFIG['tangentUseParity'])
  2860. EX_tangentSplitMirrored = BoolProperty(
  2861. name="Tangent Split Mirrored",
  2862. description="MESH split mirrored tangents",
  2863. default=CONFIG['tangentSplitMirrored'])
  2864. EX_tangentSplitRotated = BoolProperty(
  2865. name="Tangent Split Rotated",
  2866. description="MESH split rotated tangents",
  2867. default=CONFIG['tangentSplitRotated'])
  2868. EX_reorganiseBuffers = BoolProperty(
  2869. name="Reorganise Buffers",
  2870. description="MESH reorganise vertex buffers",
  2871. default=CONFIG['reorganiseBuffers'])
  2872. EX_optimiseAnimations = BoolProperty(
  2873. name="Optimize Animations",
  2874. description="MESH optimize animations",
  2875. default=CONFIG['optimiseAnimations'])
  2876. EX_COPY_SHADER_PROGRAMS = BoolProperty(
  2877. name="copy shader programs",
  2878. description="when using script inheritance copy the source shader programs to the output path",
  2879. default=CONFIG['COPY_SHADER_PROGRAMS'])
  2880. filepath_last = ""
  2881. filepath = StringProperty(
  2882. name="File Path",
  2883. description="Filepath used for exporting file",
  2884. maxlen=1024, default="",
  2885. subtype='FILE_PATH')
  2886. def dot_material( self, meshes, path='/tmp', mat_file_name='SceneMaterial'):
  2887. material_files = []
  2888. mats = []
  2889. for ob in meshes:
  2890. if len(ob.data.materials):
  2891. for mat in ob.data.materials:
  2892. if mat not in mats:
  2893. mats.append( mat )
  2894. if not mats:
  2895. print('WARNING: no materials, not writting .material script'); return []
  2896. M = MISSING_MATERIAL + '\n'
  2897. for mat in mats:
  2898. if mat is None:
  2899. continue
  2900. Report.materials.append( material_name(mat) )
  2901. if CONFIG['COPY_SHADER_PROGRAMS']:
  2902. data = generate_material( mat, path=path, copy_programs=True, touch_textures=CONFIG['TOUCH_TEXTURES'] )
  2903. else:
  2904. data = generate_material( mat, path=path, touch_textures=CONFIG['TOUCH_TEXTURES'] )
  2905. M += data
  2906. # Write own .material file per material
  2907. if self.EX_SEP_MATS:
  2908. url = self.dot_material_write_separate( mat, data, path )
  2909. material_files.append( url )
  2910. # Write one .material file for everything
  2911. if not self.EX_SEP_MATS:
  2912. try:
  2913. url = os.path.join(path, '%s.material' % mat_file_name)
  2914. f = open( url, 'wb' ); f.write( bytes(M,'utf-8') ); f.close()
  2915. print(' - Created material:', url)
  2916. material_files.append( url )
  2917. except Exception as e:
  2918. show_dialog("Invalid material object name: " + mat_file_name)
  2919. return material_files
  2920. def dot_material_write_separate( self, mat, data, path = '/tmp' ):
  2921. try:
  2922. url = os.path.join(path, '%s.material' % material_name(mat))
  2923. f = open(url, 'wb'); f.write( bytes(data,'utf-8') ); f.close()
  2924. print(' - Exported Material:', url)
  2925. return url
  2926. except Exception as e:
  2927. show_dialog("Invalid material object name: " + material_name(mat))
  2928. return ""
  2929. def dot_mesh( self, ob, path='/tmp', force_name=None, ignore_shape_animation=False ):
  2930. dot_mesh( ob, path, force_name, ignore_shape_animation=False )
  2931. def ogre_export(self, url, context, force_material_update=[]):
  2932. print ("_"*80)
  2933. # Updating config to latest values?
  2934. global CONFIG
  2935. for name in dir(self):
  2936. if name.startswith('EX_'):
  2937. CONFIG[ name[3:] ] = getattr(self,name)
  2938. Report.reset()
  2939. print("Processing Scene")
  2940. prefix = url.split('.')[0]
  2941. path = os.path.split(url)[0]
  2942. # Nodes (objects) - gather because macros will change selection state
  2943. objects = []
  2944. linkedgroups = []
  2945. for ob in bpy.context.scene.objects:
  2946. if ob.subcollision:
  2947. continue
  2948. if self.EX_SELONLY and not ob.select:
  2949. if ob.type == 'CAMERA' and self.EX_FORCE_CAMERA:
  2950. pass
  2951. elif ob.type == 'LAMP' and self.EX_FORCE_LAMPS:
  2952. pass
  2953. else:
  2954. continue
  2955. if ob.type == 'EMPTY' and ob.dupli_group and ob.dupli_type == 'GROUP':
  2956. linkedgroups.append(ob)
  2957. else:
  2958. objects.append(ob)
  2959. # Linked groups - allows 3 levels of nested blender library linking
  2960. temps = []
  2961. for e in linkedgroups:
  2962. grp = e.dupli_group
  2963. subs = []
  2964. for o in grp.objects:
  2965. if o.type=='MESH':
  2966. subs.append( o ) # TOP-LEVEL
  2967. elif o.type == 'EMPTY' and o.dupli_group and o.dupli_type == 'GROUP':
  2968. ss = [] # LEVEL2
  2969. for oo in o.dupli_group.objects:
  2970. if oo.type=='MESH':
  2971. ss.append( oo )
  2972. elif oo.type == 'EMPTY' and oo.dupli_group and oo.dupli_type == 'GROUP':
  2973. sss = [] # LEVEL3
  2974. for ooo in oo.dupli_group.objects:
  2975. if ooo.type=='MESH':
  2976. sss.append( ooo )
  2977. if sss:
  2978. m = merge_objects( sss, name=oo.name, transform=oo.matrix_world )
  2979. subs.append( m )
  2980. temps.append( m )
  2981. if ss:
  2982. m = merge_objects( ss, name=o.name, transform=o.matrix_world )
  2983. subs.append( m )
  2984. temps.append( m )
  2985. if subs:
  2986. m = merge_objects( subs, name=e.name, transform=e.matrix_world )
  2987. objects.append( m )
  2988. temps.append( m )
  2989. # Find merge groups
  2990. mgroups = []
  2991. mobjects = []
  2992. for ob in objects:
  2993. group = get_merge_group( ob )
  2994. if group:
  2995. for member in group.objects:
  2996. if member not in mobjects: mobjects.append( member )
  2997. if group not in mgroups: mgroups.append( group )
  2998. for rem in mobjects:
  2999. if rem in objects: objects.remove( rem )
  3000. for group in mgroups:
  3001. merged = merge_group( group )
  3002. objects.append( merged )
  3003. temps.append( merged )
  3004. # Gather roots because ogredotscene supports parents and children
  3005. def _flatten( _c, _f ):
  3006. if _c.parent in objects: _f.append( _c.parent )
  3007. if _c.parent: _flatten( _c.parent, _f )
  3008. else: _f.append( _c )
  3009. roots = []
  3010. meshes = []
  3011. for ob in objects:
  3012. flat = []
  3013. _flatten( ob, flat )
  3014. root = flat[-1]
  3015. if root not in roots:
  3016. roots.append(root)
  3017. if ob.type=='MESH':
  3018. meshes.append(ob)
  3019. mesh_collision_prims = {}
  3020. mesh_collision_files = {}
  3021. # Track that we don't export same data multiple times
  3022. exported_meshes = []
  3023. if self.EX_MATERIALS:
  3024. print (" Processing Materials")
  3025. material_file_name_base = os.path.split(url)[1].replace('.scene', '').replace('.txml', '')
  3026. material_files = self.dot_material(meshes + force_material_update, path, material_file_name_base)
  3027. else:
  3028. material_files = []
  3029. # realXtend Tundra .txml scene description export
  3030. if self.EXPORT_TYPE == 'REX':
  3031. rex = self.create_tundra_document(context)
  3032. proxies = []
  3033. for ob in objects:
  3034. print(" Processing %s [%s]" % (ob.name, ob.type))
  3035. # This seemingly needs to be done as its done in .scene
  3036. # export. Fixed a bug that no .meshes were exported when doing
  3037. # a Tundra export.
  3038. if ob.type == 'MESH':
  3039. ob.data.update(calc_tessface=True)
  3040. # EC_Light
  3041. if ob.type == 'LAMP':
  3042. TE = self.tundra_entity(rex, ob, path=path, collision_proxies=proxies)
  3043. self.tundra_light( TE, ob )
  3044. # EC_Sound
  3045. elif ob.type == 'SPEAKER':
  3046. TE = self.tundra_entity(rex, ob, path=path, collision_proxies=proxies)
  3047. # EC_Mesh
  3048. elif ob.type == 'MESH' and len(ob.data.tessfaces):
  3049. if ob.modifiers and ob.modifiers[0].type=='MULTIRES' and ob.use_multires_lod:
  3050. mod = ob.modifiers[0]
  3051. basename = ob.name
  3052. dataname = ob.data.name
  3053. ID = uid( ob ) # ensure uid
  3054. TE = self.tundra_entity(rex, ob, path=path, collision_proxies=proxies)
  3055. for level in range( mod.total_levels+1 ):
  3056. ob.uid += 1
  3057. mod.levels = level
  3058. ob.name = '%s.LOD%s' %(basename,level)
  3059. ob.data.name = '%s.LOD%s' %(dataname,level)
  3060. TE = self.tundra_entity(
  3061. rex, ob, path=path, collision_proxies=proxies, parent=basename,
  3062. matrix=mathutils.Matrix(), visible=False
  3063. )
  3064. self.tundra_mesh( TE, ob, url, exported_meshes )
  3065. ob.uid = ID
  3066. ob.name = basename
  3067. ob.data.name = dataname
  3068. else:
  3069. TE = self.tundra_entity( rex, ob, path=path, collision_proxies=proxies )
  3070. self.tundra_mesh( TE, ob, url, exported_meshes )
  3071. # EC_RigidBody separate collision meshes
  3072. for proxy in proxies:
  3073. self.dot_mesh(
  3074. proxy,
  3075. path=os.path.split(url)[0],
  3076. force_name='_collision_%s' %proxy.data.name
  3077. )
  3078. if self.EX_SCENE:
  3079. if not url.endswith('.txml'):
  3080. url += '.txml'
  3081. data = rex.toprettyxml()
  3082. f = open( url, 'wb' ); f.write( bytes(data,'utf-8') ); f.close()
  3083. print(' Exported Tundra Scene:', url)
  3084. # Ogre .scene scene description export
  3085. elif self.EXPORT_TYPE == 'OGRE':
  3086. doc = self.create_ogre_document( context, material_files )
  3087. for root in roots:
  3088. print(' - Exporting root node:', root.name)
  3089. self._node_export(
  3090. root,
  3091. url = url,
  3092. doc = doc,
  3093. exported_meshes = exported_meshes,
  3094. meshes = meshes,
  3095. mesh_collision_prims = mesh_collision_prims,
  3096. mesh_collision_files = mesh_collision_files,
  3097. prefix = prefix,
  3098. objects = objects,
  3099. xmlparent = doc._scene_nodes
  3100. )
  3101. if self.EX_SCENE:
  3102. if not url.endswith('.scene'):
  3103. url += '.scene'
  3104. data = doc.toprettyxml()
  3105. f = open( url, 'wb' ); f.write( bytes(data,'utf-8') ); f.close()
  3106. print(' Exported Ogre Scene:', url)
  3107. for ob in temps:
  3108. context.scene.objects.unlink( ob )
  3109. bpy.ops.wm.call_menu(name='MiniReport')
  3110. # Always save?
  3111. # todo: This does not seem to stick! It might save to disk
  3112. # but the old config defaults are read when this panel is opened!
  3113. save_config()
  3114. def create_ogre_document(self, context, material_files=[] ):
  3115. now = time.time()
  3116. doc = RDocument()
  3117. scn = doc.createElement('scene'); doc.appendChild( scn )
  3118. scn.setAttribute('export_time', str(now))
  3119. scn.setAttribute('formatVersion', '1.0.1')
  3120. bscn = bpy.context.scene
  3121. if '_previous_export_time_' in bscn.keys():
  3122. scn.setAttribute('previous_export_time', str(bscn['_previous_export_time_']))
  3123. else:
  3124. scn.setAttribute('previous_export_time', '0')
  3125. bscn[ '_previous_export_time_' ] = now
  3126. scn.setAttribute('exported_by', getpass.getuser())
  3127. nodes = doc.createElement('nodes')
  3128. doc._scene_nodes = nodes
  3129. extern = doc.createElement('externals')
  3130. environ = doc.createElement('environment')
  3131. for n in (nodes,extern,environ):
  3132. scn.appendChild( n )
  3133. # Extern files
  3134. for url in material_files:
  3135. item = doc.createElement('item'); extern.appendChild( item )
  3136. item.setAttribute('type','material')
  3137. a = doc.createElement('file'); item.appendChild( a )
  3138. a.setAttribute('name', url)
  3139. # Environ settings
  3140. world = context.scene.world
  3141. if world: # multiple scenes - other scenes may not have a world
  3142. _c = {'colourAmbient':world.ambient_color, 'colourBackground':world.horizon_color, 'colourDiffuse':world.horizon_color}
  3143. for ctag in _c:
  3144. a = doc.createElement(ctag); environ.appendChild( a )
  3145. color = _c[ctag]
  3146. a.setAttribute('r', '%s'%color.r)
  3147. a.setAttribute('g', '%s'%color.g)
  3148. a.setAttribute('b', '%s'%color.b)
  3149. if world and world.mist_settings.use_mist:
  3150. a = doc.createElement('fog'); environ.appendChild( a )
  3151. a.setAttribute('linearStart', '%s'%world.mist_settings.start )
  3152. mist_falloff = world.mist_settings.falloff
  3153. if mist_falloff == 'QUADRATIC': a.setAttribute('mode', 'exp') # on DTD spec (none | exp | exp2 | linear)
  3154. elif mist_falloff == 'LINEAR': a.setAttribute('mode', 'linear')
  3155. else: a.setAttribute('mode', 'exp2')
  3156. #a.setAttribute('mode', world.mist_settings.falloff.lower() ) # not on DTD spec
  3157. a.setAttribute('linearEnd', '%s' %(world.mist_settings.start+world.mist_settings.depth))
  3158. a.setAttribute('expDensity', world.mist_settings.intensity)
  3159. a.setAttribute('colourR', world.horizon_color.r)
  3160. a.setAttribute('colourG', world.horizon_color.g)
  3161. a.setAttribute('colourB', world.horizon_color.b)
  3162. return doc
  3163. # Recursive Node export
  3164. def _node_export( self, ob, url='', doc=None, rex=None, exported_meshes=[], meshes=[], mesh_collision_prims={}, mesh_collision_files={}, prefix='', objects=[], xmlparent=None ):
  3165. o = _ogre_node_helper( doc, ob, objects )
  3166. xmlparent.appendChild(o)
  3167. # Custom user props
  3168. for prop in ob.items():
  3169. propname, propvalue = prop
  3170. if not propname.startswith('_'):
  3171. user = doc.createElement('user_data')
  3172. o.appendChild( user )
  3173. user.setAttribute( 'name', propname )
  3174. user.setAttribute( 'value', str(propvalue) )
  3175. user.setAttribute( 'type', type(propvalue).__name__ )
  3176. # Custom user props from BGE props by Mind Calamity
  3177. for prop in ob.game.properties:
  3178. e = doc.createElement( 'user_data' )
  3179. o.appendChild( e )
  3180. e.setAttribute('name', prop.name)
  3181. e.setAttribute('value', str(prop.value))
  3182. e.setAttribute('type', type(prop.value).__name__)
  3183. # -- end of Mind Calamity patch
  3184. # BGE subset
  3185. game = doc.createElement('game')
  3186. o.appendChild( game )
  3187. sens = doc.createElement('sensors')
  3188. game.appendChild( sens )
  3189. acts = doc.createElement('actuators')
  3190. game.appendChild( acts )
  3191. for sen in ob.game.sensors:
  3192. sens.appendChild( WrapSensor(sen).xml(doc) )
  3193. for act in ob.game.actuators:
  3194. acts.appendChild( WrapActuator(act).xml(doc) )
  3195. if ob.type == 'MESH':
  3196. ob.data.update(calc_tessface=True)
  3197. if ob.type == 'MESH' and len(ob.data.tessfaces):
  3198. collisionFile = None
  3199. collisionPrim = None
  3200. if ob.data.name in mesh_collision_prims:
  3201. collisionPrim = mesh_collision_prims[ ob.data.name ]
  3202. if ob.data.name in mesh_collision_files:
  3203. collisionFile = mesh_collision_files[ ob.data.name ]
  3204. e = doc.createElement('entity')
  3205. o.appendChild(e); e.setAttribute('name', ob.data.name)
  3206. prefix = ''
  3207. e.setAttribute('meshFile', '%s%s.mesh' %(prefix,ob.data.name) )
  3208. if not collisionPrim and not collisionFile:
  3209. if ob.game.use_collision_bounds:
  3210. collisionPrim = ob.game.collision_bounds_type.lower()
  3211. mesh_collision_prims[ ob.data.name ] = collisionPrim
  3212. else:
  3213. for child in ob.children:
  3214. if child.subcollision and child.name.startswith('DECIMATE'):
  3215. collisionFile = '%s_collision_%s.mesh' %(prefix,ob.data.name)
  3216. break
  3217. if collisionFile:
  3218. mesh_collision_files[ ob.data.name ] = collisionFile
  3219. self.dot_mesh(
  3220. child,
  3221. path=os.path.split(url)[0],
  3222. force_name='_collision_%s' %ob.data.name
  3223. )
  3224. if collisionPrim:
  3225. e.setAttribute('collisionPrim', collisionPrim )
  3226. elif collisionFile:
  3227. e.setAttribute('collisionFile', collisionFile )
  3228. _mesh_entity_helper( doc, ob, e )
  3229. if self.EX_MESH:
  3230. murl = os.path.join( os.path.split(url)[0], '%s.mesh'%ob.data.name )
  3231. exists = os.path.isfile( murl )
  3232. if not exists or (exists and self.EX_MESH_OVERWRITE):
  3233. if ob.data.name not in exported_meshes:
  3234. exported_meshes.append( ob.data.name )
  3235. self.dot_mesh( ob, os.path.split(url)[0] )
  3236. # Deal with Array modifier
  3237. vecs = [ ob.matrix_world.to_translation() ]
  3238. for mod in ob.modifiers:
  3239. if mod.type == 'ARRAY':
  3240. if mod.fit_type != 'FIXED_COUNT':
  3241. print( 'WARNING: unsupport array-modifier type->', mod.fit_type )
  3242. continue
  3243. if not mod.use_constant_offset:
  3244. print( 'WARNING: unsupport array-modifier mode, must be "constant offset" type' )
  3245. continue
  3246. else:
  3247. #v = ob.matrix_world.to_translation()
  3248. newvecs = []
  3249. for prev in vecs:
  3250. for i in range( mod.count-1 ):
  3251. v = prev + mod.constant_offset_displace
  3252. newvecs.append( v )
  3253. ao = _ogre_node_helper( doc, ob, objects, prefix='_array_%s_'%len(vecs+newvecs), pos=v )
  3254. xmlparent.appendChild(ao)
  3255. e = doc.createElement('entity')
  3256. ao.appendChild(e); e.setAttribute('name', ob.data.name)
  3257. #if self.EX_MESH_SUBDIR: e.setAttribute('meshFile', 'meshes/%s.mesh' %ob.data.name)
  3258. #else:
  3259. e.setAttribute('meshFile', '%s.mesh' %ob.data.name)
  3260. if collisionPrim: e.setAttribute('collisionPrim', collisionPrim )
  3261. elif collisionFile: e.setAttribute('collisionFile', collisionFile )
  3262. vecs += newvecs
  3263. elif ob.type == 'CAMERA':
  3264. Report.cameras.append( ob.name )
  3265. c = doc.createElement('camera')
  3266. o.appendChild(c); c.setAttribute('name', ob.data.name)
  3267. aspx = bpy.context.scene.render.pixel_aspect_x
  3268. aspy = bpy.context.scene.render.pixel_aspect_y
  3269. sx = bpy.context.scene.render.resolution_x
  3270. sy = bpy.context.scene.render.resolution_y
  3271. fovY = 0.0
  3272. if (sx*aspx > sy*aspy):
  3273. fovY = 2*math.atan(sy*aspy*16.0/(ob.data.lens*sx*aspx))
  3274. else:
  3275. fovY = 2*math.atan(16.0/ob.data.lens)
  3276. # fov in radians - like OgreMax - requested by cyrfer
  3277. fov = math.radians( fovY*180.0/math.pi )
  3278. c.setAttribute('fov', '%s'%fov)
  3279. c.setAttribute('projectionType', "perspective")
  3280. a = doc.createElement('clipping'); c.appendChild( a )
  3281. a.setAttribute('nearPlaneDist', '%s' %ob.data.clip_start)
  3282. a.setAttribute('farPlaneDist', '%s' %ob.data.clip_end)
  3283. a.setAttribute('near', '%s' %ob.data.clip_start) # requested by cyrfer
  3284. a.setAttribute('far', '%s' %ob.data.clip_end)
  3285. elif ob.type == 'LAMP' and ob.data.type in 'POINT SPOT SUN'.split():
  3286. Report.lights.append( ob.name )
  3287. l = doc.createElement('light')
  3288. o.appendChild(l)
  3289. mat = get_parent_matrix(ob, objects).inverted() * ob.matrix_world
  3290. p = doc.createElement('position') # just to make sure we conform with the DTD
  3291. l.appendChild(p)
  3292. v = swap( ob.matrix_world.to_translation() )
  3293. p.setAttribute('x', '%6f'%v.x)
  3294. p.setAttribute('y', '%6f'%v.y)
  3295. p.setAttribute('z', '%6f'%v.z)
  3296. if ob.data.type == 'POINT':
  3297. l.setAttribute('type', 'point')
  3298. elif ob.data.type == 'SPOT':
  3299. l.setAttribute('type', 'spot')
  3300. elif ob.data.type == 'SUN':
  3301. l.setAttribute('type', 'directional')
  3302. l.setAttribute('name', ob.name )
  3303. l.setAttribute('powerScale', str(ob.data.energy))
  3304. a = doc.createElement('lightAttenuation'); l.appendChild( a )
  3305. a.setAttribute('range', '5000' ) # is this an Ogre constant?
  3306. a.setAttribute('constant', '1.0') # TODO support quadratic light
  3307. a.setAttribute('linear', '%s'%(1.0/ob.data.distance))
  3308. a.setAttribute('quadratic', '0.0')
  3309. if ob.data.type in ('SPOT', 'SUN'):
  3310. vector = swap(mathutils.Euler.to_matrix(ob.rotation_euler)[2])
  3311. a = doc.createElement('direction')
  3312. l.appendChild(a)
  3313. a.setAttribute('x',str(round(-vector[0],3)))
  3314. a.setAttribute('y',str(round(-vector[1],3)))
  3315. a.setAttribute('z',str(round(-vector[2],3)))
  3316. if ob.data.type == 'SPOT':
  3317. a = doc.createElement('spotLightRange')
  3318. l.appendChild(a)
  3319. a.setAttribute('inner',str( ob.data.spot_size*(1.0-ob.data.spot_blend) ))
  3320. a.setAttribute('outer',str(ob.data.spot_size))
  3321. a.setAttribute('falloff','1.0')
  3322. if ob.data.use_diffuse:
  3323. a = doc.createElement('colourDiffuse'); l.appendChild( a )
  3324. a.setAttribute('r', '%s'%ob.data.color.r)
  3325. a.setAttribute('g', '%s'%ob.data.color.g)
  3326. a.setAttribute('b', '%s'%ob.data.color.b)
  3327. if ob.data.use_specular:
  3328. a = doc.createElement('colourSpecular'); l.appendChild( a )
  3329. a.setAttribute('r', '%s'%ob.data.color.r)
  3330. a.setAttribute('g', '%s'%ob.data.color.g)
  3331. a.setAttribute('b', '%s'%ob.data.color.b)
  3332. if ob.data.type != 'HEMI': # colourShadow is extra, not part of Ogre DTD
  3333. if ob.data.shadow_method != 'NOSHADOW': # Hemi light has no shadow_method
  3334. a = doc.createElement('colourShadow');l.appendChild( a )
  3335. a.setAttribute('r', '%s'%ob.data.color.r)
  3336. a.setAttribute('g', '%s'%ob.data.color.g)
  3337. a.setAttribute('b', '%s'%ob.data.color.b)
  3338. l.setAttribute('shadow','true')
  3339. for child in ob.children:
  3340. self._node_export( child,
  3341. url = url, doc = doc, rex = rex,
  3342. exported_meshes = exported_meshes,
  3343. meshes = meshes,
  3344. mesh_collision_prims = mesh_collision_prims,
  3345. mesh_collision_files = mesh_collision_files,
  3346. prefix = prefix,
  3347. objects=objects,
  3348. xmlparent=o
  3349. )
  3350. ## UI panel Ogre export - Subclasses _OgreCommonExport_
  3351. class INFO_OT_createOgreExport(bpy.types.Operator, _OgreCommonExport_):
  3352. '''Export Ogre Scene'''
  3353. bl_idname = "ogre.export"
  3354. bl_label = "Export Ogre"
  3355. bl_options = {'REGISTER'}
  3356. # Basic options
  3357. EX_SWAP_AXIS = EnumProperty(
  3358. items=AXIS_MODES,
  3359. name='swap axis',
  3360. description='axis swapping mode',
  3361. default= CONFIG['SWAP_AXIS'])
  3362. EX_SEP_MATS = BoolProperty(
  3363. name="Separate Materials",
  3364. description="exports a .material for each material (rather than putting all materials in a single .material file)",
  3365. default=CONFIG['SEP_MATS'])
  3366. EX_ONLY_DEFORMABLE_BONES = BoolProperty(
  3367. name="Only Deformable Bones",
  3368. description="only exports bones that are deformable. Useful for hiding IK-Bones used in Blender. Warning: Will cause trouble if a deformable bone has a non-deformable parent",
  3369. default=CONFIG['ONLY_DEFORMABLE_BONES'])
  3370. EX_ONLY_ANIMATED_BONES = BoolProperty(
  3371. name="Only Animated Bones",
  3372. description="only exports bones that have been keyframed, useful for run-time animation blending (example: upper/lower torso split)",
  3373. default=CONFIG['ONLY_ANIMATED_BONES'])
  3374. EX_SCENE = BoolProperty(
  3375. name="Export Scene",
  3376. description="export current scene (OgreDotScene xml)",
  3377. default=CONFIG['SCENE'])
  3378. EX_SELONLY = BoolProperty(
  3379. name="Export Selected Only",
  3380. description="export selected",
  3381. default=CONFIG['SELONLY'])
  3382. EX_FORCE_CAMERA = BoolProperty(
  3383. name="Force Camera",
  3384. description="export active camera",
  3385. default=CONFIG['FORCE_CAMERA'])
  3386. EX_FORCE_LAMPS = BoolProperty(
  3387. name="Force Lamps",
  3388. description="export all lamps",
  3389. default=CONFIG['FORCE_LAMPS'])
  3390. EX_MESH = BoolProperty(
  3391. name="Export Meshes",
  3392. description="export meshes",
  3393. default=CONFIG['MESH'])
  3394. EX_MESH_OVERWRITE = BoolProperty(
  3395. name="Export Meshes (overwrite)",
  3396. description="export meshes (overwrite existing files)",
  3397. default=CONFIG['MESH_OVERWRITE'])
  3398. EX_ARM_ANIM = BoolProperty(
  3399. name="Armature Animation",
  3400. description="export armature animations - updates the .skeleton file",
  3401. default=CONFIG['ARM_ANIM'])
  3402. EX_SHAPE_ANIM = BoolProperty(
  3403. name="Shape Animation",
  3404. description="export shape animations - updates the .mesh file",
  3405. default=CONFIG['SHAPE_ANIM'])
  3406. EX_INDEPENDENT_ANIM = BoolProperty(
  3407. name="Independent Animations",
  3408. description="Export each NLA-Strip independently. If unchecked NLA-Strips that overlap influence each other.",
  3409. default=CONFIG['INDEPENDENT_ANIM'])
  3410. EX_TRIM_BONE_WEIGHTS = FloatProperty(
  3411. name="Trim Weights",
  3412. description="ignore bone weights below this value (Ogre supports 4 bones per vertex)",
  3413. min=0.0, max=0.5, default=CONFIG['TRIM_BONE_WEIGHTS'] )
  3414. EX_ARRAY = BoolProperty(
  3415. name="Optimize Arrays",
  3416. description="optimize array modifiers as instances (constant offset only)",
  3417. default=CONFIG['ARRAY'])
  3418. EX_MATERIALS = BoolProperty(
  3419. name="Export Materials",
  3420. description="exports .material script",
  3421. default=CONFIG['MATERIALS'])
  3422. EX_FORCE_IMAGE_FORMAT = EnumProperty(
  3423. items=_IMAGE_FORMATS,
  3424. name='Convert Images',
  3425. description='convert all textures to format',
  3426. default=CONFIG['FORCE_IMAGE_FORMAT'] )
  3427. EX_DDS_MIPS = IntProperty(
  3428. name="DDS Mips",
  3429. description="number of mip maps (DDS)",
  3430. min=0, max=16,
  3431. default=CONFIG['DDS_MIPS'])
  3432. # Mesh options
  3433. EX_lodLevels = IntProperty(
  3434. name="LOD Levels",
  3435. description="MESH number of LOD levels",
  3436. min=0, max=32,
  3437. default=CONFIG['lodLevels'])
  3438. EX_lodDistance = IntProperty(
  3439. name="LOD Distance",
  3440. description="MESH distance increment to reduce LOD",
  3441. min=0, max=2000,
  3442. default=CONFIG['lodDistance'])
  3443. EX_lodPercent = IntProperty(
  3444. name="LOD Percentage",
  3445. description="LOD percentage reduction",
  3446. min=0, max=99,
  3447. default=CONFIG['lodPercent'])
  3448. EX_nuextremityPoints = IntProperty(
  3449. name="Extremity Points",
  3450. description="MESH Extremity Points",
  3451. min=0, max=65536,
  3452. default=CONFIG['nuextremityPoints'])
  3453. EX_generateEdgeLists = BoolProperty(
  3454. name="Edge Lists",
  3455. description="MESH generate edge lists (for stencil shadows)",
  3456. default=CONFIG['generateEdgeLists'])
  3457. EX_generateTangents = BoolProperty(
  3458. name="Tangents",
  3459. description="MESH generate tangents",
  3460. default=CONFIG['generateTangents'])
  3461. EX_tangentSemantic = StringProperty(
  3462. name="Tangent Semantic",
  3463. description="MESH tangent semantic",
  3464. maxlen=3,
  3465. default=CONFIG['tangentSemantic'])
  3466. EX_tangentUseParity = IntProperty(
  3467. name="Tangent Parity",
  3468. description="MESH tangent use parity",
  3469. min=0, max=16,
  3470. default=CONFIG['tangentUseParity'])
  3471. EX_tangentSplitMirrored = BoolProperty(
  3472. name="Tangent Split Mirrored",
  3473. description="MESH split mirrored tangents",
  3474. default=CONFIG['tangentSplitMirrored'])
  3475. EX_tangentSplitRotated = BoolProperty(
  3476. name="Tangent Split Rotated",
  3477. description="MESH split rotated tangents",
  3478. default=CONFIG['tangentSplitRotated'])
  3479. EX_reorganiseBuffers = BoolProperty(
  3480. name="Reorganise Buffers",
  3481. description="MESH reorganise vertex buffers",
  3482. default=CONFIG['reorganiseBuffers'])
  3483. EX_optimiseAnimations = BoolProperty(
  3484. name="Optimize Animations",
  3485. description="MESH optimize animations",
  3486. default=CONFIG['optimiseAnimations'])
  3487. filepath= StringProperty(
  3488. name="File Path",
  3489. description="Filepath used for exporting Ogre .scene file",
  3490. maxlen=1024,
  3491. default="",
  3492. subtype='FILE_PATH')
  3493. EXPORT_TYPE = 'OGRE'
  3494. ## UI panel Tundra export - Subclasses _OgreCommonExport_
  3495. class INFO_OT_createRealxtendExport( bpy.types.Operator, _OgreCommonExport_):
  3496. '''Export RealXtend Scene'''
  3497. bl_idname = "ogre.export_realxtend"
  3498. bl_label = "Export RealXtend"
  3499. bl_options = {'REGISTER', 'UNDO'}
  3500. EX_SWAP_AXIS = EnumProperty(
  3501. items=AXIS_MODES,
  3502. name='swap axis',
  3503. description='axis swapping mode',
  3504. default= CONFIG['SWAP_AXIS']
  3505. )
  3506. # Basic options
  3507. EX_SEP_MATS = BoolProperty(
  3508. name="Separate Materials",
  3509. description="exports a .material for each material (rather than putting all materials in a single .material file)",
  3510. default=CONFIG['SEP_MATS'])
  3511. EX_ONLY_DEFORMABLE_BONES = BoolProperty(
  3512. name="Only Deformable Bones",
  3513. description="only exports bones that are deformable. Useful for hiding IK-Bones used in Blender. Warning: Will cause trouble if a deformable bone has a non-deformable parent",
  3514. default=CONFIG['ONLY_DEFORMABLE_BONES'])
  3515. EX_ONLY_ANIMATED_BONES = BoolProperty(
  3516. name="Only Animated Bones",
  3517. description="only exports bones that have been keyframed, useful for run-time animation blending (example: upper/lower torso split)",
  3518. default=CONFIG['ONLY_ANIMATED_BONES'])
  3519. EX_SCENE = BoolProperty(
  3520. name="Export Scene",
  3521. description="export current scene (OgreDotScene xml)",
  3522. default=CONFIG['SCENE'])
  3523. EX_SELONLY = BoolProperty(
  3524. name="Export Selected Only",
  3525. description="export selected",
  3526. default=CONFIG['SELONLY'])
  3527. EX_FORCE_CAMERA = BoolProperty(
  3528. name="Force Camera",
  3529. description="export active camera",
  3530. default=CONFIG['FORCE_CAMERA'])
  3531. EX_FORCE_LAMPS = BoolProperty(
  3532. name="Force Lamps",
  3533. description="export all lamps",
  3534. default=CONFIG['FORCE_LAMPS'])
  3535. EX_MESH = BoolProperty(
  3536. name="Export Meshes",
  3537. description="export meshes",
  3538. default=CONFIG['MESH'])
  3539. EX_MESH_OVERWRITE = BoolProperty(
  3540. name="Export Meshes (overwrite)",
  3541. description="export meshes (overwrite existing files)",
  3542. default=CONFIG['MESH_OVERWRITE'])
  3543. EX_ARM_ANIM = BoolProperty(
  3544. name="Armature Animation",
  3545. description="export armature animations - updates the .skeleton file",
  3546. default=CONFIG['ARM_ANIM'])
  3547. EX_SHAPE_ANIM = BoolProperty(
  3548. name="Shape Animation",
  3549. description="export shape animations - updates the .mesh file",
  3550. default=CONFIG['SHAPE_ANIM'])
  3551. EX_INDEPENDENT_ANIM = BoolProperty(
  3552. name="Independent Animations",
  3553. description="Export each NLA-Strip independently. If unchecked NLA-Strips that overlap influence each other.",
  3554. default=CONFIG['INDEPENDENT_ANIM'])
  3555. EX_TRIM_BONE_WEIGHTS = FloatProperty(
  3556. name="Trim Weights",
  3557. description="ignore bone weights below this value (Ogre supports 4 bones per vertex)",
  3558. min=0.0, max=0.5, default=CONFIG['TRIM_BONE_WEIGHTS'] )
  3559. EX_ARRAY = BoolProperty(
  3560. name="Optimize Arrays",
  3561. description="optimize array modifiers as instances (constant offset only)",
  3562. default=CONFIG['ARRAY'])
  3563. EX_MATERIALS = BoolProperty(
  3564. name="Export Materials",
  3565. description="exports .material script",
  3566. default=CONFIG['MATERIALS'])
  3567. EX_FORCE_IMAGE_FORMAT = EnumProperty(
  3568. name='Convert Images',
  3569. description='convert all textures to format',
  3570. items=_IMAGE_FORMATS,
  3571. default=CONFIG['FORCE_IMAGE_FORMAT'])
  3572. EX_DDS_MIPS = IntProperty(
  3573. name="DDS Mips",
  3574. description="number of mip maps (DDS)",
  3575. min=0, max=16,
  3576. default=CONFIG['DDS_MIPS'])
  3577. # Mesh options
  3578. EX_lodLevels = IntProperty(
  3579. name="LOD Levels",
  3580. description="MESH number of LOD levels",
  3581. min=0, max=32,
  3582. default=CONFIG['lodLevels'])
  3583. EX_lodDistance = IntProperty(
  3584. name="LOD Distance",
  3585. description="MESH distance increment to reduce LOD",
  3586. min=0, max=2000,
  3587. default=CONFIG['lodDistance'])
  3588. EX_lodPercent = IntProperty(
  3589. name="LOD Percentage",
  3590. description="LOD percentage reduction",
  3591. min=0, max=99,
  3592. default=CONFIG['lodPercent'])
  3593. EX_nuextremityPoints = IntProperty(
  3594. name="Extremity Points",
  3595. description="MESH Extremity Points",
  3596. min=0, max=65536,
  3597. default=CONFIG['nuextremityPoints'])
  3598. EX_generateEdgeLists = BoolProperty(
  3599. name="Edge Lists",
  3600. description="MESH generate edge lists (for stencil shadows)",
  3601. default=CONFIG['generateEdgeLists'])
  3602. EX_generateTangents = BoolProperty(
  3603. name="Tangents",
  3604. description="MESH generate tangents",
  3605. default=CONFIG['generateTangents'])
  3606. EX_tangentSemantic = StringProperty(
  3607. name="Tangent Semantic",
  3608. description="MESH tangent semantic",
  3609. maxlen=3,
  3610. default=CONFIG['tangentSemantic'])
  3611. EX_tangentUseParity = IntProperty(
  3612. name="Tangent Parity",
  3613. description="MESH tangent use parity",
  3614. min=0, max=16,
  3615. default=CONFIG['tangentUseParity'])
  3616. EX_tangentSplitMirrored = BoolProperty(
  3617. name="Tangent Split Mirrored",
  3618. description="MESH split mirrored tangents",
  3619. default=CONFIG['tangentSplitMirrored'])
  3620. EX_tangentSplitRotated = BoolProperty(
  3621. name="Tangent Split Rotated",
  3622. description="MESH split rotated tangents",
  3623. default=CONFIG['tangentSplitRotated'])
  3624. EX_reorganiseBuffers = BoolProperty(
  3625. name="Reorganise Buffers",
  3626. description="MESH reorganise vertex buffers",
  3627. default=CONFIG['reorganiseBuffers'])
  3628. EX_optimiseAnimations = BoolProperty(
  3629. name="Optimize Animations",
  3630. description="MESH optimize animations",
  3631. default=CONFIG['optimiseAnimations'])
  3632. filepath = StringProperty(
  3633. name="File Path",
  3634. description="Filepath used for exporting .txml file",
  3635. maxlen=1024,
  3636. default="",
  3637. subtype='FILE_PATH')
  3638. EXPORT_TYPE = 'REX'
  3639. ## Ogre node helper
  3640. def _ogre_node_helper( doc, ob, objects, prefix='', pos=None, rot=None, scl=None ):
  3641. # shouldn't this be matrix_local?
  3642. mat = get_parent_matrix(ob, objects).inverted() * ob.matrix_world
  3643. o = doc.createElement('node')
  3644. o.setAttribute('name',prefix+ob.name)
  3645. p = doc.createElement('position')
  3646. q = doc.createElement('rotation') #('quaternion')
  3647. s = doc.createElement('scale')
  3648. for n in (p,q,s):
  3649. o.appendChild(n)
  3650. if pos:
  3651. v = swap(pos)
  3652. else:
  3653. v = swap( mat.to_translation() )
  3654. p.setAttribute('x', '%6f'%v.x)
  3655. p.setAttribute('y', '%6f'%v.y)
  3656. p.setAttribute('z', '%6f'%v.z)
  3657. if rot:
  3658. v = swap(rot)
  3659. else:
  3660. v = swap( mat.to_quaternion() )
  3661. q.setAttribute('qx', '%6f'%v.x)
  3662. q.setAttribute('qy', '%6f'%v.y)
  3663. q.setAttribute('qz', '%6f'%v.z)
  3664. q.setAttribute('qw','%6f'%v.w)
  3665. if scl: # this should not be used
  3666. v = swap(scl)
  3667. x=abs(v.x); y=abs(v.y); z=abs(v.z)
  3668. s.setAttribute('x', '%6f'%x)
  3669. s.setAttribute('y', '%6f'%y)
  3670. s.setAttribute('z', '%6f'%z)
  3671. else: # scale is different in Ogre from blender - rotation is removed
  3672. ri = mat.to_quaternion().inverted().to_matrix()
  3673. scale = ri.to_4x4() * mat
  3674. v = swap( scale.to_scale() )
  3675. x=abs(v.x); y=abs(v.y); z=abs(v.z)
  3676. s.setAttribute('x', '%6f'%x)
  3677. s.setAttribute('y', '%6f'%y)
  3678. s.setAttribute('z', '%6f'%z)
  3679. return o
  3680. ## MeshMagick
  3681. class MeshMagick(object):
  3682. ''' Usage: MeshMagick [global_options] toolname [tool_options] infile(s) -- [outfile(s)]
  3683. Available Tools
  3684. ===============
  3685. info - print information about the mesh.
  3686. meshmerge - Merge multiple submeshes into a single mesh.
  3687. optimise - Optimise meshes and skeletons.
  3688. rename - Rename different elements of meshes and skeletons.
  3689. transform - Scale, rotate or otherwise transform a mesh.
  3690. '''
  3691. @staticmethod
  3692. def get_merge_group( ob ):
  3693. return get_merge_group( ob, prefix='magicmerge' )
  3694. @staticmethod
  3695. def merge( group, path='/tmp', force_name=None ):
  3696. print('-'*80)
  3697. print(' mesh magick - merge ')
  3698. exe = CONFIG['OGRETOOLS_MESH_MAGICK']
  3699. if not os.path.isfile( exe ):
  3700. print( 'ERROR: can not find MeshMagick.exe' )
  3701. print( exe )
  3702. return
  3703. files = []
  3704. for ob in group.objects:
  3705. if ob.data.users == 1: # single users only
  3706. files.append( os.path.join( path, ob.data.name+'.mesh' ) )
  3707. print( files[-1] )
  3708. opts = 'meshmerge'
  3709. if sys.platform == 'linux2': cmd = '/usr/bin/wine %s %s' %(exe, opts)
  3710. else: cmd = '%s %s' %(exe, opts)
  3711. if force_name: output = force_name + '.mesh'
  3712. else: output = '_%s_.mesh' %group.name
  3713. cmd = cmd.split() + files + ['--', os.path.join(path,output) ]
  3714. subprocess.call( cmd )
  3715. print(' mesh magick - complete ')
  3716. print('-'*80)
  3717. ## Ogre Command Line Tools Documentation
  3718. _ogre_command_line_tools_doc = '''
  3719. Usage: OgreXMLConverter [options] sourcefile [destfile]
  3720. Available options:
  3721. -i = interactive mode - prompt for options
  3722. (The next 4 options are only applicable when converting XML to Mesh)
  3723. -l lodlevels = number of LOD levels
  3724. -v lodvalue = value increment to reduce LOD
  3725. -s lodstrategy = LOD strategy to use for this mesh
  3726. -p lodpercent = Percentage triangle reduction amount per LOD
  3727. -f lodnumtris = Fixed vertex reduction per LOD
  3728. -e = DON'T generate edge lists (for stencil shadows)
  3729. -r = DON'T reorganise vertex buffers to OGRE recommended format.
  3730. -t = Generate tangents (for normal mapping)
  3731. -td [uvw|tangent]
  3732. = Tangent vertex semantic destination (default tangent)
  3733. -ts [3|4] = Tangent size (3 or 4 components, 4 includes parity, default 3)
  3734. -tm = Split tangent vertices at UV mirror points
  3735. -tr = Split tangent vertices where basis is rotated > 90 degrees
  3736. -o = DON'T optimise out redundant tracks & keyframes
  3737. -d3d = Prefer D3D packed colour formats (default on Windows)
  3738. -gl = Prefer GL packed colour formats (default on non-Windows)
  3739. -E endian = Set endian mode 'big' 'little' or 'native' (default)
  3740. -x num = Generate no more than num eXtremes for every submesh (default 0)
  3741. -q = Quiet mode, less output
  3742. -log filename = name of the log file (default: 'OgreXMLConverter.log')
  3743. sourcefile = name of file to convert
  3744. destfile = optional name of file to write to. If you don't
  3745. specify this OGRE works it out through the extension
  3746. and the XML contents if the source is XML. For example
  3747. test.mesh becomes test.xml, test.xml becomes test.mesh
  3748. if the XML document root is <mesh> etc.
  3749. '''
  3750. ## Ogre Command Line Tools
  3751. def OgreXMLConverter( infile, has_uvs=False ):
  3752. # todo: Show a UI dialog to show this error. It's pretty fatal for normal usage.
  3753. # We should show how to configure the converter location in config panel or tell the default path.
  3754. exe = CONFIG['OGRETOOLS_XML_CONVERTER']
  3755. if not os.path.isfile( exe ):
  3756. print( 'WARNING: can not find OgreXMLConverter (can not convert XXX.mesh.xml to XXX.mesh' )
  3757. return
  3758. basicArguments = ''
  3759. if CONFIG['lodLevels']:
  3760. basicArguments += ' -l %s -v %s -p %s' %(CONFIG['lodLevels'], CONFIG['lodDistance'], CONFIG['lodPercent'])
  3761. if CONFIG['nuextremityPoints'] > 0:
  3762. basicArguments += ' -x %s' %CONFIG['nuextremityPoints']
  3763. if not CONFIG['generateEdgeLists']:
  3764. basicArguments += ' -e'
  3765. # note: OgreXmlConverter fails to convert meshes without UVs
  3766. if CONFIG['generateTangents'] and has_uvs:
  3767. basicArguments += ' -t'
  3768. if CONFIG['tangentSemantic']:
  3769. basicArguments += ' -td %s' %CONFIG['tangentSemantic']
  3770. if CONFIG['tangentUseParity']:
  3771. basicArguments += ' -ts %s' %CONFIG['tangentUseParity']
  3772. if CONFIG['tangentSplitMirrored']:
  3773. basicArguments += ' -tm'
  3774. if CONFIG['tangentSplitRotated']:
  3775. basicArguments += ' -tr'
  3776. if not CONFIG['reorganiseBuffers']:
  3777. basicArguments += ' -r'
  3778. if not CONFIG['optimiseAnimations']:
  3779. basicArguments += ' -o'
  3780. # Make xml converter print less stuff, comment this if you want more debug info out
  3781. basicArguments += ' -q'
  3782. opts = '-log _ogre_debug.txt %s' %basicArguments
  3783. path,name = os.path.split( infile )
  3784. cmd = '%s %s' %(exe, opts)
  3785. cmd = cmd.split() + [infile]
  3786. subprocess.call( cmd )
  3787. ## Bone
  3788. class Bone(object):
  3789. def __init__(self, rbone, pbone, skeleton):
  3790. if CONFIG['SWAP_AXIS'] == 'xyz':
  3791. self.fixUpAxis = False
  3792. else:
  3793. self.fixUpAxis = True
  3794. if CONFIG['SWAP_AXIS'] == '-xzy': # Tundra 1.x
  3795. self.flipMat = mathutils.Matrix(((-1,0,0,0),(0,0,1,0),(0,1,0,0),(0,0,0,1)))
  3796. elif CONFIG['SWAP_AXIS'] == 'xz-y': # Tundra 2.x current generation
  3797. #self.flipMat = mathutils.Matrix(((1,0,0,0),(0,0,1,0),(0,1,0,0),(0,0,0,1)))
  3798. self.flipMat = mathutils.Matrix(((1,0,0,0),(0,0,1,0),(0,-1,0,0),(0,0,0,1))) # thanks to Waruck
  3799. else:
  3800. print( 'ERROR - TODO: axis swap mode not supported with armature animation' )
  3801. assert 0
  3802. self.skeleton = skeleton
  3803. self.name = pbone.name
  3804. self.matrix = rbone.matrix_local.copy() # armature space
  3805. #self.matrix_local = rbone.matrix.copy() # space?
  3806. self.bone = pbone # safe to hold pointer to pose bone, not edit bone!
  3807. if pbone.parent and not pbone.parent.bone.use_deform and CONFIG['ONLY_DEFORMABLE_BONES']:
  3808. print('warning: bone <%s> has non-deformable parent.' %self.name)
  3809. # todo: Test -> #if pbone.bone.use_inherit_scale: print('warning: bone <%s> is using inherit scaling, Ogre has no support for this' %self.name)
  3810. self.parent = pbone.parent
  3811. self.children = []
  3812. def update(self): # called on frame update
  3813. pose = self.bone.matrix.copy()
  3814. self._inverse_total_trans_pose = pose.inverted()
  3815. # calculate difference to parent bone
  3816. if self.parent:
  3817. pose = self.parent._inverse_total_trans_pose* pose
  3818. elif self.fixUpAxis:
  3819. pose = self.flipMat * pose
  3820. else:
  3821. pass
  3822. self.pose_location = pose.to_translation() - self.ogre_rest_matrix.to_translation()
  3823. pose = self.inverse_ogre_rest_matrix * pose
  3824. self.pose_rotation = pose.to_quaternion()
  3825. self.pose_scale = pose.to_scale()
  3826. for child in self.children: child.update()
  3827. def rebuild_tree( self ): # called first on all bones
  3828. if self.parent:
  3829. self.parent = self.skeleton.get_bone( self.parent.name )
  3830. self.parent.children.append( self )
  3831. def compute_rest( self ): # called after rebuild_tree, recursive roots to leaves
  3832. if self.parent:
  3833. inverseParentMatrix = self.parent.inverse_total_trans
  3834. elif self.fixUpAxis:
  3835. inverseParentMatrix = self.flipMat
  3836. else:
  3837. inverseParentMatrix = mathutils.Matrix(((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)))
  3838. #self.ogre_rest_matrix = self.skeleton.object_space_transformation * self.matrix # ALLOW ROTATION?
  3839. self.ogre_rest_matrix = self.matrix.copy()
  3840. # store total inverse transformation
  3841. self.inverse_total_trans = self.ogre_rest_matrix.inverted()
  3842. # relative to OGRE parent bone origin
  3843. self.ogre_rest_matrix = inverseParentMatrix * self.ogre_rest_matrix
  3844. self.inverse_ogre_rest_matrix = self.ogre_rest_matrix.inverted()
  3845. # recursion
  3846. for child in self.children:
  3847. child.compute_rest()
  3848. # Skeleton
  3849. class Skeleton(object):
  3850. def get_bone( self, name ):
  3851. for b in self.bones:
  3852. if b.name == name: return b
  3853. def __init__(self, ob ):
  3854. if ob.location.x != 0 or ob.location.y != 0 or ob.location.z != 0:
  3855. Report.warnings.append('ERROR: Mesh (%s): is offset from Armature - zero transform is required' %ob.name)
  3856. if ob.scale.x != 1 or ob.scale.y != 1 or ob.scale.z != 1:
  3857. Report.warnings.append('ERROR: Mesh (%s): has been scaled - scale(1,1,1) is required' %ob.name)
  3858. self.object = ob
  3859. self.bones = []
  3860. mats = {}
  3861. self.arm = arm = ob.find_armature()
  3862. arm.hide = False
  3863. self._restore_layers = list(arm.layers)
  3864. #arm.layers = [True]*20 # can not have anything hidden - REQUIRED?
  3865. for pbone in arm.pose.bones:
  3866. if pbone.bone.use_deform or not CONFIG['ONLY_DEFORMABLE_BONES']:
  3867. mybone = Bone( arm.data.bones[pbone.name] ,pbone, self )
  3868. self.bones.append( mybone )
  3869. if arm.name not in Report.armatures:
  3870. Report.armatures.append( arm.name )
  3871. ## bad idea - allowing rotation of armature, means vertices must also be rotated,
  3872. ## also a bug with applying the rotation, the Z rotation is lost
  3873. #x,y,z = arm.matrix_local.copy().inverted().to_euler()
  3874. #e = mathutils.Euler( (x,z,y) )
  3875. #self.object_space_transformation = e.to_matrix().to_4x4()
  3876. x,y,z = arm.matrix_local.to_euler()
  3877. if x != 0 or y != 0 or z != 0:
  3878. Report.warnings.append('ERROR: Armature: %s is rotated - (rotation is ignored)' %arm.name)
  3879. ## setup bones for Ogre format ##
  3880. for b in self.bones: b.rebuild_tree()
  3881. ## walk bones, convert them ##
  3882. self.roots = []
  3883. ep = 0.0001
  3884. for b in self.bones:
  3885. if not b.parent:
  3886. b.compute_rest()
  3887. loc,rot,scl = b.ogre_rest_matrix.decompose()
  3888. #if loc.x or loc.y or loc.z:
  3889. # Report.warnings.append('ERROR: root bone has non-zero transform (location offset)')
  3890. #if rot.w > ep or rot.x > ep or rot.y > ep or rot.z < 1.0-ep:
  3891. # Report.warnings.append('ERROR: root bone has non-zero transform (rotation offset)')
  3892. self.roots.append( b )
  3893. def to_xml( self ):
  3894. _fps = float( bpy.context.scene.render.fps )
  3895. doc = RDocument()
  3896. root = doc.createElement('skeleton'); doc.appendChild( root )
  3897. bones = doc.createElement('bones'); root.appendChild( bones )
  3898. bh = doc.createElement('bonehierarchy'); root.appendChild( bh )
  3899. for i,bone in enumerate(self.bones):
  3900. b = doc.createElement('bone')
  3901. b.setAttribute('name', bone.name)
  3902. b.setAttribute('id', str(i) )
  3903. bones.appendChild( b )
  3904. mat = bone.ogre_rest_matrix.copy()
  3905. if bone.parent:
  3906. bp = doc.createElement('boneparent')
  3907. bp.setAttribute('bone', bone.name)
  3908. bp.setAttribute('parent', bone.parent.name)
  3909. bh.appendChild( bp )
  3910. pos = doc.createElement( 'position' ); b.appendChild( pos )
  3911. x,y,z = mat.to_translation()
  3912. pos.setAttribute('x', '%6f' %x )
  3913. pos.setAttribute('y', '%6f' %y )
  3914. pos.setAttribute('z', '%6f' %z )
  3915. rot = doc.createElement( 'rotation' ) # "rotation", not "rotate"
  3916. b.appendChild( rot )
  3917. q = mat.to_quaternion()
  3918. rot.setAttribute('angle', '%6f' %q.angle )
  3919. axis = doc.createElement('axis'); rot.appendChild( axis )
  3920. x,y,z = q.axis
  3921. axis.setAttribute('x', '%6f' %x )
  3922. axis.setAttribute('y', '%6f' %y )
  3923. axis.setAttribute('z', '%6f' %z )
  3924. # Ogre bones do not have initial scaling? ##
  3925. # note: Ogre bones by default do not pass down their scaling in animation,
  3926. # so in blender all bones are like 'do-not-inherit-scaling'
  3927. if 0:
  3928. scale = doc.createElement('scale'); b.appendChild( scale )
  3929. x,y,z = swap( mat.to_scale() )
  3930. scale.setAttribute('x', str(x))
  3931. scale.setAttribute('y', str(y))
  3932. scale.setAttribute('z', str(z))
  3933. arm = self.arm
  3934. if not arm.animation_data or (arm.animation_data and not arm.animation_data.nla_tracks): # assume animated via constraints and use blender timeline.
  3935. anims = doc.createElement('animations'); root.appendChild( anims )
  3936. anim = doc.createElement('animation'); anims.appendChild( anim )
  3937. tracks = doc.createElement('tracks'); anim.appendChild( tracks )
  3938. anim.setAttribute('name', 'my_animation')
  3939. start = bpy.context.scene.frame_start; end = bpy.context.scene.frame_end
  3940. anim.setAttribute('length', str( (end-start)/_fps ) )
  3941. _keyframes = {}
  3942. _bonenames_ = []
  3943. for bone in arm.pose.bones:
  3944. if self.get_bone(bone.name): #check if the bone was exported
  3945. _bonenames_.append( bone.name )
  3946. track = doc.createElement('track')
  3947. track.setAttribute('bone', bone.name)
  3948. tracks.appendChild( track )
  3949. keyframes = doc.createElement('keyframes')
  3950. track.appendChild( keyframes )
  3951. _keyframes[ bone.name ] = keyframes
  3952. for frame in range( int(start), int(end)+1, bpy.context.scene.frame_step):
  3953. bpy.context.scene.frame_set(frame)
  3954. for bone in self.roots: bone.update()
  3955. print('\t\t Frame:', frame)
  3956. for bonename in _bonenames_:
  3957. if self.get_bone(bonename): #check if the bone was exported
  3958. bone = self.get_bone( bonename )
  3959. _loc = bone.pose_location
  3960. _rot = bone.pose_rotation
  3961. _scl = bone.pose_scale
  3962. keyframe = doc.createElement('keyframe')
  3963. keyframe.setAttribute('time', str((frame-start)/_fps))
  3964. _keyframes[ bonename ].appendChild( keyframe )
  3965. trans = doc.createElement('translate')
  3966. keyframe.appendChild( trans )
  3967. x,y,z = _loc
  3968. trans.setAttribute('x', '%6f' %x)
  3969. trans.setAttribute('y', '%6f' %y)
  3970. trans.setAttribute('z', '%6f' %z)
  3971. rot = doc.createElement( 'rotate' )
  3972. keyframe.appendChild( rot )
  3973. q = _rot
  3974. rot.setAttribute('angle', '%6f' %q.angle )
  3975. axis = doc.createElement('axis'); rot.appendChild( axis )
  3976. x,y,z = q.axis
  3977. axis.setAttribute('x', '%6f' %x )
  3978. axis.setAttribute('y', '%6f' %y )
  3979. axis.setAttribute('z', '%6f' %z )
  3980. scale = doc.createElement('scale')
  3981. keyframe.appendChild( scale )
  3982. x,y,z = _scl
  3983. scale.setAttribute('x', '%6f' %x)
  3984. scale.setAttribute('y', '%6f' %y)
  3985. scale.setAttribute('z', '%6f' %z)
  3986. elif arm.animation_data:
  3987. anims = doc.createElement('animations'); root.appendChild( anims )
  3988. if not len( arm.animation_data.nla_tracks ):
  3989. Report.warnings.append('you must assign an NLA strip to armature (%s) that defines the start and end frames' %arm.name)
  3990. if CONFIG['INDEPENDENT_ANIM']:
  3991. for nla in arm.animation_data.nla_tracks:
  3992. nla.mute = True
  3993. for nla in arm.animation_data.nla_tracks: # NLA required, lone actions not supported
  3994. if not len(nla.strips): print( 'skipping empty NLA track: %s' %nla.name ); continue
  3995. print('NLA track:', nla.name)
  3996. if CONFIG['INDEPENDENT_ANIM']:
  3997. nla.mute = False
  3998. for strip in nla.strips:
  3999. strip.mute = True
  4000. for strip in nla.strips:
  4001. if CONFIG['INDEPENDENT_ANIM']: strip.mute = False
  4002. print(' strip name:', strip.name)
  4003. anim = doc.createElement('animation'); anims.appendChild( anim )
  4004. tracks = doc.createElement('tracks'); anim.appendChild( tracks )
  4005. Report.armature_animations.append( '%s : %s [start frame=%s end frame=%s]' %(arm.name, nla.name, strip.frame_start, strip.frame_end) )
  4006. anim.setAttribute('name', strip.name) # USE the strip name
  4007. anim.setAttribute('length', str( (strip.frame_end-strip.frame_start)/_fps ) )
  4008. stripbones = []
  4009. if CONFIG['ONLY_ANIMATED_BONES']:
  4010. for group in strip.action.groups: # check if the user has keyed only some of the bones (for anim blending)
  4011. if group.name in arm.pose.bones: stripbones.append( group.name )
  4012. if not stripbones: # otherwise we use all bones
  4013. stripbones = [ bone.name for bone in arm.pose.bones ]
  4014. else:
  4015. stripbones = [ bone.name for bone in arm.pose.bones ]
  4016. _keyframes = {}
  4017. for bonename in stripbones:
  4018. if self.get_bone(bonename): #check if the bone was exported
  4019. track = doc.createElement('track')
  4020. track.setAttribute('bone', bonename)
  4021. tracks.appendChild( track )
  4022. keyframes = doc.createElement('keyframes')
  4023. track.appendChild( keyframes )
  4024. _keyframes[ bonename ] = keyframes
  4025. for frame in range( int(strip.frame_start), int(strip.frame_end)+1, bpy.context.scene.frame_step):#thanks to Vesa
  4026. bpy.context.scene.frame_set(frame)
  4027. for bone in self.roots: bone.update()
  4028. for bonename in stripbones:
  4029. if self.get_bone( bonename ): #check if the bone was exported
  4030. bone = self.get_bone( bonename )
  4031. _loc = bone.pose_location
  4032. _rot = bone.pose_rotation
  4033. _scl = bone.pose_scale
  4034. keyframe = doc.createElement('keyframe')
  4035. keyframe.setAttribute('time', str((frame-strip.frame_start)/_fps))
  4036. _keyframes[ bonename ].appendChild( keyframe )
  4037. trans = doc.createElement('translate')
  4038. keyframe.appendChild( trans )
  4039. x,y,z = _loc
  4040. trans.setAttribute('x', '%6f' %x)
  4041. trans.setAttribute('y', '%6f' %y)
  4042. trans.setAttribute('z', '%6f' %z)
  4043. rot = doc.createElement( 'rotate' )
  4044. keyframe.appendChild( rot )
  4045. q = _rot
  4046. rot.setAttribute('angle', '%6f' %q.angle )
  4047. axis = doc.createElement('axis'); rot.appendChild( axis )
  4048. x,y,z = q.axis
  4049. axis.setAttribute('x', '%6f' %x )
  4050. axis.setAttribute('y', '%6f' %y )
  4051. axis.setAttribute('z', '%6f' %z )
  4052. scale = doc.createElement('scale')
  4053. keyframe.appendChild( scale )
  4054. x,y,z = _scl
  4055. scale.setAttribute('x', '%6f' %x)
  4056. scale.setAttribute('y', '%6f' %y)
  4057. scale.setAttribute('z', '%6f' %z)
  4058. if CONFIG['INDEPENDENT_ANIM']: strip.mute = True
  4059. if CONFIG['INDEPENDENT_ANIM']:
  4060. nla.mute = True
  4061. for strip in nla.strips:
  4062. strip.mute = False
  4063. if CONFIG['INDEPENDENT_ANIM']:
  4064. for nla in arm.animation_data.nla_tracks:
  4065. nla.mute = False
  4066. return doc.toprettyxml()
  4067. ## Selector extras
  4068. class INFO_MT_instances(bpy.types.Menu):
  4069. bl_label = "Instances"
  4070. def draw(self, context):
  4071. layout = self.layout
  4072. inst = gather_instances()
  4073. for data in inst:
  4074. ob = inst[data][0]
  4075. op = layout.operator(INFO_MT_instance.bl_idname, text=ob.name) # operator has no variable for button name?
  4076. op.mystring = ob.name
  4077. layout.separator()
  4078. class INFO_MT_instance(bpy.types.Operator):
  4079. '''select instance group'''
  4080. bl_idname = "ogre.select_instances"
  4081. bl_label = "Select Instance Group"
  4082. bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
  4083. mystring= StringProperty(name="MyString", description="hidden string", maxlen=1024, default="my string")
  4084. @classmethod
  4085. def poll(cls, context):
  4086. return True
  4087. def invoke(self, context, event):
  4088. print( 'invoke select_instances op', event )
  4089. select_instances( context, self.mystring )
  4090. return {'FINISHED'}
  4091. class INFO_MT_groups(bpy.types.Menu):
  4092. bl_label = "Groups"
  4093. def draw(self, context):
  4094. layout = self.layout
  4095. for group in bpy.data.groups:
  4096. op = layout.operator(INFO_MT_group.bl_idname, text=group.name) # operator no variable for button name?
  4097. op.mystring = group.name
  4098. layout.separator()
  4099. class INFO_MT_group(bpy.types.Operator):
  4100. '''select group'''
  4101. bl_idname = "ogre.select_group"
  4102. bl_label = "Select Group"
  4103. bl_options = {'REGISTER'} # Options for this panel type
  4104. mystring= StringProperty(name="MyString", description="hidden string", maxlen=1024, default="my string")
  4105. @classmethod
  4106. def poll(cls, context):
  4107. return True
  4108. def invoke(self, context, event):
  4109. select_group( context, self.mystring )
  4110. return {'FINISHED'}
  4111. ## NVIDIA texture tool documentation
  4112. NVDXT_DOC = '''
  4113. Version 8.30
  4114. NVDXT
  4115. This program
  4116. compresses images
  4117. creates normal maps from color or alpha
  4118. creates DuDv map
  4119. creates cube maps
  4120. writes out .dds file
  4121. does batch processing
  4122. reads .tga, .bmp, .gif, .ppm, .jpg, .tif, .cel, .dds, .png, .psd, .rgb, *.bw and .rgba
  4123. filters MIP maps
  4124. Options:
  4125. -profile <profile name> : Read a profile created from the Photoshop plugin
  4126. -quick : use fast compression method
  4127. -quality_normal : normal quality compression
  4128. -quality_production : production quality compression
  4129. -quality_highest : highest quality compression (this can be very slow)
  4130. -rms_threshold <int> : quality RMS error. Above this, an extensive search is performed.
  4131. -prescale <int> <int>: rescale image to this size first
  4132. -rescale <nearest | hi | lo | next_lo>: rescale image to nearest, next highest or next lowest power of two
  4133. -rel_scale <float, float> : relative scale of original image. 0.5 is half size Default 1.0, 1.0
  4134. Optional Filtering for rescaling. Default cube filter:
  4135. -RescalePoint
  4136. -RescaleBox
  4137. -RescaleTriangle
  4138. -RescaleQuadratic
  4139. -RescaleCubic
  4140. -RescaleCatrom
  4141. -RescaleMitchell
  4142. -RescaleGaussian
  4143. -RescaleSinc
  4144. -RescaleBessel
  4145. -RescaleHanning
  4146. -RescaleHamming
  4147. -RescaleBlackman
  4148. -RescaleKaiser
  4149. -clamp <int, int> : maximum image size. image width and height are clamped
  4150. -clampScale <int, int> : maximum image size. image width and height are scaled
  4151. -window <left, top, right, bottom> : window of original window to compress
  4152. -nomipmap : don't generate MIP maps
  4153. -nmips <int> : specify the number of MIP maps to generate
  4154. -rgbe : Image is RGBE format
  4155. -dither : add dithering
  4156. -sharpenMethod <method>: sharpen method MIP maps
  4157. <method> is
  4158. None
  4159. Negative
  4160. Lighter
  4161. Darker
  4162. ContrastMore
  4163. ContrastLess
  4164. Smoothen
  4165. SharpenSoft
  4166. SharpenMedium
  4167. SharpenStrong
  4168. FindEdges
  4169. Contour
  4170. EdgeDetect
  4171. EdgeDetectSoft
  4172. Emboss
  4173. MeanRemoval
  4174. UnSharp <radius, amount, threshold>
  4175. XSharpen <xsharpen_strength, xsharpen_threshold>
  4176. Custom
  4177. -pause : wait for keyboard on error
  4178. -flip : flip top to bottom
  4179. -timestamp : Update only changed files
  4180. -list <filename> : list of files to convert
  4181. -cubeMap : create cube map .
  4182. Cube faces specified with individual files with -list option
  4183. positive x, negative x, positive y, negative y, positive z, negative z
  4184. Use -output option to specify filename
  4185. Cube faces specified in one file. Use -file to specify input filename
  4186. -volumeMap : create volume texture.
  4187. Volume slices specified with individual files with -list option
  4188. Use -output option to specify filename
  4189. Volume specified in one file. Use -file to specify input filename
  4190. -all : all image files in current directory
  4191. -outdir <directory>: output directory
  4192. -deep [directory]: include all subdirectories
  4193. -outsamedir : output directory same as input
  4194. -overwrite : if input is .dds file, overwrite old file
  4195. -forcewrite : write over readonly files
  4196. -file <filename> : input file to process. Accepts wild cards
  4197. -output <filename> : filename to write to [-outfile can also be specified]
  4198. -append <filename_append> : append this string to output filename
  4199. -8 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555 | L8 | A8> : compress 8 bit images with this format
  4200. -16 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555 | A8L8> : compress 16 bit images with this format
  4201. -24 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555> : compress 24 bit images with this format
  4202. -32 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555> : compress 32 bit images with this format
  4203. -swapRB : swap rb
  4204. -swapRG : swap rg
  4205. -gamma <float value>: gamma correcting during filtering
  4206. -outputScale <float, float, float, float>: scale the output by this (r,g,b,a)
  4207. -outputBias <float, float, float, float>: bias the output by this amount (r,g,b,a)
  4208. -outputWrap : wraps overflow values modulo the output format
  4209. -inputScale <float, float, float, float>: scale the inpput by this (r,g,b,a)
  4210. -inputBias <float, float, float, float>: bias the input by this amount (r,g,b,a)
  4211. -binaryalpha : treat alpha as 0 or 1
  4212. -alpha_threshold <byte>: [0-255] alpha reference value
  4213. -alphaborder : border images with alpha = 0
  4214. -alphaborderLeft : border images with alpha (left) = 0
  4215. -alphaborderRight : border images with alpha (right)= 0
  4216. -alphaborderTop : border images with alpha (top) = 0
  4217. -alphaborderBottom : border images with alpha (bottom)= 0
  4218. -fadeamount <int>: percentage to fade each MIP level. Default 15
  4219. -fadecolor : fade map (color, normal or DuDv) over MIP levels
  4220. -fadetocolor <hex color> : color to fade to
  4221. -custom_fade <n> <n fadeamounts> : set custom fade amount. n is number number of fade amounts. fadeamount are [0,1]
  4222. -fadealpha : fade alpha over MIP levels
  4223. -fadetoalpha <byte>: [0-255] alpha to fade to
  4224. -border : border images with color
  4225. -bordercolor <hex color> : color for border
  4226. -force4 : force DXT1c to use always four colors
  4227. -weight <float, float, float>: Compression weightings for R G and B
  4228. -luminance : convert color values to luminance for L8 formats
  4229. -greyScale : Convert to grey scale
  4230. -greyScaleWeights <float, float, float, float>: override greyscale conversion weights of (0.3086, 0.6094, 0.0820, 0)
  4231. -brightness <float, float, float, float>: per channel brightness. Default 0.0 usual range [0,1]
  4232. -contrast <float, float, float, float>: per channel contrast. Default 1.0 usual range [0.5, 1.5]
  4233. Texture Format Default DXT3:
  4234. -dxt1c : DXT1 (color only)
  4235. -dxt1a : DXT1 (one bit alpha)
  4236. -dxt3 : DXT3
  4237. -dxt5 : DXT5n
  4238. -u1555 : uncompressed 1:5:5:5
  4239. -u4444 : uncompressed 4:4:4:4
  4240. -u565 : uncompressed 5:6:5
  4241. -u8888 : uncompressed 8:8:8:8
  4242. -u888 : uncompressed 0:8:8:8
  4243. -u555 : uncompressed 0:5:5:5
  4244. -p8c : paletted 8 bit (256 colors)
  4245. -p8a : paletted 8 bit (256 colors with alpha)
  4246. -p4c : paletted 4 bit (16 colors)
  4247. -p4a : paletted 4 bit (16 colors with alpha)
  4248. -a8 : 8 bit alpha channel
  4249. -cxv8u8 : normal map format
  4250. -v8u8 : EMBM format (8, bit two component signed)
  4251. -v16u16 : EMBM format (16 bit, two component signed)
  4252. -A8L8 : 8 bit alpha channel, 8 bit luminance
  4253. -fp32x4 : fp32 four channels (A32B32G32R32F)
  4254. -fp32 : fp32 one channel (R32F)
  4255. -fp16x4 : fp16 four channels (A16B16G16R16F)
  4256. -dxt5nm : dxt5 style normal map
  4257. -3Dc : 3DC
  4258. -g16r16 : 16 bit in, two component
  4259. -g16r16f : 16 bit float, two components
  4260. Mip Map Filtering Options. Default box filter:
  4261. -Point
  4262. -Box
  4263. -Triangle
  4264. -Quadratic
  4265. -Cubic
  4266. -Catrom
  4267. -Mitchell
  4268. -Gaussian
  4269. -Sinc
  4270. -Bessel
  4271. -Hanning
  4272. -Hamming
  4273. -Blackman
  4274. -Kaiser
  4275. ***************************
  4276. To make a normal or dudv map, specify one of
  4277. -n4 : normal map 4 sample
  4278. -n3x3 : normal map 3x3 filter
  4279. -n5x5 : normal map 5x5 filter
  4280. -n7x7 : normal map 7x7 filter
  4281. -n9x9 : normal map 9x9 filter
  4282. -dudv : DuDv
  4283. and source of height info:
  4284. -alpha : alpha channel
  4285. -rgb : average rgb
  4286. -biased : average rgb biased
  4287. -red : red channel
  4288. -green : green channel
  4289. -blue : blue channel
  4290. -max : max of (r,g,b)
  4291. -colorspace : mix of r,g,b
  4292. -norm : normalize mip maps (source is a normal map)
  4293. -toHeight : create a height map (source is a normal map)
  4294. Normal/DuDv Map dxt:
  4295. -aheight : store calculated height in alpha field
  4296. -aclear : clear alpha channel
  4297. -awhite : set alpha channel = 1.0
  4298. -scale <float> : scale of height map. Default 1.0
  4299. -wrap : wrap texture around. Default off
  4300. -minz <int> : minimum value for up vector [0-255]. Default 0
  4301. ***************************
  4302. To make a depth sprite, specify:
  4303. -depth
  4304. and source of depth info:
  4305. -alpha : alpha channel
  4306. -rgb : average rgb (default)
  4307. -red : red channel
  4308. -green : green channel
  4309. -blue : blue channel
  4310. -max : max of (r,g,b)
  4311. -colorspace : mix of r,g,b
  4312. Depth Sprite dxt:
  4313. -aheight : store calculated depth in alpha channel
  4314. -aclear : store 0.0 in alpha channel
  4315. -awhite : store 1.0 in alpha channel
  4316. -scale <float> : scale of depth sprite (default 1.0)
  4317. -alpha_modulate : multiplies color by alpha during filtering
  4318. -pre_modulate : multiplies color by alpha before processing
  4319. Examples
  4320. nvdxt -cubeMap -list cubemapfile.lst -output cubemap.dds
  4321. nvdxt -cubeMap -file cubemapfile.tga
  4322. nvdxt -file test.tga -dxt1c
  4323. nvdxt -file *.tga
  4324. nvdxt -file c:\temp\*.tga
  4325. nvdxt -file temp\*.tga
  4326. nvdxt -file height_field_in_alpha.tga -n3x3 -alpha -scale 10 -wrap
  4327. nvdxt -file grey_scale_height_field.tga -n5x5 -rgb -scale 1.3
  4328. nvdxt -file normal_map.tga -norm
  4329. nvdxt -file image.tga -dudv -fade -fadeamount 10
  4330. nvdxt -all -dxt3 -gamma -outdir .\dds_dir -time
  4331. nvdxt -file *.tga -depth -max -scale 0.5
  4332. '''
  4333. try:
  4334. import io_export_rogremesh.rogremesh as Rmesh
  4335. except:
  4336. Rmesh = None
  4337. print( 'WARNING: "io_export_rogremesh" is missing' )
  4338. if Rmesh and Rmesh.rpy.load():
  4339. _USE_RPYTHON_ = True
  4340. else:
  4341. _USE_RPYTHON_ = False
  4342. print( 'Rpython module is not cached, you must exit Blender to compile the module:' )
  4343. print( 'cd io_export_rogremesh; python rogremesh.py' )
  4344. class VertexNoPos(object):
  4345. def __init__(self, ogre_vidx, nx,ny,nz, r,g,b,ra, vert_uvs):
  4346. self.ogre_vidx = ogre_vidx
  4347. self.nx = nx
  4348. self.ny = ny
  4349. self.nz = nz
  4350. self.r = r
  4351. self.g = g
  4352. self.b = b
  4353. self.ra = ra
  4354. self.vert_uvs = vert_uvs
  4355. '''does not compare ogre_vidx (and position at the moment) [ no need to compare position ]'''
  4356. def __eq__(self, o):
  4357. if self.nx != o.nx or self.ny != o.ny or self.nz != o.nz: return False
  4358. elif self.r != o.r or self.g != o.g or self.b != o.b or self.ra != o.ra: return False
  4359. elif len(self.vert_uvs) != len(o.vert_uvs): return False
  4360. elif self.vert_uvs:
  4361. for i, uv1 in enumerate( self.vert_uvs ):
  4362. uv2 = o.vert_uvs[ i ]
  4363. if uv1 != uv2: return False
  4364. return True
  4365. ## Creating .mesh
  4366. def dot_mesh( ob, path='/tmp', force_name=None, ignore_shape_animation=False, normals=True ):
  4367. start = time.time()
  4368. if not os.path.isdir( path ):
  4369. print('>> Creating working directory', path )
  4370. os.makedirs( path )
  4371. Report.meshes.append( ob.data.name )
  4372. Report.faces += len( ob.data.tessfaces )
  4373. Report.orig_vertices += len( ob.data.vertices )
  4374. cleanup = False
  4375. if ob.modifiers:
  4376. cleanup = True
  4377. copy = ob.copy()
  4378. #bpy.context.scene.objects.link(copy)
  4379. rem = []
  4380. for mod in copy.modifiers: # remove armature and array modifiers before collaspe
  4381. if mod.type in 'ARMATURE ARRAY'.split(): rem.append( mod )
  4382. for mod in rem: copy.modifiers.remove( mod )
  4383. # bake mesh
  4384. mesh = copy.to_mesh(bpy.context.scene, True, "PREVIEW") # collaspe
  4385. else:
  4386. copy = ob
  4387. mesh = ob.data
  4388. name = force_name or ob.data.name
  4389. xmlfile = os.path.join(path, '%s.mesh.xml' %name )
  4390. print(' - Generating:', '%s.mesh.xml' %name)
  4391. if _USE_RPYTHON_ and False:
  4392. Rmesh.save( ob, xmlfile )
  4393. else:
  4394. f = None
  4395. try:
  4396. f = open( xmlfile, 'w' )
  4397. except Exception as e:
  4398. show_dialog("Invalid mesh object name: " + name)
  4399. return
  4400. doc = SimpleSaxWriter(f, 'UTF-8', "mesh", {})
  4401. # Very ugly, have to replace number of vertices later
  4402. doc.start_tag('sharedgeometry', {'vertexcount' : '__TO_BE_REPLACED_VERTEX_COUNT__'})
  4403. print(' - Writing shared geometry')
  4404. doc.start_tag('vertexbuffer', {
  4405. 'positions':'true',
  4406. 'normals':'true',
  4407. 'colours_diffuse' : str(bool( mesh.vertex_colors )),
  4408. 'texture_coords' : '%s' % len(mesh.uv_textures) if mesh.uv_textures.active else '0'
  4409. })
  4410. # Vertex colors
  4411. vcolors = None
  4412. vcolors_alpha = None
  4413. if len( mesh.tessface_vertex_colors ):
  4414. vcolors = mesh.tessface_vertex_colors[0]
  4415. for bloc in mesh.tessface_vertex_colors:
  4416. if bloc.name.lower().startswith('alpha'):
  4417. vcolors_alpha = bloc; break
  4418. # Materials
  4419. materials = []
  4420. for mat in ob.data.materials:
  4421. if mat:
  4422. materials.append( mat )
  4423. else:
  4424. print('[WARNING:] Bad material data in', ob)
  4425. materials.append( '_missing_material_' ) # fixed dec22, keep proper index
  4426. if not materials:
  4427. materials.append( '_missing_material_' )
  4428. _sm_faces_ = []
  4429. for matidx, mat in enumerate( materials ):
  4430. _sm_faces_.append([])
  4431. # Textures
  4432. dotextures = False
  4433. uvcache = [] # should get a little speed boost by this cache
  4434. if mesh.tessface_uv_textures.active:
  4435. dotextures = True
  4436. for layer in mesh.tessface_uv_textures:
  4437. uvs = []; uvcache.append( uvs ) # layer contains: name, active, data
  4438. for uvface in layer.data:
  4439. uvs.append( (uvface.uv1, uvface.uv2, uvface.uv3, uvface.uv4) )
  4440. _sm_vertices_ = {}
  4441. _remap_verts_ = []
  4442. numverts = 0
  4443. for F in mesh.tessfaces:
  4444. smooth = F.use_smooth
  4445. faces = _sm_faces_[ F.material_index ]
  4446. # Ogre only supports triangles
  4447. tris = []
  4448. tris.append( (F.vertices[0], F.vertices[1], F.vertices[2]) )
  4449. if len(F.vertices) >= 4: tris.append( (F.vertices[0], F.vertices[2], F.vertices[3]) )
  4450. if dotextures:
  4451. a = []; b = []
  4452. uvtris = [ a, b ]
  4453. for layer in uvcache:
  4454. uv1, uv2, uv3, uv4 = layer[ F.index ]
  4455. a.append( (uv1, uv2, uv3) )
  4456. b.append( (uv1, uv3, uv4) )
  4457. for tidx, tri in enumerate(tris):
  4458. face = []
  4459. for vidx, idx in enumerate(tri):
  4460. v = mesh.vertices[ idx ]
  4461. if smooth:
  4462. nx,ny,nz = swap( v.normal ) # fixed june 17th 2011
  4463. else:
  4464. nx,ny,nz = swap( F.normal )
  4465. r = 1.0
  4466. g = 1.0
  4467. b = 1.0
  4468. ra = 1.0
  4469. if vcolors:
  4470. k = list(F.vertices).index(idx)
  4471. r,g,b = getattr( vcolors.data[ F.index ], 'color%s'%(k+1) )
  4472. if vcolors_alpha:
  4473. ra,ga,ba = getattr( vcolors_alpha.data[ F.index ], 'color%s'%(k+1) )
  4474. else:
  4475. ra = 1.0
  4476. # Texture maps
  4477. vert_uvs = []
  4478. if dotextures:
  4479. for layer in uvtris[ tidx ]:
  4480. vert_uvs.append(layer[ vidx ])
  4481. ''' Check if we already exported that vertex with same normal, do not export in that case,
  4482. (flat shading in blender seems to work with face normals, so we copy each flat face'
  4483. vertices, if this vertex with same normals was already exported,
  4484. todo: maybe not best solution, check other ways (let blender do all the work, or only
  4485. support smooth shading, what about seems, smoothing groups, materials, ...)
  4486. '''
  4487. vert = VertexNoPos(numverts, nx, ny, nz, r, g, b, ra, vert_uvs)
  4488. alreadyExported = False
  4489. if idx in _sm_vertices_:
  4490. for vert2 in _sm_vertices_[idx]:
  4491. #does not compare ogre_vidx (and position at the moment)
  4492. if vert == vert2:
  4493. face.append(vert2.ogre_vidx)
  4494. alreadyExported = True
  4495. #print(idx,numverts, nx,ny,nz, r,g,b,ra, vert_uvs, "already exported")
  4496. break
  4497. if not alreadyExported:
  4498. face.append(vert.ogre_vidx)
  4499. _sm_vertices_[idx].append(vert)
  4500. #print(numverts, nx,ny,nz, r,g,b,ra, vert_uvs, "appended")
  4501. else:
  4502. face.append(vert.ogre_vidx)
  4503. _sm_vertices_[idx] = [vert]
  4504. #print(idx, numverts, nx,ny,nz, r,g,b,ra, vert_uvs, "created")
  4505. if alreadyExported:
  4506. continue
  4507. numverts += 1
  4508. _remap_verts_.append( v )
  4509. x,y,z = swap(v.co) # xz-y is correct!
  4510. doc.start_tag('vertex', {})
  4511. doc.leaf_tag('position', {
  4512. 'x' : '%6f' % x,
  4513. 'y' : '%6f' % y,
  4514. 'z' : '%6f' % z
  4515. })
  4516. doc.leaf_tag('normal', {
  4517. 'x' : '%6f' % nx,
  4518. 'y' : '%6f' % ny,
  4519. 'z' : '%6f' % nz
  4520. })
  4521. if vcolors:
  4522. doc.leaf_tag('colour_diffuse', {'value' : '%6f %6f %6f %6f' % (r,g,b,ra)})
  4523. # Texture maps
  4524. if dotextures:
  4525. for uv in vert_uvs:
  4526. doc.leaf_tag('texcoord', {
  4527. 'u' : '%6f' % uv[0],
  4528. 'v' : '%6f' % (1.0-uv[1])
  4529. })
  4530. doc.end_tag('vertex')
  4531. faces.append( (face[0], face[1], face[2]) )
  4532. del(_sm_vertices_)
  4533. Report.vertices += numverts
  4534. doc.end_tag('vertexbuffer')
  4535. doc.end_tag('sharedgeometry')
  4536. print(' Done at', timer_diff_str(start), "seconds")
  4537. print(' - Writing submeshes')
  4538. doc.start_tag('submeshes', {})
  4539. for matidx, mat in enumerate( materials ):
  4540. if not len(_sm_faces_[matidx]):
  4541. Report.warnings.append( 'BAD SUBMESH: %s' %ob.name )
  4542. continue # fixes corrupt unused materials
  4543. doc.start_tag('submesh', {
  4544. 'usesharedvertices' : 'true',
  4545. 'material' : material_name(mat),
  4546. # Maybe better look at index of all faces, if one over 65535 set to true;
  4547. # Problem: we know it too late, postprocessing of file needed
  4548. "use32bitindexes" : str(bool(numverts > 65535)),
  4549. "operationtype" : "triangle_list"
  4550. })
  4551. doc.start_tag('faces', {
  4552. 'count' : str(len(_sm_faces_[matidx]))
  4553. })
  4554. for fidx, (v1, v2, v3) in enumerate(_sm_faces_[matidx]):
  4555. doc.leaf_tag('face', {
  4556. 'v1' : str(v1),
  4557. 'v2' : str(v2),
  4558. 'v3' : str(v3)
  4559. })
  4560. doc.end_tag('faces')
  4561. doc.end_tag('submesh')
  4562. Report.triangles += len(_sm_faces_[matidx])
  4563. del(_sm_faces_)
  4564. doc.end_tag('submeshes')
  4565. ## by MrMagne
  4566. doc.start_tag('submeshnames', {})
  4567. for matidx, mat in enumerate( materials ):
  4568. doc.start_tag('submesh', {
  4569. 'name' : material_name(mat),
  4570. 'index' : str(matidx)
  4571. })
  4572. doc.end_tag('submesh')
  4573. doc.end_tag('submeshnames')
  4574. # -- end of MrMagne's patch
  4575. print(' Done at', timer_diff_str(start), "seconds")
  4576. arm = ob.find_armature()
  4577. if arm:
  4578. doc.leaf_tag('skeletonlink', {
  4579. 'name' : '%s.skeleton' %(force_name or ob.data.name)
  4580. })
  4581. doc.start_tag('boneassignments', {})
  4582. badverts = 0
  4583. for vidx, v in enumerate(_remap_verts_):
  4584. check = 0
  4585. for vgroup in v.groups:
  4586. if vgroup.weight > CONFIG['TRIM_BONE_WEIGHTS']:
  4587. bnidx = find_bone_index(copy,arm,vgroup.group)
  4588. if bnidx is not None: # allows other vertex groups, not just armature vertex groups
  4589. doc.leaf_tag('vertexboneassignment', {
  4590. 'vertexindex' : str(vidx),
  4591. 'boneindex' : str(bnidx),
  4592. 'weight' : str(vgroup.weight)
  4593. })
  4594. check += 1
  4595. if check > 4:
  4596. badverts += 1
  4597. print('WARNING: vertex %s is in more than 4 vertex groups (bone weights)\n(this maybe Ogre incompatible)' %vidx)
  4598. if badverts:
  4599. Report.warnings.append( '%s has %s vertices weighted to too many bones (Ogre limits a vertex to 4 bones)\n[try increaseing the Trim-Weights threshold option]' %(mesh.name, badverts) )
  4600. doc.end_tag('boneassignments')
  4601. # Updated June3 2011 - shape animation works
  4602. if CONFIG['SHAPE_ANIM'] and ob.data.shape_keys and len(ob.data.shape_keys.key_blocks):
  4603. print(' - Writing shape keys')
  4604. doc.start_tag('poses', {})
  4605. for sidx, skey in enumerate(ob.data.shape_keys.key_blocks):
  4606. if sidx == 0: continue
  4607. if len(skey.data) != len( mesh.vertices ):
  4608. failure = 'FAILED to save shape animation - you can not use a modifier that changes the vertex count! '
  4609. failure += '[ mesh : %s ]' %mesh.name
  4610. Report.warnings.append( failure )
  4611. print( failure )
  4612. break
  4613. doc.start_tag('pose', {
  4614. 'name' : skey.name,
  4615. # If target is 'mesh', no index needed, if target is submesh then submesh identified by 'index'
  4616. #'index' : str(sidx-1),
  4617. #'index' : '0',
  4618. 'target' : 'mesh'
  4619. })
  4620. for vidx, v in enumerate(_remap_verts_):
  4621. pv = skey.data[ v.index ]
  4622. x,y,z = swap( pv.co - v.co )
  4623. #for i,p in enumerate( skey.data ):
  4624. #x,y,z = p.co - ob.data.vertices[i].co
  4625. #x,y,z = swap( ob.data.vertices[i].co - p.co )
  4626. #if x==.0 and y==.0 and z==.0: continue # the older exporter optimized this way, is it safe?
  4627. doc.leaf_tag('poseoffset', {
  4628. 'x' : '%6f' % x,
  4629. 'y' : '%6f' % y,
  4630. 'z' : '%6f' % z,
  4631. 'index' : str(vidx) # is this required?
  4632. })
  4633. doc.end_tag('pose')
  4634. doc.end_tag('poses')
  4635. print(' Done at', timer_diff_str(start), "seconds")
  4636. if ob.data.shape_keys.animation_data and len(ob.data.shape_keys.animation_data.nla_tracks):
  4637. print(' - Writing shape animations')
  4638. doc.start_tag('animations', {})
  4639. _fps = float( bpy.context.scene.render.fps )
  4640. for nla in ob.data.shape_keys.animation_data.nla_tracks:
  4641. for idx, strip in enumerate(nla.strips):
  4642. doc.start_tag('animation', {
  4643. 'name' : strip.name,
  4644. 'length' : str((strip.frame_end-strip.frame_start)/_fps)
  4645. })
  4646. doc.start_tag('tracks', {})
  4647. doc.start_tag('track', {
  4648. 'type' : 'pose',
  4649. 'target' : 'mesh'
  4650. # If target is 'mesh', no index needed, if target is submesh then submesh identified by 'index'
  4651. #'index' : str(idx)
  4652. #'index' : '0'
  4653. })
  4654. doc.start_tag('keyframes', {})
  4655. for frame in range( int(strip.frame_start), int(strip.frame_end)+1, bpy.context.scene.frame_step):#thanks to Vesa
  4656. bpy.context.scene.frame_set(frame)
  4657. doc.start_tag('keyframe', {
  4658. 'time' : str((frame-strip.frame_start)/_fps)
  4659. })
  4660. for sidx, skey in enumerate( ob.data.shape_keys.key_blocks ):
  4661. if sidx == 0: continue
  4662. doc.leaf_tag('poseref', {
  4663. 'poseindex' : str(sidx-1),
  4664. 'influence' : str(skey.value)
  4665. })
  4666. doc.end_tag('keyframe')
  4667. doc.end_tag('keyframes')
  4668. doc.end_tag('track')
  4669. doc.end_tag('tracks')
  4670. doc.end_tag('animation')
  4671. doc.end_tag('animations')
  4672. print(' Done at', timer_diff_str(start), "seconds")
  4673. ## Clean up and save
  4674. #bpy.context.scene.meshes.unlink(mesh)
  4675. if cleanup:
  4676. #bpy.context.scene.objects.unlink(copy)
  4677. bpy.data.objects.remove(copy)
  4678. bpy.data.meshes.remove(mesh)
  4679. mesh.user_clear()
  4680. copy.user_clear()
  4681. del copy
  4682. del mesh
  4683. del _remap_verts_
  4684. del uvcache
  4685. doc.close() # reported by Reyn
  4686. f.close()
  4687. print(' - Created .mesh.xml at', timer_diff_str(start), "seconds")
  4688. # todo: Very ugly, find better way
  4689. def replaceInplace(f,searchExp,replaceExp):
  4690. import fileinput
  4691. for line in fileinput.input(f, inplace=1):
  4692. if searchExp in line:
  4693. line = line.replace(searchExp,replaceExp)
  4694. sys.stdout.write(line)
  4695. fileinput.close() # reported by jakob
  4696. replaceInplace(xmlfile, '__TO_BE_REPLACED_VERTEX_COUNT__' + '"', str(numverts) + '"' )#+ ' ' * (ls - lr))
  4697. del(replaceInplace)
  4698. # Start .mesh.xml to .mesh convertion tool
  4699. OgreXMLConverter(xmlfile, has_uvs=dotextures)
  4700. if arm and CONFIG['ARM_ANIM']:
  4701. skel = Skeleton( ob )
  4702. data = skel.to_xml()
  4703. name = force_name or ob.data.name
  4704. xmlfile = os.path.join(path, '%s.skeleton.xml' %name )
  4705. f = open( xmlfile, 'wb' )
  4706. f.write( bytes(data,'utf-8') )
  4707. f.close()
  4708. OgreXMLConverter( xmlfile )
  4709. mats = []
  4710. for mat in materials:
  4711. if mat != '_missing_material_': mats.append( mat )
  4712. print(' - Created .mesh in total time', timer_diff_str(start), 'seconds')
  4713. return mats
  4714. ## Jmonkey preview
  4715. ## todo: remove jmonkey
  4716. class JmonkeyPreviewOp( _OgreCommonExport_, bpy.types.Operator ):
  4717. '''helper to open jMonkey (JME)'''
  4718. bl_idname = 'jmonkey.preview'
  4719. bl_label = "opens JMonkeyEngine in a non-blocking subprocess"
  4720. bl_options = {'REGISTER'}
  4721. filepath= StringProperty(name="File Path", description="Filepath used for exporting Jmonkey .scene file", maxlen=1024, default="/tmp/preview.txml", subtype='FILE_PATH')
  4722. EXPORT_TYPE = 'OGRE'
  4723. @classmethod
  4724. def poll(cls, context):
  4725. if context.active_object: return True
  4726. def invoke(self, context, event):
  4727. global TundraSingleton
  4728. path = '/tmp/preview.scene'
  4729. self.ogre_export( path, context )
  4730. JmonkeyPipe( path )
  4731. return {'FINISHED'}
  4732. def JmonkeyPipe( path ):
  4733. root = CONFIG[ 'JMONKEY_ROOT']
  4734. if sys.platform.startswith('win'):
  4735. cmd = [ os.path.join( os.path.join( root, 'bin' ), 'jmonkeyplatform.exe' ) ]
  4736. else:
  4737. cmd = [ os.path.join( os.path.join( root, 'bin' ), 'jmonkeyplatform' ) ]
  4738. cmd.append( '--nosplash' )
  4739. cmd.append( '--open' )
  4740. cmd.append( path )
  4741. proc = subprocess.Popen(cmd)#, stdin=subprocess.PIPE)
  4742. return proc
  4743. ## realXtend Tundra preview
  4744. ## todo: This only work if the custom py script is enabled in Tundra
  4745. ## It's nice when it works but PythonScriptModule is not part of the
  4746. ## default Tundra distro anymore, so this is atm kind of dead.
  4747. class TundraPreviewOp( _OgreCommonExport_, bpy.types.Operator ):
  4748. '''helper to open Tundra2 (realXtend)'''
  4749. bl_idname = 'tundra.preview'
  4750. bl_label = "opens Tundra2 in a non-blocking subprocess"
  4751. bl_options = {'REGISTER'}
  4752. EXPORT_TYPE = 'REX'
  4753. filepath= StringProperty(
  4754. name="File Path",
  4755. description="Filepath used for exporting Tundra .txml file",
  4756. maxlen=1024,
  4757. default="/tmp/preview.txml",
  4758. subtype='FILE_PATH')
  4759. EX_FORCE_CAMERA = BoolProperty(
  4760. name="Force Camera",
  4761. description="export active camera",
  4762. default=False)
  4763. EX_FORCE_LAMPS = BoolProperty(
  4764. name="Force Lamps",
  4765. description="export all lamps",
  4766. default=False)
  4767. @classmethod
  4768. def poll(cls, context):
  4769. if context.active_object and context.mode != 'EDIT_MESH':
  4770. return True
  4771. def invoke(self, context, event):
  4772. global TundraSingleton
  4773. syncmats = []
  4774. obs = []
  4775. if TundraSingleton:
  4776. actob = context.active_object
  4777. obs = TundraSingleton.deselect_previously_updated(context)
  4778. for ob in obs:
  4779. if ob.type=='MESH':
  4780. syncmats.append( ob )
  4781. if ob.name == actob.name:
  4782. export_mesh( ob, path='/tmp/rex' )
  4783. if not os.path.isdir( '/tmp/rex' ): os.makedirs( '/tmp/rex' )
  4784. path = '/tmp/rex/preview.txml'
  4785. self.ogre_export( path, context, force_material_update=syncmats )
  4786. if not TundraSingleton:
  4787. TundraSingleton = TundraPipe( context )
  4788. elif self.EX_SCENE:
  4789. TundraSingleton.load( context, path )
  4790. for ob in obs:
  4791. ob.select = True # restore selection
  4792. return {'FINISHED'}
  4793. TundraSingleton = None
  4794. class Tundra_StartPhysicsOp(bpy.types.Operator):
  4795. '''TundraSingleton helper'''
  4796. bl_idname = 'tundra.start_physics'
  4797. bl_label = "start physics"
  4798. bl_options = {'REGISTER'}
  4799. @classmethod
  4800. def poll(cls, context):
  4801. if TundraSingleton: return True
  4802. def invoke(self, context, event):
  4803. TundraSingleton.start()
  4804. return {'FINISHED'}
  4805. class Tundra_StopPhysicsOp(bpy.types.Operator):
  4806. '''TundraSingleton helper'''
  4807. bl_idname = 'tundra.stop_physics'
  4808. bl_label = "stop physics"
  4809. bl_options = {'REGISTER'}
  4810. @classmethod
  4811. def poll(cls, context):
  4812. if TundraSingleton: return True
  4813. def invoke(self, context, event):
  4814. TundraSingleton.stop()
  4815. return {'FINISHED'}
  4816. class Tundra_PhysicsDebugOp(bpy.types.Operator):
  4817. '''TundraSingleton helper'''
  4818. bl_idname = 'tundra.toggle_physics_debug'
  4819. bl_label = "stop physics"
  4820. bl_options = {'REGISTER'}
  4821. @classmethod
  4822. def poll(cls, context):
  4823. if TundraSingleton: return True
  4824. def invoke(self, context, event):
  4825. TundraSingleton.toggle_physics_debug()
  4826. return {'FINISHED'}
  4827. class Tundra_ExitOp(bpy.types.Operator):
  4828. '''TundraSingleton helper'''
  4829. bl_idname = 'tundra.exit'
  4830. bl_label = "quit tundra"
  4831. bl_options = {'REGISTER'}
  4832. @classmethod
  4833. def poll(cls, context):
  4834. if TundraSingleton: return True
  4835. def invoke(self, context, event):
  4836. TundraSingleton.exit()
  4837. return {'FINISHED'}
  4838. ## Server object to talk with realXtend Tundra with UDP
  4839. ## Requires Tundra to be running a py script.
  4840. class Server(object):
  4841. def stream( self, o ):
  4842. b = pickle.dumps( o, protocol=2 ) #protocol2 is python2 compatible
  4843. #print( 'streaming bytes', len(b) )
  4844. n = len( b ); d = STREAM_BUFFER_SIZE - n -4
  4845. if n > STREAM_BUFFER_SIZE:
  4846. print( 'ERROR: STREAM OVERFLOW:', n )
  4847. return
  4848. padding = b'#' * d
  4849. if n < 10: header = '000%s' %n
  4850. elif n < 100: header = '00%s' %n
  4851. elif n < 1000: header = '0%s' %n
  4852. else: header = '%s' %n
  4853. header = bytes( header, 'utf-8' )
  4854. assert len(header) == 4
  4855. w = header + b + padding
  4856. assert len(w) == STREAM_BUFFER_SIZE
  4857. self.buffer.insert(0, w )
  4858. return w
  4859. def multires_lod( self ):
  4860. '''
  4861. Ogre builtin LOD sucks for character animation
  4862. '''
  4863. ob = bpy.context.active_object
  4864. cam = bpy.context.scene.camera
  4865. if ob and cam and ob.type=='MESH' and ob.use_multires_lod:
  4866. delta = bpy.context.active_object.matrix_world.to_translation() - cam.matrix_world.to_translation()
  4867. dist = delta.length
  4868. #print( 'Distance', dist )
  4869. if ob.modifiers and ob.modifiers[0].type == 'MULTIRES' and ob.modifiers[0].total_levels > 1:
  4870. mod = ob.modifiers[0]
  4871. step = ob.multires_lod_range / mod.total_levels
  4872. level = mod.total_levels - int( dist / step )
  4873. if mod.levels != level: mod.levels = level
  4874. return level
  4875. def sync( self ): # 153 bytes per object + n bytes for animation names and weights
  4876. LOD = self.multires_lod()
  4877. p = STREAM_PROTO
  4878. i = 0; msg = []
  4879. for ob in bpy.context.selected_objects:
  4880. if ob.type not in ('MESH','LAMP','SPEAKER'): continue
  4881. loc, rot, scale = ob.matrix_world.decompose()
  4882. loc = swap(loc).to_tuple()
  4883. x,y,z = swap( rot.to_euler() )
  4884. rot = (x,y,z)
  4885. x,y,z = swap( scale )
  4886. scale = ( abs(x), abs(y), abs(z) )
  4887. d = { p['ID']:uid(ob), p['POSITION']:loc, p['ROTATION']:rot, p['SCALE']:scale, p['TYPE']:p[ob.type] }
  4888. msg.append( d )
  4889. if ob.name == bpy.context.active_object.name and LOD is not None:
  4890. d[ p['LOD'] ] = LOD
  4891. if ob.type == 'MESH':
  4892. arm = ob.find_armature()
  4893. if arm and arm.animation_data and arm.animation_data.nla_tracks:
  4894. anim = None
  4895. d[ p['ANIMATIONS'] ] = state = {} # animation-name : weight
  4896. for nla in arm.animation_data.nla_tracks:
  4897. for strip in nla.strips:
  4898. if strip.active: state[ strip.name ] = strip.influence
  4899. else: pass # armature without proper NLA setup
  4900. elif ob.type == 'LAMP':
  4901. d[ p['ENERGY'] ] = ob.data.energy
  4902. d[ p['DISTANCE'] ] = ob.data.distance
  4903. elif ob.type == 'SPEAKER':
  4904. d[ p['VOLUME'] ] = ob.data.volume
  4905. d[ p['MUTE'] ] = ob.data.muted
  4906. if i >= 10: break # max is 13 objects to stay under 2048 bytes
  4907. return msg
  4908. def __init__(self):
  4909. import socket
  4910. self.buffer = [] # cmd buffer
  4911. self.socket = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
  4912. host='localhost'; port = 9420
  4913. sock.connect((host, port))
  4914. print('SERVER: socket connected', sock)
  4915. self._handle = None
  4916. self.setup_callback( bpy.context )
  4917. import threading
  4918. self.ready = threading._allocate_lock()
  4919. self.ID = threading._start_new_thread(
  4920. self.loop, (None,)
  4921. )
  4922. print( 'SERVER: thread started')
  4923. def loop(self, none):
  4924. self.active = True
  4925. prev = time.time()
  4926. while self.active:
  4927. if not self.ready.locked(): time.sleep(0.001) # not threadsafe
  4928. else: # threadsafe start
  4929. now = time.time()
  4930. if now - prev > 0.066: # don't flood Tundra
  4931. actob = None
  4932. try: actob = bpy.context.active_object
  4933. except: pass
  4934. if not actob: continue
  4935. prev = now
  4936. sel = bpy.context.active_object
  4937. msg = self.sync()
  4938. self.ready.release() # thread release
  4939. self.stream( msg ) # releases GIL?
  4940. if self.buffer:
  4941. bin = self.buffer.pop()
  4942. try:
  4943. self.socket.sendall( bin )
  4944. except:
  4945. print('SERVER: send data error')
  4946. time.sleep(0.5)
  4947. pass
  4948. else: print( 'SERVER: empty buffer' )
  4949. else:
  4950. self.ready.release()
  4951. print('SERVER: thread exit')
  4952. def threadsafe( self, reg ):
  4953. if not TundraSingleton: return
  4954. if not self.ready.locked():
  4955. self.ready.acquire()
  4956. time.sleep(0.0001)
  4957. while self.ready.locked(): # must block to be safe
  4958. time.sleep(0.0001) # wait for unlock
  4959. else: pass #time.sleep(0.033) dont block
  4960. _handle = None
  4961. def setup_callback( self, context ): # TODO replace with a proper frame update callback
  4962. print('SERVER: setup frame update callback')
  4963. if self._handle: return self._handle
  4964. for area in bpy.context.window.screen.areas:
  4965. if area.type == 'VIEW_3D':
  4966. for reg in area.regions:
  4967. if reg.type == 'WINDOW':
  4968. # PRE_VIEW, POST_VIEW, POST_PIXEL
  4969. self._handle = reg.callback_add(self.threadsafe, (reg,), 'PRE_VIEW' )
  4970. self._area = area
  4971. self._region = reg
  4972. break
  4973. if not self._handle:
  4974. print('SERVER: FAILED to setup frame update callback')
  4975. def _create_stream_proto():
  4976. proto = {}
  4977. tags = 'ID NAME POSITION ROTATION SCALE DATA SELECTED TYPE MESH LAMP CAMERA SPEAKER ANIMATIONS DISTANCE ENERGY VOLUME MUTE LOD'.split()
  4978. for i,tag in enumerate( tags ):
  4979. proto[ tag ] = chr(i) # up to 256
  4980. return proto
  4981. STREAM_PROTO = _create_stream_proto()
  4982. STREAM_BUFFER_SIZE = 2048
  4983. TUNDRA_SCRIPT = '''
  4984. # this file was generated by blender2ogre #
  4985. import tundra, socket, select, pickle
  4986. STREAM_BUFFER_SIZE = 2048
  4987. globals().update( %s )
  4988. E = {} # this is just for debugging from the pyconsole
  4989. def get_entity(ID):
  4990. scn = tundra.Scene().MainCameraScene()
  4991. return scn.GetEntityRaw( ID )
  4992. class Client(object):
  4993. def __init__(self):
  4994. self.socket = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  4995. host='localhost'; port = 9420
  4996. sock.bind((host, port))
  4997. self._animated = {} # entity ID : { anim-name : weight }
  4998. def update(self, delay):
  4999. global E
  5000. sock = self.socket
  5001. poll = select.select( [ sock ], [], [], 0.01 )
  5002. if not poll[0]: return True
  5003. data = sock.recv( STREAM_BUFFER_SIZE )
  5004. assert len(data) == STREAM_BUFFER_SIZE
  5005. if not data:
  5006. print( 'blender crashed?' )
  5007. return
  5008. header = data[ : 4]
  5009. s = data[ 4 : int(header)+4 ]
  5010. objects = pickle.loads( s )
  5011. scn = tundra.Scene().MainCameraScene() # replaces GetDefaultScene()
  5012. for ob in objects:
  5013. e = scn.GetEntityRaw( ob[ID] )
  5014. if not e: continue
  5015. x,y,z = ob[POSITION]
  5016. e.placeable.SetPosition( x,y,z )
  5017. x,y,z = ob[SCALE]
  5018. e.placeable.SetScale( x,y,z )
  5019. #e.placeable.SetOrientation( ob[ROTATION] )
  5020. if ob[TYPE] == LAMP:
  5021. e.light.range = ob[ DISTANCE ]
  5022. e.light.brightness = ob[ ENERGY ]
  5023. #e.light.diffColor = !! not wrapped !!
  5024. #e.light.specColor = !! not wrapped !!
  5025. elif ob[TYPE] == SPEAKER:
  5026. e.sound.soundGain = ob[VOLUME]
  5027. #e.sound.soundInnerRadius =
  5028. #e.sound.soundOuterRadius =
  5029. if ob[MUTE]: e.sound.StopSound()
  5030. else: e.sound.PlaySound() # tundra API needs sound.IsPlaying()
  5031. if ANIMATIONS in ob:
  5032. self.update_animation( e, ob )
  5033. if LOD in ob:
  5034. #print( 'LOD', ob[LOD] )
  5035. index = e.id + ob[LOD] + 1
  5036. for i in range(1,9):
  5037. elod = get_entity( e.id + i )
  5038. if elod:
  5039. if elod.id == index and not elod.placeable.visible:
  5040. elod.placeable.visible = True
  5041. elif elod.id != index and elod.placeable.visible:
  5042. elod.placeable.visible = False
  5043. if ob[ID] not in E: E[ ob[ID] ] = e
  5044. def update_animation( self, e, ob ):
  5045. if ob[ID] not in self._animated:
  5046. self._animated[ ob[ID] ] = {}
  5047. state = self._animated[ ob[ID] ]
  5048. ac = e.animationcontroller
  5049. for aname in ob[ ANIMATIONS ]:
  5050. if aname not in state: # save weight of new animation
  5051. state[ aname ] = ob[ANIMATIONS][aname] # weight
  5052. for aname in state:
  5053. if aname not in ob[ANIMATIONS] and ac.IsAnimationActive( aname ):
  5054. ac.StopAnim( aname, '0.0' )
  5055. elif aname in ob[ANIMATIONS]:
  5056. weight = ob[ANIMATIONS][aname]
  5057. if ac.HasAnimationFinished( aname ):
  5058. ac.PlayLoopedAnim( aname, '1.0', 'false' ) # PlayAnim(...) TODO single playback
  5059. ok = ac.SetAnimationWeight( aname, weight )
  5060. state[ aname ] = weight
  5061. if weight != state[ aname ]:
  5062. ok = ac.SetAnimationWeight( aname, weight )
  5063. state[ aname ] = weight
  5064. client = Client()
  5065. tundra.Frame().connect( 'Updated(float)', client.update )
  5066. print('blender2ogre plugin ok')
  5067. ''' %STREAM_PROTO
  5068. class TundraPipe(object):
  5069. CONFIG_PATH = '/tmp/rex/plugins.xml'
  5070. TUNDRA_SCRIPT_PATH = '/tmp/rex/b2ogre_plugin.py'
  5071. CONFIG_XML = '''<?xml version="1.0"?>
  5072. <Tundra>
  5073. <!-- plugins.xml is hardcoded to be the default configuration file to load if another file is not specified on the command line with the "config filename.xml" parameter. -->
  5074. <plugin path="OgreRenderingModule" />
  5075. <plugin path="EnvironmentModule" /> <!-- EnvironmentModule depends on OgreRenderingModule -->
  5076. <plugin path="PhysicsModule" /> <!-- PhysicsModule depends on OgreRenderingModule and EnvironmentModule -->
  5077. <plugin path="TundraProtocolModule" /> <!-- TundraProtocolModule depends on OgreRenderingModule -->
  5078. <plugin path="JavascriptModule" /> <!-- JavascriptModule depends on TundraProtocolModule -->
  5079. <plugin path="AssetModule" /> <!-- AssetModule depends on TundraProtocolModule -->
  5080. <plugin path="AvatarModule" /> <!-- AvatarModule depends on AssetModule and OgreRenderingModule -->
  5081. <plugin path="ECEditorModule" /> <!-- ECEditorModule depends on OgreRenderingModule, TundraProtocolModule, OgreRenderingModule and AssetModule -->
  5082. <plugin path="SkyXHydrax" /> <!-- SkyXHydrax depends on OgreRenderingModule -->
  5083. <plugin path="OgreAssetEditorModule" /> <!-- OgreAssetEditorModule depends on OgreRenderingModule -->
  5084. <plugin path="DebugStatsModule" /> <!-- DebugStatsModule depends on OgreRenderingModule, EnvironmentModule and AssetModule -->
  5085. <plugin path="SceneWidgetComponents" /> <!-- SceneWidgetComponents depends on OgreRenderingModule and TundraProtocolModule -->
  5086. <plugin path="PythonScriptModule" />
  5087. <!-- TODO: Currently the above <plugin> items are loaded in the order they are specified, but below, the jsplugin items are loaded in an undefined order. Use the order specified here as the load order. -->
  5088. <!-- NOTE: The startup .js scripts are specified only by base name of the file. Don's specify a path here. Place the startup .js scripts to /bin/jsmodules/startup/. -->
  5089. <!-- Important: The file names specified here are case sensitive even on Windows! -->
  5090. <jsplugin path="cameraapplication.js" />
  5091. <jsplugin path="FirstPersonMouseLook.js" />
  5092. <jsplugin path="MenuBar.js" />
  5093. <!-- Python plugins -->
  5094. <!-- <pyplugin path="lib/apitests.py" /> --> <!-- Runs framework api tests -->
  5095. <pyplugin path="%s" /> <!-- shows qt py console. could enable by default when add to menu etc. for controls, now just shows directly when is enabled here -->
  5096. <option name="--accept_unknown_http_sources" />
  5097. <option name="--accept_unknown_local_sources" />
  5098. <option name="--fpslimit" value="60" />
  5099. <!-- AssetAPI's file system watcher currently disabled because LocalAssetProvider implements
  5100. the same functionality for LocalAssetStorages and HTTPAssetProviders do not yet support live-update. -->
  5101. <option name="--nofilewatcher" />
  5102. </Tundra>''' %TUNDRA_SCRIPT_PATH
  5103. def __init__(self, context, debug=False):
  5104. self._physics_debug = True
  5105. self._objects = []
  5106. self.proc = None
  5107. exe = None
  5108. if 'Tundra.exe' in os.listdir( CONFIG['TUNDRA_ROOT'] ):
  5109. exe = os.path.join( CONFIG['TUNDRA_ROOT'], 'Tundra.exe' )
  5110. elif 'Tundra' in os.listdir( CONFIG['TUNDRA_ROOT'] ):
  5111. exe = os.path.join( CONFIG['TUNDRA_ROOT'], 'Tundra' )
  5112. cmd = []
  5113. if not exe:
  5114. print('ERROR: failed to find Tundra executable')
  5115. assert 0
  5116. elif sys.platform.startswith('win'):
  5117. cmd.append(exe)
  5118. else:
  5119. if exe.endswith('.exe'): cmd.append('wine') # assume user has Wine
  5120. cmd.append( exe )
  5121. if debug:
  5122. cmd.append('--loglevel')
  5123. cmd.append('debug')
  5124. if CONFIG['TUNDRA_STREAMING']:
  5125. cmd.append( '--config' )
  5126. cmd.append( self.CONFIG_PATH )
  5127. with open( self.CONFIG_PATH, 'wb' ) as fp: fp.write( bytes(self.CONFIG_XML,'utf-8') )
  5128. with open( self.TUNDRA_SCRIPT_PATH, 'wb' ) as fp: fp.write( bytes(TUNDRA_SCRIPT,'utf-8') )
  5129. self.server = Server()
  5130. #cmd += ['--file', '/tmp/rex/preview.txml'] # tundra2.1.2 bug loading from --file ignores entity ID's
  5131. cmd.append( '--storage' )
  5132. if sys.platform.startswith('win'): cmd.append( 'C:\\tmp\\rex' )
  5133. else: cmd.append( '/tmp/rex' )
  5134. self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, cwd=CONFIG['TUNDRA_ROOT'])
  5135. self.physics = True
  5136. if self.proc:
  5137. time.sleep(0.1)
  5138. self.load( context, '/tmp/rex/preview.txml' )
  5139. self.stop()
  5140. def deselect_previously_updated(self, context):
  5141. r = []
  5142. for ob in context.selected_objects:
  5143. if ob.name in self._objects: ob.select = False; r.append( ob )
  5144. return r
  5145. def load( self, context, url, clear=False ):
  5146. self._objects += [ob.name for ob in context.selected_objects]
  5147. if clear:
  5148. self.proc.stdin.write( b'loadscene(/tmp/rex/preview.txml,true,true)\n')
  5149. else:
  5150. self.proc.stdin.write( b'loadscene(/tmp/rex/preview.txml,false,true)\n')
  5151. try:
  5152. self.proc.stdin.flush()
  5153. except:
  5154. global TundraSingleton
  5155. TundraSingleton = None
  5156. def start( self ):
  5157. self.physics = True
  5158. self.proc.stdin.write( b'startphysics\n' )
  5159. try: self.proc.stdin.flush()
  5160. except:
  5161. global TundraSingleton
  5162. TundraSingleton = None
  5163. def stop( self ):
  5164. self.physics = False
  5165. self.proc.stdin.write( b'stopphysics\n' )
  5166. try: self.proc.stdin.flush()
  5167. except:
  5168. global TundraSingleton
  5169. TundraSingleton = None
  5170. def toggle_physics_debug( self ):
  5171. self._physics_debug = not self._physics_debug
  5172. self.proc.stdin.write( b'physicsdebug\n' )
  5173. try: self.proc.stdin.flush()
  5174. except:
  5175. global TundraSingleton
  5176. TundraSingleton = None
  5177. def exit(self):
  5178. self.proc.stdin.write( b'exit\n' )
  5179. self.proc.stdin.flush()
  5180. global TundraSingleton
  5181. TundraSingleton = None
  5182. ## More UI
  5183. class MENU_preview_material_text(bpy.types.Menu):
  5184. bl_label = 'preview'
  5185. @classmethod
  5186. def poll(self,context):
  5187. if context.active_object and context.active_object.active_material:
  5188. return True
  5189. def draw(self, context):
  5190. layout = self.layout
  5191. mat = context.active_object.active_material
  5192. if mat:
  5193. #CONFIG['TOUCH_TEXTURES'] = False
  5194. preview = generate_material( mat )
  5195. for line in preview.splitlines():
  5196. if line.strip():
  5197. for ww in wordwrap( line ):
  5198. layout.label(text=ww)
  5199. @UI
  5200. class INFO_HT_myheader(bpy.types.Header):
  5201. bl_space_type = 'INFO'
  5202. def draw(self, context):
  5203. layout = self.layout
  5204. wm = context.window_manager
  5205. window = context.window
  5206. scene = context.scene
  5207. rd = scene.render
  5208. ob = context.active_object
  5209. screen = context.screen
  5210. #layout.separator()
  5211. if _USE_JMONKEY_:
  5212. row = layout.row(align=True)
  5213. op = row.operator( 'jmonkey.preview', text='', icon='MONKEY' )
  5214. if _USE_TUNDRA_:
  5215. row = layout.row(align=True)
  5216. op = row.operator( 'tundra.preview', text='', icon='WORLD' )
  5217. if TundraSingleton:
  5218. op = row.operator( 'tundra.preview', text='', icon='META_CUBE' )
  5219. op.EX_SCENE = False
  5220. if not TundraSingleton.physics:
  5221. op = row.operator( 'tundra.start_physics', text='', icon='PLAY' )
  5222. else:
  5223. op = row.operator( 'tundra.stop_physics', text='', icon='PAUSE' )
  5224. op = row.operator( 'tundra.toggle_physics_debug', text='', icon='MOD_PHYSICS' )
  5225. op = row.operator( 'tundra.exit', text='', icon='CANCEL' )
  5226. op = layout.operator( 'ogremeshy.preview', text='', icon='PLUGIN' ); op.mesh = True
  5227. row = layout.row(align=True)
  5228. sub = row.row(align=True)
  5229. sub.menu("INFO_MT_file")
  5230. sub.menu("INFO_MT_add")
  5231. if rd.use_game_engine: sub.menu("INFO_MT_game")
  5232. else: sub.menu("INFO_MT_render")
  5233. row = layout.row(align=False); row.scale_x = 1.25
  5234. row.menu("INFO_MT_instances", icon='NODETREE', text='')
  5235. row.menu("INFO_MT_groups", icon='GROUP', text='')
  5236. layout.template_header()
  5237. if not context.area.show_menus:
  5238. if window.screen.show_fullscreen: layout.operator("screen.back_to_previous", icon='SCREEN_BACK', text="Back to Previous")
  5239. else: layout.template_ID(context.window, "screen", new="screen.new", unlink="screen.delete")
  5240. layout.template_ID(context.screen, "scene", new="scene.new", unlink="scene.delete")
  5241. layout.separator()
  5242. layout.template_running_jobs()
  5243. layout.template_reports_banner()
  5244. layout.separator()
  5245. if rd.has_multiple_engines: layout.prop(rd, "engine", text="")
  5246. layout.label(text=scene.statistics())
  5247. layout.menu( "INFO_MT_help" )
  5248. else:
  5249. layout.template_ID(context.window, "screen", new="screen.new", unlink="screen.delete")
  5250. if ob:
  5251. row = layout.row(align=True)
  5252. row.prop( ob, 'name', text='' )
  5253. row.prop( ob, 'draw_type', text='' )
  5254. row.prop( ob, 'show_x_ray', text='' )
  5255. row = layout.row()
  5256. row.scale_y = 0.75; row.scale_x = 0.9
  5257. row.prop( ob, 'layers', text='' )
  5258. layout.separator()
  5259. row = layout.row(align=True); row.scale_x = 1.1
  5260. row.prop(scene.game_settings, 'material_mode', text='')
  5261. row.prop(scene, 'camera', text='')
  5262. layout.menu( 'MENU_preview_material_text', icon='TEXT', text='' )
  5263. layout.menu( "INFO_MT_ogre_docs" )
  5264. layout.operator("wm.window_fullscreen_toggle", icon='FULLSCREEN_ENTER', text="")
  5265. if OgreToggleInterfaceOp.TOGGLE: layout.operator('ogre.toggle_interface', text='Ogre', icon='CHECKBOX_DEHLT')
  5266. else: layout.operator('ogre.toggle_interface', text='Ogre', icon='CHECKBOX_HLT')
  5267. def export_menu_func_ogre(self, context):
  5268. op = self.layout.operator(INFO_OT_createOgreExport.bl_idname, text="Ogre3D (.scene and .mesh)")
  5269. def export_menu_func_realxtend(self, context):
  5270. op = self.layout.operator(INFO_OT_createRealxtendExport.bl_idname, text="realXtend Tundra (.txml and .mesh)")
  5271. try:
  5272. _header_ = bpy.types.INFO_HT_header
  5273. except:
  5274. print('---blender2ogre addon enable---')
  5275. ## Toggle button for blender2ogre UI panels
  5276. class OgreToggleInterfaceOp(bpy.types.Operator):
  5277. '''Toggle Ogre UI'''
  5278. bl_idname = "ogre.toggle_interface"
  5279. bl_label = "Ogre UI"
  5280. bl_options = {'REGISTER'}
  5281. TOGGLE = True #restore_minimal_interface()
  5282. BLENDER_DEFAULT_HEADER = _header_
  5283. @classmethod
  5284. def poll(cls, context):
  5285. return True
  5286. def invoke(self, context, event):
  5287. #global _header_
  5288. if OgreToggleInterfaceOp.TOGGLE: #_header_:
  5289. print( 'ogre.toggle_interface ENABLE' )
  5290. bpy.utils.register_module(__name__)
  5291. #_header_ = bpy.types.INFO_HT_header
  5292. try: bpy.utils.unregister_class(_header_)
  5293. except: pass
  5294. bpy.utils.unregister_class( INFO_HT_microheader ) # moved to custom header
  5295. OgreToggleInterfaceOp.TOGGLE = False
  5296. else:
  5297. print( 'ogre.toggle_interface DISABLE' )
  5298. #bpy.utils.unregister_module(__name__); # this is not safe, can segfault blender, why?
  5299. hide_user_interface()
  5300. bpy.utils.register_class(_header_)
  5301. restore_minimal_interface()
  5302. OgreToggleInterfaceOp.TOGGLE = True
  5303. return {'FINISHED'}
  5304. class INFO_HT_microheader(bpy.types.Header):
  5305. bl_space_type = 'INFO'
  5306. def draw(self, context):
  5307. layout = self.layout
  5308. try:
  5309. if OgreToggleInterfaceOp.TOGGLE:
  5310. layout.operator('ogre.toggle_interface', text='Ogre', icon='CHECKBOX_DEHLT')
  5311. else:
  5312. layout.operator('ogre.toggle_interface', text='Ogre', icon='CHECKBOX_HLT')
  5313. except: pass # STILL REQUIRED?
  5314. def get_minimal_interface_classes():
  5315. return INFO_OT_createOgreExport, INFO_OT_createRealxtendExport, OgreToggleInterfaceOp, MiniReport, INFO_HT_microheader
  5316. _USE_TUNDRA_ = False
  5317. _USE_JMONKEY_ = False
  5318. def restore_minimal_interface():
  5319. #if not hasattr( bpy.ops.ogre.. #always true
  5320. for cls in get_minimal_interface_classes():
  5321. try: bpy.utils.register_class( cls )
  5322. except: pass
  5323. return False
  5324. try:
  5325. bpy.utils.register_class( INFO_HT_microheader )
  5326. for op in get_minimal_interface_classes(): bpy.utils.register_class( op )
  5327. return False
  5328. except:
  5329. print( 'b2ogre minimal UI already setup' )
  5330. return True
  5331. MyShaders = None
  5332. def register():
  5333. print('Starting blender2ogre', VERSION)
  5334. global MyShaders, _header_, _USE_TUNDRA_, _USE_JMONKEY_
  5335. #bpy.utils.register_module(__name__) ## do not load all the ogre panels by default
  5336. #_header_ = bpy.types.INFO_HT_header
  5337. #bpy.utils.unregister_class(_header_)
  5338. restore_minimal_interface()
  5339. # only test for Tundra2 once - do not do this every panel redraw ##
  5340. if os.path.isdir( CONFIG['TUNDRA_ROOT'] ): _USE_TUNDRA_ = True
  5341. else: _USE_TUNDRA_ = False
  5342. #if os.path.isdir( CONFIG['JMONKEY_ROOT'] ): _USE_JMONKEY_ = True
  5343. #else: _USE_JMONKEY_ = False
  5344. bpy.types.INFO_MT_file_export.append(export_menu_func_ogre)
  5345. bpy.types.INFO_MT_file_export.append(export_menu_func_realxtend)
  5346. bpy.utils.register_class(PopUpDialogOperator)
  5347. if os.path.isdir( CONFIG['USER_MATERIALS'] ):
  5348. scripts,progs = update_parent_material_path( CONFIG['USER_MATERIALS'] )
  5349. for prog in progs:
  5350. print('Ogre shader program', prog.name)
  5351. else:
  5352. print('[WARNING]: Invalid my-shaders path' )
  5353. def unregister():
  5354. print('Unloading blender2ogre', VERSION)
  5355. header = _header_
  5356. bpy.utils.unregister_module(__name__)
  5357. if header:
  5358. bpy.utils.register_class(header)
  5359. bpy.types.INFO_MT_file_export.remove(export_menu_func_ogre)
  5360. bpy.types.INFO_MT_file_export.remove(export_menu_func_realxtend)
  5361. bpy.utils.unregister_class(PopUpDialogOperator)
  5362. ## Blender world panel options for EC_SkyX creation
  5363. ## todo: EC_SkyX has changes a bit lately, see that
  5364. ## all these options are still correct and valid
  5365. ## old todo (?): Move to tundra.py
  5366. bpy.types.World.ogre_skyX = BoolProperty(
  5367. name="enable sky", description="ogre sky",
  5368. default=False
  5369. )
  5370. bpy.types.World.ogre_skyX_time = FloatProperty(
  5371. name="Time Multiplier",
  5372. description="change speed of day/night cycle",
  5373. default=0.3,
  5374. min=0.0, max=5.0
  5375. )
  5376. bpy.types.World.ogre_skyX_wind = FloatProperty(
  5377. name="Wind Direction",
  5378. description="change direction of wind",
  5379. default=33.0,
  5380. min=0.0, max=360.0
  5381. )
  5382. bpy.types.World.ogre_skyX_volumetric_clouds = BoolProperty(
  5383. name="volumetric clouds", description="toggle ogre volumetric clouds",
  5384. default=True
  5385. )
  5386. bpy.types.World.ogre_skyX_cloud_density_x = FloatProperty(
  5387. name="Cloud Density X",
  5388. description="change density of volumetric clouds on X",
  5389. default=0.1,
  5390. min=0.0, max=5.0
  5391. )
  5392. bpy.types.World.ogre_skyX_cloud_density_y = FloatProperty(
  5393. name="Cloud Density Y",
  5394. description="change density of volumetric clouds on Y",
  5395. default=1.0,
  5396. min=0.0, max=5.0
  5397. )
  5398. ## Sky UI panel
  5399. @UI
  5400. class OgreSkyPanel(bpy.types.Panel):
  5401. bl_space_type = 'PROPERTIES'
  5402. bl_region_type = 'WINDOW'
  5403. bl_context = "world"
  5404. bl_label = "Ogre Sky Settings"
  5405. @classmethod
  5406. def poll(cls, context):
  5407. return True
  5408. def draw(self, context):
  5409. layout = self.layout
  5410. box = layout.box()
  5411. box.prop( context.world, 'ogre_skyX' )
  5412. if context.world.ogre_skyX:
  5413. box.prop( context.world, 'ogre_skyX_time' )
  5414. box.prop( context.world, 'ogre_skyX_wind' )
  5415. box.prop( context.world, 'ogre_skyX_volumetric_clouds' )
  5416. if context.world.ogre_skyX_volumetric_clouds:
  5417. box.prop( context.world, 'ogre_skyX_cloud_density_x' )
  5418. box.prop( context.world, 'ogre_skyX_cloud_density_y' )
  5419. class OgreProgram(object):
  5420. '''
  5421. parses .program scripts
  5422. saves bytes to copy later
  5423. self.name = name of program reference
  5424. self.source = name of shader program (.cg, .glsl)
  5425. '''
  5426. def save( self, path ):
  5427. print('saving program to', path)
  5428. f = open( os.path.join(path,self.source), 'wb' )
  5429. f.write(self.source_bytes )
  5430. f.close()
  5431. for name in self.includes:
  5432. f = open( os.path.join(path,name), 'wb' )
  5433. f.write( self.includes[name] )
  5434. f.close()
  5435. PROGRAMS = {}
  5436. SOURCES = {}
  5437. def reload(self): # only one directory is allowed to hold shader programs
  5438. if self.source not in os.listdir( CONFIG['SHADER_PROGRAMS'] ):
  5439. print( 'ERROR: ogre material %s is missing source: %s' %(self.name,self.source) )
  5440. print( CONFIG['SHADER_PROGRAMS'] )
  5441. return False
  5442. url = os.path.join( CONFIG['SHADER_PROGRAMS'], self.source )
  5443. print('shader source:', url)
  5444. self.source_bytes = open( url, 'rb' ).read()#.decode('utf-8')
  5445. print('shader source num bytes:', len(self.source_bytes))
  5446. data = self.source_bytes.decode('utf-8')
  5447. for line in data.splitlines(): # only cg shaders use the include macro?
  5448. if line.startswith('#include') and line.count('"')==2:
  5449. name = line.split()[-1].replace('"','').strip()
  5450. print('shader includes:', name)
  5451. url = os.path.join( CONFIG['SHADER_PROGRAMS'], name )
  5452. self.includes[ name ] = open( url, 'rb' ).read()
  5453. return True
  5454. def __init__(self, name='', data=''):
  5455. self.name=name
  5456. self.data = data.strip()
  5457. self.source = None
  5458. self.includes = {} # cg files may use #include something.cg
  5459. if self.name in OgreProgram.PROGRAMS:
  5460. print('---copy ogreprogram---', self.name)
  5461. other = OgreProgram.PROGRAMS
  5462. self.source = other.source
  5463. self.data = other.data
  5464. self.entry_point = other.entry_point
  5465. self.profiles = other.profiles
  5466. if data: self.parse( self.data )
  5467. if self.name: OgreProgram.PROGRAMS[ self.name ] = self
  5468. def parse( self, txt ):
  5469. self.data = txt
  5470. print('--parsing ogre shader program--' )
  5471. for line in self.data.splitlines():
  5472. print(line)
  5473. line = line.split('//')[0]
  5474. line = line.strip()
  5475. if line.startswith('vertex_program') or line.startswith('fragment_program'):
  5476. a, self.name, self.type = line.split()
  5477. elif line.startswith('source'): self.source = line.split()[-1]
  5478. elif line.startswith('entry_point'): self.entry_point = line.split()[-1]
  5479. elif line.startswith('profiles'): self.profiles = line.split()[1:]
  5480. ## Ogre Material object(s) that is utilized during export stages
  5481. class OgreMaterialScript(object):
  5482. def get_programs(self):
  5483. progs = []
  5484. for name in list(self.vertex_programs.keys()) + list(self.fragment_programs.keys()):
  5485. p = get_shader_program( name ) # OgreProgram.PROGRAMS
  5486. if p: progs.append( p )
  5487. return progs
  5488. def __init__(self, txt, url):
  5489. self.url = url
  5490. self.data = txt.strip()
  5491. self.parent = None
  5492. self.vertex_programs = {}
  5493. self.fragment_programs = {}
  5494. self.texture_units = {}
  5495. self.texture_units_order = []
  5496. self.passes = []
  5497. line = self.data.splitlines()[0]
  5498. assert line.startswith('material')
  5499. if ':' in line:
  5500. line, self.parent = line.split(':')
  5501. self.name = line.split()[-1]
  5502. print( 'new ogre material: %s' %self.name )
  5503. brace = 0
  5504. self.techniques = techs = []
  5505. prog = None # pick up program params
  5506. tex = None # pick up texture_unit options, require "texture" ?
  5507. for line in self.data.splitlines():
  5508. #print( line )
  5509. rawline = line
  5510. line = line.split('//')[0]
  5511. line = line.strip()
  5512. if not line: continue
  5513. if line == '{': brace += 1
  5514. elif line == '}': brace -= 1; prog = None; tex = None
  5515. if line.startswith( 'technique' ):
  5516. tech = {'passes':[]}; techs.append( tech )
  5517. if len(line.split()) > 1: tech['technique-name'] = line.split()[-1]
  5518. elif techs:
  5519. if line.startswith('pass'):
  5520. P = {'texture_units':[], 'vprogram':None, 'fprogram':None, 'body':[]}
  5521. tech['passes'].append( P )
  5522. self.passes.append( P )
  5523. elif tech['passes']:
  5524. P = tech['passes'][-1]
  5525. P['body'].append( rawline )
  5526. if line == '{' or line == '}': continue
  5527. if line.startswith('vertex_program_ref'):
  5528. prog = P['vprogram'] = {'name':line.split()[-1], 'params':{}}
  5529. self.vertex_programs[ prog['name'] ] = prog
  5530. elif line.startswith('fragment_program_ref'):
  5531. prog = P['fprogram'] = {'name':line.split()[-1], 'params':{}}
  5532. self.fragment_programs[ prog['name'] ] = prog
  5533. elif line.startswith('texture_unit'):
  5534. prog = None
  5535. tex = {'name':line.split()[-1], 'params':{}}
  5536. if tex['name'] == 'texture_unit': # ignore unnamed texture units
  5537. print('WARNING: material %s contains unnamed texture_units' %self.name)
  5538. print('---unnamed texture units will be ignored---')
  5539. else:
  5540. P['texture_units'].append( tex )
  5541. self.texture_units[ tex['name'] ] = tex
  5542. self.texture_units_order.append( tex['name'] )
  5543. elif prog:
  5544. p = line.split()[0]
  5545. if p=='param_named':
  5546. items = line.split()
  5547. if len(items) == 4: p, o, t, v = items
  5548. elif len(items) == 3:
  5549. p, o, v = items
  5550. t = 'class'
  5551. elif len(items) > 4:
  5552. o = items[1]; t = items[2]
  5553. v = items[3:]
  5554. opt = { 'name': o, 'type':t, 'raw_value':v }
  5555. prog['params'][ o ] = opt
  5556. if t=='float': opt['value'] = float(v)
  5557. elif t in 'float2 float3 float4'.split(): opt['value'] = [ float(a) for a in v ]
  5558. else: print('unknown type:', t)
  5559. elif tex: # (not used)
  5560. tex['params'][ line.split()[0] ] = line.split()[ 1 : ]
  5561. for P in self.passes:
  5562. lines = P['body']
  5563. while lines and ''.join(lines).count('{')!=''.join(lines).count('}'):
  5564. if lines[-1].strip() == '}': lines.pop()
  5565. else: break
  5566. P['body'] = '\n'.join( lines )
  5567. assert P['body'].count('{') == P['body'].count('}') # if this fails, the parser choked
  5568. #print( self.techniques )
  5569. self.hidden_texture_units = rem = []
  5570. for tex in self.texture_units.values():
  5571. if 'texture' not in tex['params']:
  5572. rem.append( tex )
  5573. for tex in rem:
  5574. print('WARNING: not using texture_unit because it lacks a "texture" parameter', tex['name'])
  5575. self.texture_units.pop( tex['name'] )
  5576. if len(self.techniques)>1:
  5577. print('WARNING: user material %s has more than one technique' %self.url)
  5578. def as_abstract_passes( self ):
  5579. r = []
  5580. for i,P in enumerate(self.passes):
  5581. head = 'abstract pass %s/PASS%s' %(self.name,i)
  5582. r.append( head + '\n' + P['body'] )
  5583. return r
  5584. class MaterialScripts(object):
  5585. ALL_MATERIALS = {}
  5586. ENUM_ITEMS = []
  5587. def __init__(self, url):
  5588. self.url = url
  5589. self.data = ''
  5590. data = open( url, 'rb' ).read()
  5591. try:
  5592. self.data = data.decode('utf-8')
  5593. except:
  5594. self.data = data.decode('latin-1')
  5595. self.materials = {}
  5596. ## chop up .material file, find all material defs ####
  5597. mats = []
  5598. mat = []
  5599. skip = False # for now - programs must be defined in .program files, not in the .material
  5600. for line in self.data.splitlines():
  5601. if not line.strip(): continue
  5602. a = line.split()[0] #NOTE ".split()" strips white space
  5603. if a == 'material':
  5604. mat = []; mats.append( mat )
  5605. mat.append( line )
  5606. elif a in ('vertex_program', 'fragment_program', 'abstract'):
  5607. skip = True
  5608. elif mat and not skip:
  5609. mat.append( line )
  5610. elif skip and line=='}':
  5611. skip = False
  5612. ##########################
  5613. for mat in mats:
  5614. omat = OgreMaterialScript( '\n'.join( mat ), url )
  5615. if omat.name in self.ALL_MATERIALS:
  5616. print( 'WARNING: material %s redefined' %omat.name )
  5617. #print( '--OLD MATERIAL--')
  5618. #print( self.ALL_MATERIALS[ omat.name ].data )
  5619. #print( '--NEW MATERIAL--')
  5620. #print( omat.data )
  5621. self.materials[ omat.name ] = omat
  5622. self.ALL_MATERIALS[ omat.name ] = omat
  5623. if omat.vertex_programs or omat.fragment_programs: # ignore materials without programs
  5624. self.ENUM_ITEMS.append( (omat.name, omat.name, url) )
  5625. @classmethod # only call after parsing all material scripts
  5626. def reset_rna(self, callback=None):
  5627. bpy.types.Material.ogre_parent_material = EnumProperty(
  5628. name="Script Inheritence",
  5629. description='ogre parent material class',
  5630. items=self.ENUM_ITEMS,
  5631. #update=callback
  5632. )
  5633. ## Image/texture proecssing
  5634. def is_image_postprocessed( image ):
  5635. if CONFIG['FORCE_IMAGE_FORMAT'] != 'NONE' or image.use_resize_half or image.use_resize_absolute or image.use_color_quantize or image.use_convert_format:
  5636. return True
  5637. else:
  5638. return False
  5639. class _image_processing_( object ):
  5640. def _reformat( self, name, image ):
  5641. if image.convert_format != 'NONE':
  5642. name = '%s.%s' %(name[:name.rindex('.')], image.convert_format)
  5643. if image.convert_format == 'dds': name = '_DDS_.%s' %name
  5644. elif image.use_resize_half or image.use_resize_absolute or image.use_color_quantize or image.use_convert_format:
  5645. name = '_magick_.%s' %name
  5646. if CONFIG['FORCE_IMAGE_FORMAT'] != 'NONE' and not name.endswith('.dds'):
  5647. name = '%s.%s' %(name[:name.rindex('.')], CONFIG['FORCE_IMAGE_FORMAT'])
  5648. if CONFIG['FORCE_IMAGE_FORMAT'] == 'dds':
  5649. name = '_DDS_.%s' %name
  5650. return name
  5651. def image_magick( self, texture, infile ):
  5652. print('IMAGE MAGICK', infile )
  5653. exe = CONFIG['IMAGE_MAGICK_CONVERT']
  5654. if not os.path.isfile( exe ):
  5655. Report.warnings.append( 'ImageMagick not installed!' )
  5656. print( 'ERROR: can not find Image Magick - convert', exe ); return
  5657. cmd = [ exe, infile ]
  5658. ## enforce max size ##
  5659. x,y = texture.image.size
  5660. ax = texture.image.resize_x
  5661. ay = texture.image.resize_y
  5662. if texture.image.use_convert_format and texture.image.convert_format == 'jpg':
  5663. cmd.append( '-quality' )
  5664. cmd.append( '%s' %texture.image.jpeg_quality )
  5665. if texture.image.use_resize_half:
  5666. cmd.append( '-resize' )
  5667. cmd.append( '%sx%s' %(x/2, y/2) )
  5668. elif texture.image.use_resize_absolute and (x>ax or y>ay):
  5669. cmd.append( '-resize' )
  5670. cmd.append( '%sx%s' %(ax,ay) )
  5671. elif x > CONFIG['MAX_TEXTURE_SIZE'] or y > CONFIG['MAX_TEXTURE_SIZE']:
  5672. cmd.append( '-resize' )
  5673. cmd.append( str(CONFIG['MAX_TEXTURE_SIZE']) )
  5674. if texture.image.use_color_quantize:
  5675. if texture.image.use_color_quantize_dither:
  5676. cmd.append( '+dither' )
  5677. cmd.append( '-colors' )
  5678. cmd.append( str(texture.image.color_quantize) )
  5679. path,name = os.path.split( infile )
  5680. #if (texture.image.use_convert_format and texture.image.convert_format == 'dds') or CONFIG['FORCE_IMAGE_FORMAT'] == 'dds':
  5681. outfile = os.path.join( path, self._reformat(name,texture.image) )
  5682. if outfile.endswith('.dds'):
  5683. temp = os.path.join( path, '_temp_.png' )
  5684. cmd.append( temp )
  5685. print( 'IMAGE MAGICK: %s' %cmd )
  5686. subprocess.call( cmd )
  5687. self.nvcompress( texture, temp, outfile=outfile )
  5688. else:
  5689. cmd.append( outfile )
  5690. print( 'IMAGE MAGICK: %s' %cmd )
  5691. subprocess.call( cmd )
  5692. def nvcompress(self, texture, infile, outfile=None, version=1, fast=False, blocking=True):
  5693. print('[NVCompress DDS Wrapper]', infile )
  5694. assert version in (1,2,3,4,5)
  5695. exe = CONFIG['NVCOMPRESS']
  5696. cmd = [ exe ]
  5697. if texture.use_alpha and texture.image.depth==32:
  5698. cmd.append( '-alpha' )
  5699. if not texture.use_mipmap:
  5700. cmd.append( '-nomips' )
  5701. if texture.use_normal_map:
  5702. cmd.append( '-normal' )
  5703. if version in (1,3):
  5704. cmd.append( '-bc%sn' %version )
  5705. else:
  5706. cmd.append( '-bc%s' %version )
  5707. else:
  5708. cmd.append( '-bc%s' %version )
  5709. if fast:
  5710. cmd.append( '-fast' )
  5711. cmd.append( infile )
  5712. if outfile: cmd.append( outfile )
  5713. print( cmd )
  5714. if blocking:
  5715. subprocess.call( cmd )
  5716. else:
  5717. subprocess.Popen( cmd )
  5718. ## NVIDIA texture compress documentation
  5719. _nvcompress_doc = '''
  5720. usage: nvcompress [options] infile [outfile]
  5721. Input options:
  5722. -color The input image is a color map (default).
  5723. -alpha The input image has an alpha channel used for transparency.
  5724. -normal The input image is a normal map.
  5725. -tonormal Convert input to normal map.
  5726. -clamp Clamp wrapping mode (default).
  5727. -repeat Repeat wrapping mode.
  5728. -nomips Disable mipmap generation.
  5729. Compression options:
  5730. -fast Fast compression.
  5731. -nocuda Do not use cuda compressor.
  5732. -rgb RGBA format
  5733. -bc1 BC1 format (DXT1)
  5734. -bc1n BC1 normal map format (DXT1nm)
  5735. -bc1a BC1 format with binary alpha (DXT1a)
  5736. -bc2 BC2 format (DXT3)
  5737. -bc3 BC3 format (DXT5)
  5738. -bc3n BC3 normal map format (DXT5nm)
  5739. -bc4 BC4 format (ATI1)
  5740. -bc5 BC5 format (3Dc/ATI2)
  5741. '''
  5742. class OgreMaterialGenerator( _image_processing_ ):
  5743. def __init__(self, material, path='/tmp', touch_textures=False ):
  5744. self.material = material # top level material
  5745. self.path = path # copy textures to path
  5746. self.passes = []
  5747. self.touch_textures = touch_textures
  5748. if material.node_tree:
  5749. nodes = bpyShaders.get_subnodes( self.material.node_tree, type='MATERIAL_EXT' )
  5750. for node in nodes:
  5751. if node.material:
  5752. self.passes.append( node.material )
  5753. def get_active_programs(self):
  5754. r = []
  5755. for mat in self.passes:
  5756. if mat.use_ogre_parent_material and mat.ogre_parent_material:
  5757. usermat = get_ogre_user_material( mat.ogre_parent_material )
  5758. for prog in usermat.get_programs(): r.append( prog )
  5759. return r
  5760. def get_header(self):
  5761. r = []
  5762. for mat in self.passes:
  5763. if mat.use_ogre_parent_material and mat.ogre_parent_material:
  5764. usermat = get_ogre_user_material( mat.ogre_parent_material )
  5765. r.append( '// user material: %s' %usermat.name )
  5766. for prog in usermat.get_programs():
  5767. r.append( prog.data )
  5768. r.append( '// abstract passes //' )
  5769. r += usermat.as_abstract_passes()
  5770. return '\n'.join( r )
  5771. def get_passes(self):
  5772. r = []
  5773. r.append( self.generate_pass(self.material) )
  5774. for mat in self.passes:
  5775. if mat.use_in_ogre_material_pass: # submaterials
  5776. r.append( self.generate_pass(mat) )
  5777. return r
  5778. def generate_pass( self, mat, pass_name=None ):
  5779. usermat = texnodes = None
  5780. if mat.use_ogre_parent_material and mat.ogre_parent_material:
  5781. usermat = get_ogre_user_material( mat.ogre_parent_material )
  5782. texnodes = bpyShaders.get_texture_subnodes( self.material, mat )
  5783. M = ''
  5784. if not pass_name: pass_name = mat.name
  5785. if usermat:
  5786. M += indent(2, 'pass %s : %s/PASS0' %(pass_name,usermat.name), '{' )
  5787. else:
  5788. M += indent(2, 'pass %s'%pass_name, '{' )
  5789. color = mat.diffuse_color
  5790. alpha = 1.0
  5791. if mat.use_transparency:
  5792. alpha = mat.alpha
  5793. slots = get_image_textures( mat ) # returns texture_slot objects (CLASSIC MATERIAL)
  5794. usealpha = False #mat.ogre_depth_write
  5795. for slot in slots:
  5796. #if slot.use_map_alpha and slot.texture.use_alpha: usealpha = True; break
  5797. if slot.texture.use_alpha: usealpha = True; break
  5798. ## force material alpha to 1.0 if textures use_alpha?
  5799. #if usealpha: alpha = 1.0 # let the alpha of the texture control material alpha?
  5800. if mat.use_fixed_pipeline:
  5801. f = mat.ambient
  5802. if mat.use_vertex_color_paint:
  5803. M += indent(3, 'ambient vertexcolour' )
  5804. else: # fall back to basic material
  5805. M += indent(3, 'ambient %s %s %s %s' %(color.r*f, color.g*f, color.b*f, alpha) )
  5806. f = mat.diffuse_intensity
  5807. if mat.use_vertex_color_paint:
  5808. M += indent(3, 'diffuse vertexcolour' )
  5809. else: # fall back to basic material
  5810. M += indent(3, 'diffuse %s %s %s %s' %(color.r*f, color.g*f, color.b*f, alpha) )
  5811. f = mat.specular_intensity
  5812. s = mat.specular_color
  5813. M += indent(3, 'specular %s %s %s %s %s' %(s.r*f, s.g*f, s.b*f, alpha, mat.specular_hardness/4.0) )
  5814. f = mat.emit
  5815. if mat.use_shadeless: # requested by Borris
  5816. M += indent(3, 'emissive %s %s %s 1.0' %(color.r, color.g, color.b) )
  5817. elif mat.use_vertex_color_light:
  5818. M += indent(3, 'emissive vertexcolour' )
  5819. else:
  5820. M += indent(3, 'emissive %s %s %s %s' %(color.r*f, color.g*f, color.b*f, alpha) )
  5821. M += '\n' # pretty printing
  5822. if mat.offset_z:
  5823. M += indent(3, 'depth_bias %s'%mat.offset_z )
  5824. for name in dir(mat): #mat.items() - items returns custom props not pyRNA:
  5825. if name.startswith('ogre_') and name != 'ogre_parent_material':
  5826. var = getattr(mat,name)
  5827. op = name.replace('ogre_', '')
  5828. val = var
  5829. if type(var) == bool:
  5830. if var: val = 'on'
  5831. else: val = 'off'
  5832. M += indent( 3, '%s %s' %(op,val) )
  5833. M += '\n' # pretty printing
  5834. if texnodes and usermat.texture_units:
  5835. for i,name in enumerate(usermat.texture_units_order):
  5836. if i<len(texnodes):
  5837. node = texnodes[i]
  5838. if node.texture:
  5839. geo = bpyShaders.get_connected_input_nodes( self.material, node )[0]
  5840. M += self.generate_texture_unit( node.texture, name=name, uv_layer=geo.uv_layer )
  5841. elif slots:
  5842. for slot in slots:
  5843. M += self.generate_texture_unit( slot.texture, slot=slot )
  5844. M += indent(2, '}' ) # end pass
  5845. return M
  5846. def generate_texture_unit(self, texture, slot=None, name=None, uv_layer=None):
  5847. if not hasattr(texture, 'image'):
  5848. print('WARNING: texture must be of type IMAGE->', texture)
  5849. return ''
  5850. if not texture.image:
  5851. print('WARNING: texture has no image assigned->', texture)
  5852. return ''
  5853. #if slot: print(dir(slot))
  5854. if slot and not slot.use: return ''
  5855. path = self.path #CONFIG['PATH']
  5856. M = ''; _alphahack = None
  5857. if not name: name = '' #texture.name # (its unsafe to use texture block name)
  5858. M += indent(3, 'texture_unit %s' %name, '{' )
  5859. if texture.library: # support library linked textures
  5860. libpath = os.path.split( bpy.path.abspath(texture.library.filepath) )[0]
  5861. iurl = bpy.path.abspath( texture.image.filepath, libpath )
  5862. else:
  5863. iurl = bpy.path.abspath( texture.image.filepath )
  5864. postname = texname = os.path.split(iurl)[-1]
  5865. destpath = path
  5866. if texture.image.packed_file:
  5867. orig = texture.image.filepath
  5868. iurl = os.path.join(path, texname)
  5869. if '.' not in iurl:
  5870. print('WARNING: packed image is of unknown type - assuming PNG format')
  5871. iurl += '.png'
  5872. texname = postname = os.path.split(iurl)[-1]
  5873. if not os.path.isfile( iurl ):
  5874. if self.touch_textures:
  5875. print('MESSAGE: unpacking image: ', iurl)
  5876. texture.image.filepath = iurl
  5877. texture.image.save()
  5878. texture.image.filepath = orig
  5879. else:
  5880. print('MESSAGE: packed image already in temp, not updating', iurl)
  5881. if is_image_postprocessed( texture.image ):
  5882. postname = self._reformat( texname, texture.image )
  5883. print('MESSAGE: image postproc',postname)
  5884. M += indent(4, 'texture %s' %postname )
  5885. exmode = texture.extension
  5886. if exmode in TextureUnit.tex_address_mode:
  5887. M += indent(4, 'tex_address_mode %s' %TextureUnit.tex_address_mode[exmode] )
  5888. # TODO - hijack nodes for better control?
  5889. if slot: # classic blender material slot options
  5890. if exmode == 'CLIP': M += indent(4, 'tex_border_colour %s %s %s' %(slot.color.r, slot.color.g, slot.color.b) )
  5891. M += indent(4, 'scale %s %s' %(1.0/slot.scale.x, 1.0/slot.scale.y) )
  5892. if slot.texture_coords == 'REFLECTION':
  5893. if slot.mapping == 'SPHERE':
  5894. M += indent(4, 'env_map spherical' )
  5895. elif slot.mapping == 'FLAT':
  5896. M += indent(4, 'env_map planar' )
  5897. else: print('WARNING: <%s> has a non-UV mapping type (%s) and not picked a proper projection type of: Sphere or Flat' %(texture.name, slot.mapping))
  5898. ox,oy,oz = slot.offset
  5899. if ox or oy:
  5900. M += indent(4, 'scroll %s %s' %(ox,oy) )
  5901. if oz:
  5902. M += indent(4, 'rotate %s' %oz )
  5903. #if slot.use_map_emission: # problem, user will want to use emission sometimes
  5904. if slot.use_from_dupli: # hijacked again - june7th
  5905. M += indent(4, 'rotate_anim %s' %slot.emission_color_factor )
  5906. if slot.use_map_scatter: # hijacked from volume shaders
  5907. M += indent(4, 'scroll_anim %s %s ' %(slot.density_factor, slot.emission_factor) )
  5908. if slot.uv_layer:
  5909. idx = find_uv_layer_index( slot.uv_layer, self.material )
  5910. M += indent(4, 'tex_coord_set %s' %idx)
  5911. rgba = False
  5912. if texture.image.depth == 32: rgba = True
  5913. btype = slot.blend_type # TODO - fix this hack if/when slots support pyRNA
  5914. ex = False; texop = None
  5915. if btype in TextureUnit.colour_op:
  5916. if btype=='MIX' and slot.use_map_alpha and not slot.use_stencil:
  5917. if slot.diffuse_color_factor >= 1.0: texop = 'alpha_blend'
  5918. else:
  5919. texop = TextureUnit.colour_op[ btype ]
  5920. ex = True
  5921. elif btype=='MIX' and slot.use_map_alpha and slot.use_stencil:
  5922. texop = 'blend_current_alpha'; ex=True
  5923. elif btype=='MIX' and not slot.use_map_alpha and slot.use_stencil:
  5924. texop = 'blend_texture_alpha'; ex=True
  5925. else:
  5926. texop = TextureUnit.colour_op[ btype ]
  5927. elif btype in TextureUnit.colour_op_ex:
  5928. texop = TextureUnit.colour_op_ex[ btype ]
  5929. ex = True
  5930. if texop and ex:
  5931. if texop == 'blend_manual':
  5932. factor = 1.0 - slot.diffuse_color_factor
  5933. M += indent(4, 'colour_op_ex %s src_texture src_current %s' %(texop, factor) )
  5934. else:
  5935. M += indent(4, 'colour_op_ex %s src_texture src_current' %texop )
  5936. elif texop:
  5937. M += indent(4, 'colour_op %s' %texop )
  5938. else:
  5939. if uv_layer:
  5940. idx = find_uv_layer_index( uv_layer )
  5941. M += indent(4, 'tex_coord_set %s' %idx)
  5942. M += indent(3, '}' )
  5943. if self.touch_textures:
  5944. # Copy texture only if newer
  5945. if not os.path.isfile(iurl):
  5946. Report.warnings.append('Missing texture: %s' %iurl )
  5947. else:
  5948. desturl = os.path.join( destpath, texname )
  5949. updated = False
  5950. if not os.path.isfile( desturl ) or os.stat( desturl ).st_mtime < os.stat( iurl ).st_mtime:
  5951. f = open( desturl, 'wb' )
  5952. f.write( open(iurl,'rb').read() )
  5953. f.close()
  5954. updated = True
  5955. posturl = os.path.join(destpath,postname)
  5956. if is_image_postprocessed( texture.image ):
  5957. if not os.path.isfile( posturl ) or updated:
  5958. self.image_magick( texture, desturl ) # calls nvconvert if required
  5959. return M
  5960. class TextureUnit(object):
  5961. colour_op = {
  5962. 'MIX' : 'modulate', # Ogre Default - was "replace" but that kills lighting
  5963. 'ADD' : 'add',
  5964. 'MULTIPLY' : 'modulate',
  5965. #'alpha_blend' : '',
  5966. }
  5967. colour_op_ex = {
  5968. 'MIX' : 'blend_manual',
  5969. 'SCREEN': 'modulate_x2',
  5970. 'LIGHTEN': 'modulate_x4',
  5971. 'SUBTRACT': 'subtract',
  5972. 'OVERLAY': 'add_signed',
  5973. 'DIFFERENCE': 'dotproduct', # best match?
  5974. 'VALUE': 'blend_diffuse_colour',
  5975. }
  5976. tex_address_mode = {
  5977. 'REPEAT': 'wrap',
  5978. 'EXTEND': 'clamp',
  5979. 'CLIP' : 'border',
  5980. 'CHECKER' : 'mirror'
  5981. }
  5982. @UI
  5983. class PANEL_Object(bpy.types.Panel):
  5984. bl_space_type = 'PROPERTIES'
  5985. bl_region_type = 'WINDOW'
  5986. bl_context = "object"
  5987. bl_label = "Object+"
  5988. @classmethod
  5989. def poll(cls, context):
  5990. if _USE_TUNDRA_ and context.active_object:
  5991. return True
  5992. def draw(self, context):
  5993. ob = context.active_object
  5994. layout = self.layout
  5995. box = layout.box()
  5996. box.prop( ob, 'cast_shadows' )
  5997. box.prop( ob, 'use_draw_distance' )
  5998. if ob.use_draw_distance:
  5999. box.prop( ob, 'draw_distance' )
  6000. #if ob.find_armature():
  6001. if ob.type == 'EMPTY':
  6002. box.prop( ob, 'use_avatar' )
  6003. box.prop( ob, 'avatar_reference' )
  6004. @UI
  6005. class PANEL_Speaker(bpy.types.Panel):
  6006. bl_space_type = 'PROPERTIES'
  6007. bl_region_type = 'WINDOW'
  6008. bl_context = "data"
  6009. bl_label = "Sound+"
  6010. @classmethod
  6011. def poll(cls, context):
  6012. if context.active_object and context.active_object.type=='SPEAKER': return True
  6013. def draw(self, context):
  6014. layout = self.layout
  6015. box = layout.box()
  6016. box.prop( context.active_object.data, 'play_on_load' )
  6017. box.prop( context.active_object.data, 'loop' )
  6018. box.prop( context.active_object.data, 'use_spatial' )
  6019. @UI
  6020. class PANEL_MultiResLOD(bpy.types.Panel):
  6021. bl_space_type = 'PROPERTIES'
  6022. bl_region_type = 'WINDOW'
  6023. bl_context = "modifier"
  6024. bl_label = "Multi-Resolution LOD"
  6025. @classmethod
  6026. def poll(cls, context):
  6027. if context.active_object and context.active_object.type=='MESH':
  6028. ob = context.active_object
  6029. if ob.modifiers and ob.modifiers[0].type=='MULTIRES':
  6030. return True
  6031. def draw(self, context):
  6032. ob = context.active_object
  6033. layout = self.layout
  6034. box = layout.box()
  6035. box.prop( ob, 'use_multires_lod' )
  6036. if ob.use_multires_lod:
  6037. box.prop( ob, 'multires_lod_range' )
  6038. ## Public API (continued)
  6039. def material_name( mat ):
  6040. if type(mat) is str: return mat
  6041. elif not mat.library: return mat.name
  6042. else: return mat.name + mat.library.filepath.replace('/','_')
  6043. def export_mesh(ob, path='/tmp', force_name=None, ignore_shape_animation=False, normals=True):
  6044. ''' returns materials used by the mesh '''
  6045. return dot_mesh( ob, path, force_name, ignore_shape_animation, normals )
  6046. def generate_material(mat, path='/tmp', copy_programs=False, touch_textures=False):
  6047. ''' returns generated material string '''
  6048. safename = material_name(mat) # supports blender library linking
  6049. M = '// %s genrated by blender2ogre %s\n\n' % (mat.name, VERSION)
  6050. M += 'material %s \n{\n' % safename # start material
  6051. if mat.use_shadows:
  6052. M += indent(1, 'receive_shadows on \n')
  6053. else:
  6054. M += indent(1, 'receive_shadows off \n')
  6055. M += indent(1, 'technique', '{' ) # technique GLSL, CG
  6056. w = OgreMaterialGenerator(mat, path=path, touch_textures=touch_textures)
  6057. if copy_programs:
  6058. progs = w.get_active_programs()
  6059. for prog in progs:
  6060. prog.save(path)
  6061. header = w.get_header()
  6062. passes = w.get_passes()
  6063. M += '\n'.join(passes)
  6064. M += indent(1, '}' ) # end technique
  6065. M += '}\n' # end material
  6066. if len(header) > 0:
  6067. return header + '\n' + M
  6068. else:
  6069. return M
  6070. def get_ogre_user_material( name ):
  6071. if name in MaterialScripts.ALL_MATERIALS:
  6072. return MaterialScripts.ALL_MATERIALS[ name ]
  6073. def get_shader_program( name ):
  6074. if name in OgreProgram.PROGRAMS:
  6075. return OgreProgram.PROGRAMS[ name ]
  6076. else:
  6077. print('WARNING: no shader program named: %s' %name)
  6078. def get_shader_programs():
  6079. return OgreProgram.PROGRAMS.values()
  6080. def parse_material_and_program_scripts( path, scripts, progs, missing ): # recursive
  6081. for name in os.listdir(path):
  6082. url = os.path.join(path,name)
  6083. if os.path.isdir( url ):
  6084. parse_material_and_program_scripts( url, scripts, progs, missing )
  6085. elif os.path.isfile( url ):
  6086. if name.endswith( '.material' ):
  6087. print( '<found material>', url )
  6088. scripts.append( MaterialScripts( url ) )
  6089. if name.endswith('.program'):
  6090. print( '<found program>', url )
  6091. data = open( url, 'rb' ).read().decode('utf-8')
  6092. chk = []; chunks = [ chk ]
  6093. for line in data.splitlines():
  6094. line = line.split('//')[0]
  6095. if line.startswith('}'):
  6096. chk.append( line )
  6097. chk = []; chunks.append( chk )
  6098. elif line.strip():
  6099. chk.append( line )
  6100. for chk in chunks:
  6101. if not chk: continue
  6102. p = OgreProgram( data='\n'.join(chk) )
  6103. if p.source:
  6104. ok = p.reload()
  6105. if not ok: missing.append( p )
  6106. else: progs.append( p )
  6107. def update_parent_material_path( path ):
  6108. ''' updates RNA '''
  6109. print( '>>SEARCHING FOR OGRE MATERIALS: %s' %path )
  6110. scripts = []
  6111. progs = []
  6112. missing = []
  6113. parse_material_and_program_scripts( path, scripts, progs, missing )
  6114. if missing:
  6115. print('WARNING: missing shader programs:')
  6116. for p in missing: print(p.name)
  6117. if missing and not progs:
  6118. print('WARNING: no shader programs were found - set "SHADER_PROGRAMS" to your path')
  6119. MaterialScripts.reset_rna( callback=bpyShaders.on_change_parent_material )
  6120. return scripts, progs
  6121. def get_subcollision_meshes():
  6122. ''' returns all collision meshes found in the scene '''
  6123. r = []
  6124. for ob in bpy.context.scene.objects:
  6125. if ob.type=='MESH' and ob.subcollision: r.append( ob )
  6126. return r
  6127. def get_objects_with_subcollision():
  6128. ''' returns objects that have active sub-collisions '''
  6129. r = []
  6130. for ob in bpy.context.scene.objects:
  6131. if ob.type=='MESH' and ob.collision_mode not in ('NONE', 'PRIMITIVE'):
  6132. r.append( ob )
  6133. return r
  6134. def get_subcollisions(ob):
  6135. prefix = '%s.' %ob.collision_mode
  6136. r = []
  6137. for child in ob.children:
  6138. if child.subcollision and child.name.startswith( prefix ):
  6139. r.append( child )
  6140. return r
  6141. class bpyShaders(bpy.types.Operator):
  6142. '''operator: enables material nodes (workaround for not having IDPointers in pyRNA)'''
  6143. bl_idname = "ogre.force_setup_material_passes"
  6144. bl_label = "force bpyShaders"
  6145. bl_options = {'REGISTER'}
  6146. @classmethod
  6147. def poll(cls, context):
  6148. if context.active_object and context.active_object.active_material: return True
  6149. def invoke(self, context, event):
  6150. mat = context.active_object.active_material
  6151. mat.use_material_passes = True
  6152. bpyShaders.create_material_passes( mat )
  6153. return {'FINISHED'}
  6154. ## setup from MaterialScripts.reset_rna( callback=bpyShaders.on_change_parent_material )
  6155. @staticmethod
  6156. def on_change_parent_material(mat,context):
  6157. print(mat,context)
  6158. print('callback', mat.ogre_parent_material)
  6159. @staticmethod
  6160. def get_subnodes(mat, type='TEXTURE'):
  6161. d = {}
  6162. for node in mat.nodes:
  6163. if node.type==type: d[node.name] = node
  6164. keys = list(d.keys())
  6165. keys.sort()
  6166. r = []
  6167. for key in keys: r.append( d[key] )
  6168. return r
  6169. @staticmethod
  6170. def get_texture_subnodes( parent, submaterial=None ):
  6171. if not submaterial: submaterial = parent.active_node_material
  6172. d = {}
  6173. for link in parent.node_tree.links:
  6174. if link.from_node and link.from_node.type=='TEXTURE':
  6175. if link.to_node and link.to_node.type == 'MATERIAL_EXT':
  6176. if link.to_node.material:
  6177. if link.to_node.material.name == submaterial.name:
  6178. node = link.from_node
  6179. d[node.name] = node
  6180. keys = list(d.keys()) # this breaks if the user renames the node - TODO improve me
  6181. keys.sort()
  6182. r = []
  6183. for key in keys: r.append( d[key] )
  6184. return r
  6185. @staticmethod
  6186. def get_connected_input_nodes( material, node ):
  6187. r = []
  6188. for link in material.node_tree.links:
  6189. if link.to_node and link.to_node.name == node.name:
  6190. r.append( link.from_node )
  6191. return r
  6192. @staticmethod
  6193. def get_or_create_material_passes( mat, n=8 ):
  6194. if not mat.node_tree:
  6195. print('CREATING MATERIAL PASSES', n)
  6196. bpyShaders.create_material_passes( mat, n )
  6197. d = {} # funky, blender259 had this in order, now blender260 has random order
  6198. for node in mat.node_tree.nodes:
  6199. if node.type == 'MATERIAL_EXT' and node.name.startswith('GEN.'):
  6200. d[node.name] = node
  6201. keys = list(d.keys())
  6202. keys.sort()
  6203. r = []
  6204. for key in keys: r.append( d[key] )
  6205. return r
  6206. @staticmethod
  6207. def get_or_create_texture_nodes( mat, n=6 ): # currently not used
  6208. #print('bpyShaders.get_or_create_texture_nodes( %s, %s )' %(mat,n))
  6209. assert mat.node_tree # must call create_material_passes first
  6210. m = []
  6211. for node in mat.node_tree.nodes:
  6212. if node.type == 'MATERIAL_EXT' and node.name.startswith('GEN.'):
  6213. m.append( node )
  6214. if not m:
  6215. m = bpyShaders.get_or_create_material_passes(mat)
  6216. print(m)
  6217. r = []
  6218. for link in mat.node_tree.links:
  6219. print(link, link.to_node, link.from_node)
  6220. if link.to_node and link.to_node.name.startswith('GEN.') and link.from_node.type=='TEXTURE':
  6221. r.append( link.from_node )
  6222. if not r:
  6223. print('--missing texture nodes--')
  6224. r = bpyShaders.create_texture_nodes( mat, n )
  6225. return r
  6226. @staticmethod
  6227. def create_material_passes( mat, n=8, textures=True ):
  6228. #print('bpyShaders.create_material_passes( %s, %s )' %(mat,n))
  6229. mat.use_nodes = True
  6230. tree = mat.node_tree # valid pointer now
  6231. nodes = bpyShaders.get_subnodes( tree, 'MATERIAL' ) # assign base material
  6232. if nodes and not nodes[0].material:
  6233. nodes[0].material = mat
  6234. r = []
  6235. x = 680
  6236. for i in range( n ):
  6237. node = tree.nodes.new( type='MATERIAL_EXT' )
  6238. node.name = 'GEN.%s' %i
  6239. node.location.x = x; node.location.y = 640
  6240. r.append( node )
  6241. x += 220
  6242. #mat.use_nodes = False # TODO set user material to default output
  6243. if textures:
  6244. texnodes = bpyShaders.create_texture_nodes( mat )
  6245. print( texnodes )
  6246. return r
  6247. @staticmethod
  6248. def create_texture_nodes( mat, n=6, geoms=True ):
  6249. #print('bpyShaders.create_texture_nodes( %s )' %mat)
  6250. assert mat.node_tree # must call create_material_passes first
  6251. mats = bpyShaders.get_or_create_material_passes( mat )
  6252. r = {}; x = 400
  6253. for i,m in enumerate(mats):
  6254. r['material'] = m; r['textures'] = []; r['geoms'] = []
  6255. inputs = [] # other inputs mess up material preview #
  6256. for tag in ['Mirror', 'Ambient', 'Emit', 'SpecTra', 'Ray Mirror', 'Translucency']:
  6257. inputs.append( m.inputs[ tag ] )
  6258. for j in range(n):
  6259. tex = mat.node_tree.nodes.new( type='TEXTURE' )
  6260. tex.name = 'TEX.%s.%s' %(j, m.name)
  6261. tex.location.x = x - (j*16)
  6262. tex.location.y = -(j*230)
  6263. input = inputs[j]; output = tex.outputs['Color']
  6264. link = mat.node_tree.links.new( input, output )
  6265. r['textures'].append( tex )
  6266. if geoms:
  6267. geo = mat.node_tree.nodes.new( type='GEOMETRY' )
  6268. link = mat.node_tree.links.new( tex.inputs['Vector'], geo.outputs['UV'] )
  6269. geo.location.x = x - (j*16) - 250
  6270. geo.location.y = -(j*250) - 1500
  6271. r['geoms'].append( geo )
  6272. x += 220
  6273. return r
  6274. @UI
  6275. class PANEL_node_editor_ui( bpy.types.Panel ):
  6276. bl_space_type = 'NODE_EDITOR'
  6277. bl_region_type = 'UI'
  6278. bl_label = "Ogre Material"
  6279. @classmethod
  6280. def poll(self,context):
  6281. if context.space_data.id:
  6282. return True
  6283. def draw(self, context):
  6284. layout = self.layout
  6285. topmat = context.space_data.id # the top level node_tree
  6286. mat = topmat.active_node_material # the currently selected sub-material
  6287. if not mat or topmat.name == mat.name:
  6288. self.bl_label = topmat.name
  6289. if not topmat.use_material_passes:
  6290. layout.operator(
  6291. 'ogre.force_setup_material_passes',
  6292. text="Ogre Material Layers",
  6293. icon='SCENE_DATA'
  6294. )
  6295. ogre_material_panel( layout, topmat, show_programs=False )
  6296. elif mat:
  6297. self.bl_label = mat.name
  6298. ogre_material_panel( layout, mat, topmat, show_programs=False )
  6299. @UI
  6300. class PANEL_node_editor_ui_extra( bpy.types.Panel ):
  6301. bl_space_type = 'NODE_EDITOR'
  6302. bl_region_type = 'UI'
  6303. bl_label = "Ogre Material Advanced"
  6304. bl_options = {'DEFAULT_CLOSED'}
  6305. @classmethod
  6306. def poll(self,context):
  6307. if context.space_data.id: return True
  6308. def draw(self, context):
  6309. layout = self.layout
  6310. topmat = context.space_data.id # the top level node_tree
  6311. mat = topmat.active_node_material # the currently selected sub-material
  6312. if mat:
  6313. self.bl_label = mat.name + ' (advanced)'
  6314. ogre_material_panel_extra( layout, mat )
  6315. else:
  6316. self.bl_label = topmat.name + ' (advanced)'
  6317. ogre_material_panel_extra( layout, topmat )
  6318. def ogre_material_panel_extra( parent, mat ):
  6319. box = parent.box()
  6320. header = box.row()
  6321. if mat.use_fixed_pipeline:
  6322. header.prop( mat, 'use_fixed_pipeline', text='Fixed Pipeline', icon='LAMP_SUN' )
  6323. row = box.row()
  6324. row.prop(mat, "use_vertex_color_paint", text="Vertex Colors")
  6325. row.prop(mat, "use_shadeless")
  6326. if mat.use_shadeless and not mat.use_vertex_color_paint:
  6327. row = box.row()
  6328. row.prop(mat, "diffuse_color", text='')
  6329. elif not mat.use_shadeless:
  6330. if not mat.use_vertex_color_paint:
  6331. row = box.row()
  6332. row.prop(mat, "diffuse_color", text='')
  6333. row.prop(mat, "diffuse_intensity", text='intensity')
  6334. row = box.row()
  6335. row.prop(mat, "specular_color", text='')
  6336. row.prop(mat, "specular_intensity", text='intensity')
  6337. row = box.row()
  6338. row.prop(mat, "specular_hardness")
  6339. row = box.row()
  6340. row.prop(mat, "ambient")
  6341. #row = box.row()
  6342. row.prop(mat, "emit")
  6343. box.prop(mat, 'use_ogre_advanced_options', text='---guru options---' )
  6344. else:
  6345. header.prop( mat, 'use_fixed_pipeline', text='', icon='LAMP_SUN' )
  6346. header.prop(mat, 'use_ogre_advanced_options', text='---guru options---' )
  6347. if mat.use_ogre_advanced_options:
  6348. box.prop(mat, 'offset_z')
  6349. box.prop(mat, "use_shadows")
  6350. box.prop(mat, 'ogre_depth_write' )
  6351. for tag in 'ogre_colour_write ogre_lighting ogre_normalise_normals ogre_light_clip_planes ogre_light_scissor ogre_alpha_to_coverage ogre_depth_check'.split():
  6352. box.prop(mat, tag)
  6353. for tag in 'ogre_polygon_mode ogre_shading ogre_cull_hardware ogre_transparent_sorting ogre_illumination_stage ogre_depth_func ogre_scene_blend_op'.split():
  6354. box.prop(mat, tag)
  6355. def ogre_material_panel( layout, mat, parent=None, show_programs=True ):
  6356. box = layout.box()
  6357. header = box.row()
  6358. header.prop(mat, 'ogre_scene_blend', text='')
  6359. if mat.ogre_scene_blend and 'alpha' in mat.ogre_scene_blend:
  6360. row = box.row()
  6361. if mat.use_transparency:
  6362. row.prop(mat, "use_transparency", text='')
  6363. row.prop(mat, "alpha")
  6364. else:
  6365. row.prop(mat, "use_transparency", text='Transparent')
  6366. if not parent:
  6367. return # only allow on pass1 and higher
  6368. header.prop(mat, 'use_ogre_parent_material', icon='FILE_SCRIPT', text='')
  6369. if mat.use_ogre_parent_material:
  6370. row = box.row()
  6371. row.prop(mat, 'ogre_parent_material', text='')
  6372. s = get_ogre_user_material( mat.ogre_parent_material ) # gets by name
  6373. if s and (s.vertex_programs or s.fragment_programs):
  6374. progs = s.get_programs()
  6375. split = box.row()
  6376. texnodes = None
  6377. if parent:
  6378. texnodes = bpyShaders.get_texture_subnodes( parent, submaterial=mat )
  6379. elif mat.node_tree:
  6380. texnodes = bpyShaders.get_texture_subnodes( mat ) # assume toplevel
  6381. if not progs:
  6382. bx = split.box()
  6383. bx.label( text='(missing shader programs)', icon='ERROR' )
  6384. elif s.texture_units and texnodes:
  6385. bx = split.box()
  6386. for i,name in enumerate(s.texture_units_order):
  6387. if i<len(texnodes):
  6388. row = bx.row()
  6389. #row.label( text=name )
  6390. tex = texnodes[i]
  6391. row.prop( tex, 'texture', text=name )
  6392. if parent:
  6393. inputs = bpyShaders.get_connected_input_nodes( parent, tex )
  6394. if inputs:
  6395. geo = inputs[0]
  6396. assert geo.type == 'GEOMETRY'
  6397. row.prop( geo, 'uv_layer', text='UV' )
  6398. else:
  6399. print('WARNING: no slot for texture unit:', name)
  6400. if show_programs and (s.vertex_programs or s.fragment_programs):
  6401. bx = box.box()
  6402. for name in s.vertex_programs:
  6403. bx.label( text=name )
  6404. for name in s.fragment_programs:
  6405. bx.label( text=name )
  6406. ## Blender addon main entry point.
  6407. ## Allows directly running by "blender --python blender2ogre.py"
  6408. if __name__ == "__main__":
  6409. register()