makepandacore.py 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749
  1. ########################################################################
  2. ##
  3. ## This file, makepandacore, contains all the global state and
  4. ## global functions for the makepanda system.
  5. ##
  6. ########################################################################
  7. import sys,os,time,stat,string,re,getopt,fnmatch,threading,signal,shutil,platform,glob,getpass,signal
  8. import subprocess
  9. from distutils import sysconfig
  10. if sys.version_info >= (3, 0):
  11. import pickle
  12. import _thread as thread
  13. import configparser
  14. else:
  15. import cPickle as pickle
  16. import thread
  17. import ConfigParser as configparser
  18. SUFFIX_INC = [".cxx",".cpp",".c",".h",".I",".yxx",".lxx",".mm",".rc",".r"]
  19. SUFFIX_DLL = [".dll",".dlo",".dle",".dli",".dlm",".mll",".exe",".pyd",".ocx"]
  20. SUFFIX_LIB = [".lib",".ilb"]
  21. VCS_DIRS = set(["CVS", "CVSROOT", ".git", ".hg", "__pycache__"])
  22. VCS_FILES = set([".cvsignore", ".gitignore", ".gitmodules", ".hgignore"])
  23. STARTTIME = time.time()
  24. MAINTHREAD = threading.currentThread()
  25. OUTPUTDIR = "built"
  26. CUSTOM_OUTPUTDIR = False
  27. THIRDPARTYBASE = None
  28. THIRDPARTYDIR = None
  29. OPTIMIZE = "3"
  30. VERBOSE = False
  31. LINK_ALL_STATIC = False
  32. TARGET = None
  33. TARGET_ARCH = None
  34. HAS_TARGET_ARCH = False
  35. TOOLCHAIN_PREFIX = ""
  36. ANDROID_ABI = None
  37. ANDROID_TRIPLE = None
  38. ANDROID_API = None
  39. SYS_LIB_DIRS = []
  40. SYS_INC_DIRS = []
  41. DEBUG_DEPENDENCIES = False
  42. # Is the current Python a 32-bit or 64-bit build? There doesn't
  43. # appear to be a universal test for this.
  44. if sys.platform == 'darwin':
  45. # On OSX, platform.architecture reports '64bit' even if it is
  46. # currently running in 32-bit mode. But sys.maxint is a reliable
  47. # indicator.
  48. if sys.version_info >= (3, 0):
  49. host_64 = (sys.maxsize > 0x100000000)
  50. else:
  51. host_64 = (sys.maxint > 0x100000000)
  52. else:
  53. # On Windows (and Linux?) sys.maxint reports 0x7fffffff even on a
  54. # 64-bit build. So we stick with platform.architecture in that
  55. # case.
  56. host_64 = (platform.architecture()[0] == '64bit')
  57. # On Android, get a list of all the public system libraries.
  58. ANDROID_SYS_LIBS = []
  59. if os.path.exists("/etc/public.libraries.txt"):
  60. for line in open("/etc/public.libraries.txt", "r"):
  61. line = line.strip()
  62. ANDROID_SYS_LIBS.append(line)
  63. ########################################################################
  64. ##
  65. ## Visual C++ Version (MSVC) and Visual Studio Information Map
  66. ##
  67. ########################################################################
  68. MSVCVERSIONINFO = {
  69. (10,0): {"vsversion":(10,0), "vsname":"Visual Studio 2010"},
  70. (11,0): {"vsversion":(11,0), "vsname":"Visual Studio 2012"},
  71. (12,0): {"vsversion":(12,0), "vsname":"Visual Studio 2013"},
  72. (14,0): {"vsversion":(14,0), "vsname":"Visual Studio 2015"},
  73. (14,1): {"vsversion":(15,0), "vsname":"Visual Studio 2017"},
  74. (14,2): {"vsversion":(16,0), "vsname":"Visual Studio 2019"},
  75. }
  76. ########################################################################
  77. ##
  78. ## Maya and Max Version List (with registry keys)
  79. ##
  80. ########################################################################
  81. MAYAVERSIONINFO = [("MAYA6", "6.0"),
  82. ("MAYA65", "6.5"),
  83. ("MAYA7", "7.0"),
  84. ("MAYA8", "8.0"),
  85. ("MAYA85", "8.5"),
  86. ("MAYA2008","2008"),
  87. ("MAYA2009","2009"),
  88. ("MAYA2010","2010"),
  89. ("MAYA2011","2011"),
  90. ("MAYA2012","2012"),
  91. ("MAYA2013","2013"),
  92. ("MAYA20135","2013.5"),
  93. ("MAYA2014","2014"),
  94. ("MAYA2015","2015"),
  95. ("MAYA2016","2016"),
  96. ("MAYA20165","2016.5"),
  97. ("MAYA2017","2017"),
  98. ("MAYA2018","2018"),
  99. ("MAYA2019","2019"),
  100. ]
  101. MAXVERSIONINFO = [("MAX6", "SOFTWARE\\Autodesk\\3DSMAX\\6.0", "installdir", "maxsdk\\cssdk\\include"),
  102. ("MAX7", "SOFTWARE\\Autodesk\\3DSMAX\\7.0", "Installdir", "maxsdk\\include\\CS"),
  103. ("MAX8", "SOFTWARE\\Autodesk\\3DSMAX\\8.0", "Installdir", "maxsdk\\include\\CS"),
  104. ("MAX9", "SOFTWARE\\Autodesk\\3DSMAX\\9.0", "Installdir", "maxsdk\\include\\CS"),
  105. ("MAX2009", "SOFTWARE\\Autodesk\\3DSMAX\\11.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  106. ("MAX2010", "SOFTWARE\\Autodesk\\3DSMAX\\12.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  107. ("MAX2011", "SOFTWARE\\Autodesk\\3DSMAX\\13.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  108. ("MAX2012", "SOFTWARE\\Autodesk\\3DSMAX\\14.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  109. ("MAX2013", "SOFTWARE\\Autodesk\\3DSMAX\\15.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  110. ("MAX2014", "SOFTWARE\\Autodesk\\3DSMAX\\16.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  111. ]
  112. MAYAVERSIONS = []
  113. MAXVERSIONS = []
  114. DXVERSIONS = ["DX9"]
  115. for (ver,key) in MAYAVERSIONINFO:
  116. MAYAVERSIONS.append(ver)
  117. for (ver,key1,key2,subdir) in MAXVERSIONINFO:
  118. MAXVERSIONS.append(ver)
  119. ########################################################################
  120. ##
  121. ## Potentially Conflicting Files
  122. ##
  123. ## The next function can warn about the existence of files that are
  124. ## commonly generated by ppremake that may conflict with the build.
  125. ##
  126. ########################################################################
  127. CONFLICTING_FILES=["dtool/src/dtoolutil/pandaVersion.h",
  128. "dtool/src/dtoolutil/checkPandaVersion.h",
  129. "dtool/src/dtoolutil/checkPandaVersion.cxx",
  130. "dtool/src/prc/prc_parameters.h",
  131. "panda/src/speedtree/speedtree_parameters.h",
  132. "direct/src/plugin/p3d_plugin_config.h",
  133. "direct/src/plugin_activex/P3DActiveX.rc",
  134. "direct/src/plugin_npapi/nppanda3d.rc",
  135. "direct/src/plugin_standalone/panda3d.rc"]
  136. def WarnConflictingFiles(delete = False):
  137. for cfile in CONFLICTING_FILES:
  138. if os.path.exists(cfile):
  139. Warn("file may conflict with build:", cfile)
  140. if delete:
  141. os.unlink(cfile)
  142. print("Deleted.")
  143. ########################################################################
  144. ##
  145. ## The exit routine will normally
  146. ##
  147. ## - print a message
  148. ## - save the dependency cache
  149. ## - exit
  150. ##
  151. ## However, if it is invoked inside a thread, it instead:
  152. ##
  153. ## - prints a message
  154. ## - raises the "initiate-exit" exception
  155. ##
  156. ## If you create a thread, you must be prepared to catch this
  157. ## exception, save the dependency cache, and exit.
  158. ##
  159. ########################################################################
  160. WARNINGS = []
  161. THREADS = {}
  162. HAVE_COLORS = False
  163. SETF = ""
  164. try:
  165. import curses
  166. curses.setupterm()
  167. SETF = curses.tigetstr("setf")
  168. if (SETF == None):
  169. SETF = curses.tigetstr("setaf")
  170. assert SETF != None
  171. HAVE_COLORS = sys.stdout.isatty()
  172. except: pass
  173. def DisableColors():
  174. global HAVE_COLORS
  175. HAVE_COLORS = False
  176. def GetColor(color = None):
  177. if not HAVE_COLORS:
  178. return ""
  179. if color != None:
  180. color = color.lower()
  181. if (color == "blue"):
  182. token = curses.tparm(SETF, 1)
  183. elif (color == "green"):
  184. token = curses.tparm(SETF, 2)
  185. elif (color == "cyan"):
  186. token = curses.tparm(SETF, 3)
  187. elif (color == "red"):
  188. token = curses.tparm(SETF, 4)
  189. elif (color == "magenta"):
  190. token = curses.tparm(SETF, 5)
  191. elif (color == "yellow"):
  192. token = curses.tparm(SETF, 6)
  193. else:
  194. token = curses.tparm(curses.tigetstr("sgr0"))
  195. if sys.version_info >= (3, 0):
  196. return token.decode('ascii')
  197. else:
  198. return token
  199. def ColorText(color, text, reset=True):
  200. if reset is True:
  201. return ''.join((GetColor(color), text, GetColor()))
  202. else:
  203. return ''.join((GetColor(color), text))
  204. def PrettyTime(t):
  205. t = int(t)
  206. hours = t // 3600
  207. t -= hours * 3600
  208. minutes = t // 60
  209. t -= minutes * 60
  210. seconds = t
  211. if hours:
  212. return "%d hours %d min" % (hours, minutes)
  213. if minutes:
  214. return "%d min %d sec" % (minutes, seconds)
  215. return "%d sec" % (seconds)
  216. def ProgressOutput(progress, msg, target = None):
  217. sys.stdout.flush()
  218. sys.stderr.flush()
  219. prefix = ""
  220. thisthread = threading.currentThread()
  221. if thisthread is MAINTHREAD:
  222. if progress is None:
  223. prefix = ""
  224. elif (progress >= 100.0):
  225. prefix = "%s[%s%d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  226. elif (progress < 10.0):
  227. prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  228. else:
  229. prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  230. else:
  231. global THREADS
  232. ident = thread.get_ident()
  233. if (ident not in THREADS):
  234. THREADS[ident] = len(THREADS) + 1
  235. prefix = "%s[%sT%d%s] " % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow"))
  236. if target is not None:
  237. suffix = ' ' + ColorText("green", target)
  238. else:
  239. suffix = GetColor()
  240. print(''.join((prefix, msg, suffix)))
  241. sys.stdout.flush()
  242. sys.stderr.flush()
  243. def exit(msg = ""):
  244. sys.stdout.flush()
  245. sys.stderr.flush()
  246. if (threading.currentThread() == MAINTHREAD):
  247. SaveDependencyCache()
  248. print("Elapsed Time: " + PrettyTime(time.time() - STARTTIME))
  249. print(msg)
  250. print(ColorText("red", "Build terminated."))
  251. sys.stdout.flush()
  252. sys.stderr.flush()
  253. ##Don't quit the interperter if I'm running this file directly (debugging)
  254. if __name__ != '__main__':
  255. os._exit(1)
  256. else:
  257. print(msg)
  258. raise "initiate-exit"
  259. def Warn(msg, extra=None):
  260. if extra is not None:
  261. print("%sWARNING:%s %s %s%s%s" % (GetColor("red"), GetColor(), msg, GetColor("green"), extra, GetColor()))
  262. else:
  263. print("%sWARNING:%s %s" % (GetColor("red"), GetColor(), msg))
  264. sys.stdout.flush()
  265. def Error(msg, extra=None):
  266. if extra is not None:
  267. print("%sERROR:%s %s %s%s%s" % (GetColor("red"), GetColor(), msg, GetColor("green"), extra, GetColor()))
  268. else:
  269. print("%sERROR:%s %s" % (GetColor("red"), GetColor(), msg))
  270. exit()
  271. ########################################################################
  272. ##
  273. ## SetTarget, GetTarget, GetHost
  274. ##
  275. ## These functions control cross-compilation.
  276. ##
  277. ########################################################################
  278. def GetHost():
  279. """Returns the host platform, ie. the one we're compiling on."""
  280. if sys.platform == 'win32' or sys.platform == 'cygwin':
  281. # sys.platform is win32 on 64-bits Windows as well.
  282. return 'windows'
  283. elif sys.platform == 'darwin':
  284. return 'darwin'
  285. elif sys.platform.startswith('linux'):
  286. try:
  287. # Python seems to offer no built-in way to check this.
  288. osname = subprocess.check_output(["uname", "-o"])
  289. if osname.strip().lower() == b'android':
  290. return 'android'
  291. else:
  292. return 'linux'
  293. except:
  294. return 'linux'
  295. elif sys.platform.startswith('freebsd'):
  296. return 'freebsd'
  297. else:
  298. exit('Unrecognized sys.platform: %s' % (sys.platform))
  299. def GetHostArch():
  300. """Returns the architecture we're compiling on.
  301. Its value is also platform-dependent, as different platforms
  302. have different architecture naming."""
  303. target = GetTarget()
  304. if target == 'windows':
  305. return 'x64' if host_64 else 'x86'
  306. machine = platform.machine()
  307. if machine.startswith('armv7'):
  308. return 'armv7a'
  309. else:
  310. return machine
  311. def SetTarget(target, arch=None):
  312. """Sets the target platform; the one we're compiling for. Also
  313. sets the target architecture (None for default, if any). Should
  314. be called *before* any calls are made to GetOutputDir, GetCC, etc."""
  315. global TARGET, TARGET_ARCH, HAS_TARGET_ARCH
  316. global TOOLCHAIN_PREFIX
  317. host = GetHost()
  318. host_arch = GetHostArch()
  319. if target is None:
  320. target = host
  321. else:
  322. target = target.lower()
  323. if arch is not None:
  324. HAS_TARGET_ARCH = True
  325. TOOLCHAIN_PREFIX = ''
  326. if target == 'windows':
  327. if arch == 'i386':
  328. arch = 'x86'
  329. elif arch == 'amd64':
  330. arch = 'x64'
  331. if arch is not None and arch != 'x86' and arch != 'x64':
  332. exit("Windows architecture must be x86 or x64")
  333. elif target == 'darwin':
  334. if arch == 'amd64':
  335. arch = 'x86_64'
  336. if arch is not None:
  337. choices = ('i386', 'x86_64', 'ppc', 'ppc64')
  338. if arch not in choices:
  339. exit('Mac OS X architecture must be one of %s' % (', '.join(choices)))
  340. elif target == 'android' or target.startswith('android-'):
  341. if arch is None:
  342. # If compiling on Android, default to same architecture. Otherwise, arm.
  343. if host == 'android':
  344. arch = host_arch
  345. else:
  346. arch = 'armv7a'
  347. # Did we specify an API level?
  348. global ANDROID_API
  349. target, _, api = target.partition('-')
  350. if api:
  351. ANDROID_API = int(api)
  352. elif arch in ('mips64', 'aarch64', 'x86_64'):
  353. # 64-bit platforms were introduced in Android 21.
  354. ANDROID_API = 21
  355. else:
  356. # Default to the lowest API level supported by NDK r16.
  357. ANDROID_API = 14
  358. # Determine the prefix for our gcc tools, eg. arm-linux-androideabi-gcc
  359. global ANDROID_ABI, ANDROID_TRIPLE
  360. if arch == 'armv7a':
  361. ANDROID_ABI = 'armeabi-v7a'
  362. ANDROID_TRIPLE = 'arm-linux-androideabi'
  363. elif arch == 'arm':
  364. ANDROID_ABI = 'armeabi'
  365. ANDROID_TRIPLE = 'arm-linux-androideabi'
  366. elif arch == 'aarch64':
  367. ANDROID_ABI = 'arm64-v8a'
  368. ANDROID_TRIPLE = 'aarch64-linux-android'
  369. elif arch == 'mips':
  370. ANDROID_ABI = 'mips'
  371. ANDROID_TRIPLE = 'mipsel-linux-android'
  372. elif arch == 'mips64':
  373. ANDROID_ABI = 'mips64'
  374. ANDROID_TRIPLE = 'mips64el-linux-android'
  375. elif arch == 'x86':
  376. ANDROID_ABI = 'x86'
  377. ANDROID_TRIPLE = 'i686-linux-android'
  378. elif arch == 'x86_64':
  379. ANDROID_ABI = 'x86_64'
  380. ANDROID_TRIPLE = 'x86_64-linux-android'
  381. else:
  382. exit('Android architecture must be arm, armv7a, aarch64, mips, mips64, x86 or x86_64')
  383. TOOLCHAIN_PREFIX = ANDROID_TRIPLE + '-'
  384. elif target == 'linux':
  385. if arch is not None:
  386. TOOLCHAIN_PREFIX = '%s-linux-gnu-' % arch
  387. elif host != 'linux':
  388. exit('Should specify an architecture when building for Linux')
  389. elif target == host:
  390. if arch is None or arch == host_arch:
  391. # Not a cross build.
  392. pass
  393. else:
  394. exit('Cannot cross-compile for %s-%s from %s-%s' % (target, arch, host, host_arch))
  395. else:
  396. exit('Cannot cross-compile for %s from %s' % (target, host))
  397. if arch is None:
  398. arch = host_arch
  399. TARGET = target
  400. TARGET_ARCH = arch
  401. def GetTarget():
  402. """Returns the platform we're compiling for. Defaults to GetHost()."""
  403. global TARGET
  404. if TARGET is None:
  405. TARGET = GetHost()
  406. return TARGET
  407. def HasTargetArch():
  408. """Returns True if the user specified an architecture to compile for."""
  409. return HAS_TARGET_ARCH
  410. def GetTargetArch():
  411. """Returns the architecture we're compiling for. Defaults to GetHostArch().
  412. Its value is also dependent on that of GetTarget(), as different platforms
  413. use a different architecture naming."""
  414. global TARGET_ARCH
  415. if TARGET_ARCH is None:
  416. TARGET_ARCH = GetHostArch()
  417. return TARGET_ARCH
  418. def CrossCompiling():
  419. """Returns True if we're cross-compiling."""
  420. return GetTarget() != GetHost()
  421. def GetCC():
  422. if TARGET in ('darwin', 'freebsd', 'android'):
  423. return os.environ.get('CC', TOOLCHAIN_PREFIX + 'clang')
  424. else:
  425. return os.environ.get('CC', TOOLCHAIN_PREFIX + 'gcc')
  426. def GetCXX():
  427. if TARGET in ('darwin', 'freebsd', 'android'):
  428. return os.environ.get('CXX', TOOLCHAIN_PREFIX + 'clang++')
  429. else:
  430. return os.environ.get('CXX', TOOLCHAIN_PREFIX + 'g++')
  431. def GetStrip():
  432. # Hack
  433. if TARGET == 'android':
  434. return TOOLCHAIN_PREFIX + 'strip'
  435. else:
  436. return 'strip'
  437. def GetAR():
  438. # Hack
  439. if TARGET == 'android':
  440. return TOOLCHAIN_PREFIX + 'ar'
  441. else:
  442. return 'ar'
  443. def GetRanlib():
  444. # Hack
  445. if TARGET == 'android':
  446. return TOOLCHAIN_PREFIX + 'ranlib'
  447. else:
  448. return 'ranlib'
  449. BISON = None
  450. def GetBison():
  451. global BISON
  452. if BISON is not None:
  453. return BISON
  454. # We now require a newer version of Bison than the one we previously
  455. # shipped in the win-util dir. The new version has a 'data'
  456. # subdirectory, so check for that.
  457. win_util_data = os.path.join(GetThirdpartyBase(), 'win-util', 'data')
  458. if GetHost() == 'windows' and os.path.isdir(win_util_data):
  459. BISON = os.path.join(GetThirdpartyBase(), 'win-util', 'bison.exe')
  460. elif LocateBinary('bison'):
  461. BISON = 'bison'
  462. else:
  463. # We don't strictly need it, so don't give an error
  464. return None
  465. return BISON
  466. FLEX = None
  467. def GetFlex():
  468. global FLEX
  469. if FLEX is not None:
  470. return FLEX
  471. win_util = os.path.join(GetThirdpartyBase(), 'win-util')
  472. if GetHost() == 'windows' and os.path.isdir(win_util):
  473. FLEX = GetThirdpartyBase() + "/win-util/flex.exe"
  474. elif LocateBinary('flex'):
  475. FLEX = 'flex'
  476. else:
  477. # We don't strictly need it, so don't give an error
  478. return None
  479. return FLEX
  480. ########################################################################
  481. ##
  482. ## LocateBinary
  483. ##
  484. ## This function searches the system PATH for the binary. Returns its
  485. ## full path when it is found, or None when it was not found.
  486. ##
  487. ########################################################################
  488. def LocateBinary(binary):
  489. if os.path.isfile(binary):
  490. return binary
  491. if "PATH" not in os.environ or os.environ["PATH"] == "":
  492. p = os.defpath
  493. else:
  494. p = os.environ["PATH"]
  495. pathList = p.split(os.pathsep)
  496. suffixes = ['']
  497. if GetHost() == 'windows':
  498. if not binary.lower().endswith('.exe') and not binary.lower().endswith('.bat'):
  499. # Append .exe if necessary
  500. suffixes = ['.exe', '.bat']
  501. # On Windows the current directory is always implicitly
  502. # searched before anything else on PATH.
  503. pathList = ['.'] + pathList
  504. for path in pathList:
  505. binpath = os.path.join(os.path.expanduser(path), binary)
  506. for suffix in suffixes:
  507. if os.access(binpath + suffix, os.X_OK):
  508. return os.path.abspath(os.path.realpath(binpath + suffix))
  509. return None
  510. ########################################################################
  511. ##
  512. ## Run a command.
  513. ##
  514. ########################################################################
  515. def oscmd(cmd, ignoreError = False, cwd=None):
  516. if VERBOSE:
  517. print(GetColor("blue") + cmd.split(" ", 1)[0] + " " + GetColor("magenta") + cmd.split(" ", 1)[1] + GetColor())
  518. sys.stdout.flush()
  519. if sys.platform == "win32":
  520. if cmd[0] == '"':
  521. exe = cmd[1 : cmd.index('"', 1)]
  522. else:
  523. exe = cmd.split()[0]
  524. exe_path = LocateBinary(exe)
  525. if exe_path is None:
  526. exit("Cannot find "+exe+" on search path")
  527. if cwd is not None:
  528. pwd = os.getcwd()
  529. os.chdir(cwd)
  530. res = os.spawnl(os.P_WAIT, exe_path, cmd)
  531. if cwd is not None:
  532. os.chdir(pwd)
  533. else:
  534. cmd = cmd.replace(';', '\\;')
  535. res = subprocess.call(cmd, cwd=cwd, shell=True)
  536. sig = res & 0x7F
  537. if (GetVerbose() and res != 0):
  538. print(ColorText("red", "Process exited with exit status %d and signal code %d" % ((res & 0xFF00) >> 8, sig)))
  539. if (sig == signal.SIGINT):
  540. exit("keyboard interrupt")
  541. # Don't ask me where the 35584 or 34304 come from...
  542. if (sig == signal.SIGSEGV or res == 35584 or res == 34304):
  543. if (LocateBinary("gdb") and GetVerbose() and GetHost() != "windows"):
  544. print(ColorText("red", "Received SIGSEGV, retrieving traceback..."))
  545. os.system("gdb -batch -ex 'handle SIG33 pass nostop noprint' -ex 'set pagination 0' -ex 'run' -ex 'bt full' -ex 'info registers' -ex 'thread apply all backtrace' -ex 'quit' --args %s < /dev/null" % cmd)
  546. else:
  547. print(ColorText("red", "Received SIGSEGV"))
  548. exit("")
  549. if res != 0 and not ignoreError:
  550. if "interrogate" in cmd.split(" ", 1)[0] and GetVerbose():
  551. print(ColorText("red", "Interrogate failed, retrieving debug output..."))
  552. sys.stdout.flush()
  553. verbose_cmd = cmd.split(" ", 1)[0] + " -vv " + cmd.split(" ", 1)[1]
  554. if sys.platform == "win32":
  555. os.spawnl(os.P_WAIT, exe_path, verbose_cmd)
  556. else:
  557. subprocess.call(verbose_cmd, shell=True)
  558. exit("The following command returned a non-zero value: " + str(cmd))
  559. return res
  560. ########################################################################
  561. ##
  562. ## GetDirectoryContents
  563. ##
  564. ########################################################################
  565. def GetDirectoryContents(dir, filters="*", skip=[]):
  566. if (type(filters)==str):
  567. filters = [filters]
  568. actual = {}
  569. files = os.listdir(dir)
  570. for filter in filters:
  571. for file in fnmatch.filter(files, filter):
  572. if (skip.count(file)==0) and (os.path.isfile(dir + "/" + file)):
  573. actual[file] = 1
  574. results = list(actual.keys())
  575. results.sort()
  576. return results
  577. def GetDirectorySize(dir):
  578. if not os.path.isdir(dir):
  579. return 0
  580. size = 0
  581. for (path, dirs, files) in os.walk(dir):
  582. for file in files:
  583. try:
  584. size += os.path.getsize(os.path.join(path, file))
  585. except: pass
  586. return size
  587. ########################################################################
  588. ##
  589. ## The Timestamp Cache
  590. ##
  591. ## The make utility is constantly fetching the timestamps of files.
  592. ## This can represent the bulk of the file accesses during the make
  593. ## process. The timestamp cache eliminates redundant checks.
  594. ##
  595. ########################################################################
  596. TIMESTAMPCACHE = {}
  597. def GetTimestamp(path):
  598. if path in TIMESTAMPCACHE:
  599. return TIMESTAMPCACHE[path]
  600. try: date = os.path.getmtime(path)
  601. except: date = 0
  602. TIMESTAMPCACHE[path] = date
  603. return date
  604. def ClearTimestamp(path):
  605. del TIMESTAMPCACHE[path]
  606. ########################################################################
  607. ##
  608. ## The Dependency cache.
  609. ##
  610. ## Makepanda's strategy for file dependencies is different from most
  611. ## make-utilities. Whenever a file is built, makepanda records
  612. ## that the file was built, and it records what the input files were,
  613. ## and what their dates were. Whenever a file is about to be built,
  614. ## panda compares the current list of input files and their dates,
  615. ## to the previous list of input files and their dates. If they match,
  616. ## there is no need to build the file.
  617. ##
  618. ########################################################################
  619. BUILTFROMCACHE = {}
  620. def JustBuilt(files, others):
  621. dates = {}
  622. for file in files:
  623. del TIMESTAMPCACHE[file]
  624. dates[file] = GetTimestamp(file)
  625. for file in others:
  626. dates[file] = GetTimestamp(file)
  627. key = tuple(files)
  628. BUILTFROMCACHE[key] = dates
  629. def NeedsBuild(files, others):
  630. dates = {}
  631. for file in files:
  632. dates[file] = GetTimestamp(file)
  633. if not os.path.exists(file):
  634. if DEBUG_DEPENDENCIES:
  635. print("rebuilding %s because it does not exist" % (file))
  636. return True
  637. for file in others:
  638. dates[file] = GetTimestamp(file)
  639. key = tuple(files)
  640. if key in BUILTFROMCACHE:
  641. cached = BUILTFROMCACHE[key]
  642. if cached == dates:
  643. return False
  644. elif DEBUG_DEPENDENCIES:
  645. print("rebuilding %s because:" % (key))
  646. for key in frozenset(cached.keys()) | frozenset(dates.keys()):
  647. if key not in cached:
  648. print(" new dependency: %s" % (key))
  649. elif key not in dates:
  650. print(" removed dependency: %s" % (key))
  651. elif cached[key] != dates[key]:
  652. print(" dependency changed: %s" % (key))
  653. if VERBOSE and frozenset(cached) != frozenset(dates):
  654. Warn("file dependencies changed:", files)
  655. return True
  656. ########################################################################
  657. ##
  658. ## The CXX include cache:
  659. ##
  660. ## The following routine scans a CXX file and returns a list of
  661. ## the include-directives inside that file. It's not recursive:
  662. ## it just returns the includes that are textually inside the
  663. ## file. If you need recursive dependencies, you need the higher-level
  664. ## routine CxxCalcDependencies, defined elsewhere.
  665. ##
  666. ## Since scanning a CXX file is slow, we cache the result. It records
  667. ## the date of the source file and the list of includes that it
  668. ## contains. It assumes that if the file date hasn't changed, that
  669. ## the list of include-statements inside the file has not changed
  670. ## either. Once again, this particular routine does not return
  671. ## recursive dependencies --- it only returns an explicit list of
  672. ## include statements that are textually inside the file. That
  673. ## is what the cache stores, as well.
  674. ##
  675. ########################################################################
  676. CXXINCLUDECACHE = {}
  677. global CxxIncludeRegex
  678. CxxIncludeRegex = re.compile('^[ \t]*[#][ \t]*include[ \t]+"([^"]+)"[ \t\r\n]*$')
  679. def CxxGetIncludes(path):
  680. date = GetTimestamp(path)
  681. if (path in CXXINCLUDECACHE):
  682. cached = CXXINCLUDECACHE[path]
  683. if (cached[0]==date): return cached[1]
  684. try: sfile = open(path, 'r')
  685. except:
  686. exit("Cannot open source file \""+path+"\" for reading.")
  687. include = []
  688. try:
  689. for line in sfile:
  690. match = CxxIncludeRegex.match(line,0)
  691. if (match):
  692. incname = match.group(1)
  693. include.append(incname)
  694. except:
  695. print("Failed to determine dependencies of \""+path+"\".")
  696. raise
  697. sfile.close()
  698. CXXINCLUDECACHE[path] = [date, include]
  699. return include
  700. JAVAIMPORTCACHE = {}
  701. global JavaImportRegex
  702. JavaImportRegex = re.compile('[ \t\r\n;]import[ \t]+([a-zA-Z][^;]+)[ \t\r\n]*;')
  703. def JavaGetImports(path):
  704. date = GetTimestamp(path)
  705. if path in JAVAIMPORTCACHE:
  706. cached = JAVAIMPORTCACHE[path]
  707. if cached[0] == date:
  708. return cached[1]
  709. try:
  710. source = open(path, 'r').read()
  711. except:
  712. exit("Cannot open source file \"" + path + "\" for reading.")
  713. imports = []
  714. try:
  715. for match in JavaImportRegex.finditer(source, 0):
  716. impname = match.group(1)
  717. imports.append(impname.strip())
  718. except:
  719. print("Failed to determine dependencies of \"" + path +"\".")
  720. raise
  721. JAVAIMPORTCACHE[path] = [date, imports]
  722. return imports
  723. ########################################################################
  724. ##
  725. ## SaveDependencyCache / LoadDependencyCache
  726. ##
  727. ## This actually saves both the dependency and cxx-include caches.
  728. ##
  729. ########################################################################
  730. DCACHE_VERSION = 2
  731. DCACHE_BACKED_UP = False
  732. def SaveDependencyCache():
  733. global DCACHE_BACKED_UP
  734. if not DCACHE_BACKED_UP:
  735. try:
  736. if (os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"))):
  737. os.rename(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),
  738. os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup"))
  739. except: pass
  740. DCACHE_BACKED_UP = True
  741. try:
  742. icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb')
  743. except:
  744. icache = None
  745. if icache is not None:
  746. print("Storing dependency cache.")
  747. pickle.dump(DCACHE_VERSION, icache, 0)
  748. pickle.dump(CXXINCLUDECACHE, icache, 2)
  749. pickle.dump(BUILTFROMCACHE, icache, 2)
  750. icache.close()
  751. def LoadDependencyCache():
  752. global CXXINCLUDECACHE
  753. global BUILTFROMCACHE
  754. try:
  755. icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"), 'rb')
  756. except:
  757. icache = None
  758. if icache is not None:
  759. ver = pickle.load(icache)
  760. if ver == DCACHE_VERSION:
  761. CXXINCLUDECACHE = pickle.load(icache)
  762. BUILTFROMCACHE = pickle.load(icache)
  763. icache.close()
  764. else:
  765. print("Cannot load dependency cache, version is too old!")
  766. ########################################################################
  767. ##
  768. ## CxxFindSource: given a source file name and a directory list,
  769. ## searches the directory list for the given source file. Returns
  770. ## the full pathname of the located file.
  771. ##
  772. ## CxxFindHeader: given a source file, an include directive, and a
  773. ## directory list, searches the directory list for the given header
  774. ## file. Returns the full pathname of the located file.
  775. ##
  776. ## Of course, CxxFindSource and CxxFindHeader cannot find a source
  777. ## file that has not been created yet. This can cause dependency
  778. ## problems. So the function CreateStubHeader can be used to create
  779. ## a file that CxxFindSource or CxxFindHeader can subsequently find.
  780. ##
  781. ########################################################################
  782. def CxxFindSource(name, ipath):
  783. for dir in ipath:
  784. if (dir == "."): full = name
  785. else: full = dir + "/" + name
  786. if GetTimestamp(full) > 0: return full
  787. exit("Could not find source file: "+name)
  788. def CxxFindHeader(srcfile, incfile, ipath):
  789. if (incfile.startswith(".")):
  790. last = srcfile.rfind("/")
  791. if (last < 0): exit("CxxFindHeader cannot handle this case #1")
  792. srcdir = srcfile[:last+1]
  793. while (incfile[:1]=="."):
  794. if (incfile[:2]=="./"):
  795. incfile = incfile[2:]
  796. elif (incfile[:3]=="../"):
  797. incfile = incfile[3:]
  798. last = srcdir[:-1].rfind("/")
  799. if (last < 0): exit("CxxFindHeader cannot handle this case #2")
  800. srcdir = srcdir[:last+1]
  801. else: exit("CxxFindHeader cannot handle this case #3")
  802. full = srcdir + incfile
  803. if GetTimestamp(full) > 0: return full
  804. return 0
  805. else:
  806. for dir in ipath:
  807. full = dir + "/" + incfile
  808. if GetTimestamp(full) > 0: return full
  809. return 0
  810. def JavaFindClasses(impspec, clspath):
  811. path = clspath + '/' + impspec.replace('.', '/') + '.class'
  812. if '*' in path:
  813. return glob.glob(path)
  814. else:
  815. return [path]
  816. ########################################################################
  817. ##
  818. ## CxxCalcDependencies(srcfile, ipath, ignore)
  819. ##
  820. ## Calculate the dependencies of a source file given a
  821. ## particular include-path. Any file in the list of files to
  822. ## ignore is not considered.
  823. ##
  824. ########################################################################
  825. global CxxIgnoreHeader
  826. global CxxDependencyCache
  827. CxxIgnoreHeader = {}
  828. CxxDependencyCache = {}
  829. def CxxCalcDependencies(srcfile, ipath, ignore):
  830. if (srcfile in CxxDependencyCache):
  831. return CxxDependencyCache[srcfile]
  832. if (ignore.count(srcfile)): return []
  833. dep = {}
  834. dep[srcfile] = 1
  835. includes = CxxGetIncludes(srcfile)
  836. for include in includes:
  837. header = CxxFindHeader(srcfile, include, ipath)
  838. if (header!=0):
  839. if (ignore.count(header)==0):
  840. hdeps = CxxCalcDependencies(header, ipath, [srcfile]+ignore)
  841. for x in hdeps: dep[x] = 1
  842. result = list(dep.keys())
  843. CxxDependencyCache[srcfile] = result
  844. return result
  845. global JavaDependencyCache
  846. JavaDependencyCache = {}
  847. def JavaCalcDependencies(srcfile, clspath):
  848. if srcfile in JavaDependencyCache:
  849. return JavaDependencyCache[srcfile]
  850. deps = set((srcfile,))
  851. JavaDependencyCache[srcfile] = deps
  852. imports = JavaGetImports(srcfile)
  853. for impspec in imports:
  854. for cls in JavaFindClasses(impspec, clspath):
  855. deps.add(cls)
  856. return deps
  857. ########################################################################
  858. ##
  859. ## Registry Key Handling
  860. ##
  861. ## Of course, these routines will fail if you call them on a
  862. ## non win32 platform. If you use them on a win64 platform, they
  863. ## will look in the win32 private hive first, then look in the
  864. ## win64 hive.
  865. ##
  866. ########################################################################
  867. if sys.platform == "win32":
  868. # Note: not supported on cygwin.
  869. if sys.version_info >= (3, 0):
  870. import winreg
  871. else:
  872. import _winreg as winreg
  873. def TryRegistryKey(path):
  874. try:
  875. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ)
  876. return key
  877. except: pass
  878. try:
  879. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | 256)
  880. return key
  881. except: pass
  882. return 0
  883. def ListRegistryKeys(path):
  884. result=[]
  885. index=0
  886. key = TryRegistryKey(path)
  887. if (key != 0):
  888. try:
  889. while (1):
  890. result.append(winreg.EnumKey(key, index))
  891. index = index + 1
  892. except: pass
  893. winreg.CloseKey(key)
  894. return result
  895. def ListRegistryValues(path):
  896. result = []
  897. index = 0
  898. key = TryRegistryKey(path)
  899. if (key != 0):
  900. try:
  901. while (1):
  902. result.append(winreg.EnumValue(key, index)[0])
  903. index = index + 1
  904. except: pass
  905. winreg.CloseKey(key)
  906. return result
  907. def GetRegistryKey(path, subkey, override64=True):
  908. if (host_64 and override64):
  909. path = path.replace("SOFTWARE\\", "SOFTWARE\\Wow6432Node\\")
  910. k1=0
  911. key = TryRegistryKey(path)
  912. if (key != 0):
  913. try:
  914. k1, k2 = winreg.QueryValueEx(key, subkey)
  915. except: pass
  916. winreg.CloseKey(key)
  917. return k1
  918. def GetProgramFiles():
  919. if ("PROGRAMFILES" in os.environ):
  920. return os.environ["PROGRAMFILES"]
  921. elif (os.path.isdir("C:\\Program Files")):
  922. return "C:\\Program Files"
  923. elif (os.path.isdir("D:\\Program Files")):
  924. return "D:\\Program Files"
  925. elif (os.path.isdir("E:\\Program Files")):
  926. return "E:\\Program Files"
  927. return 0
  928. def GetProgramFiles_x86():
  929. if ("ProgramFiles(x86)" in os.environ):
  930. return os.environ["ProgramFiles(x86)"]
  931. elif (os.path.isdir("C:\\Program Files (x86)")):
  932. return "C:\\Program Files (x86)"
  933. elif (os.path.isdir("D:\\Program Files (x86)")):
  934. return "D:\\Program Files (x86)"
  935. elif (os.path.isdir("E:\\Program Files (x86)")):
  936. return "E:\\Program Files (x86)"
  937. return GetProgramFiles()
  938. ########################################################################
  939. ##
  940. ## Parsing Compiler Option Lists
  941. ##
  942. ########################################################################
  943. def GetListOption(opts, prefix):
  944. res=[]
  945. for x in opts:
  946. if (x.startswith(prefix)):
  947. res.append(x[len(prefix):])
  948. return res
  949. def GetValueOption(opts, prefix):
  950. for x in opts:
  951. if (x.startswith(prefix)):
  952. return x[len(prefix):]
  953. return 0
  954. def GetOptimizeOption(opts):
  955. val = GetValueOption(opts, "OPT:")
  956. if (val == 0):
  957. return OPTIMIZE
  958. return val
  959. ########################################################################
  960. ##
  961. ## General File Manipulation
  962. ##
  963. ########################################################################
  964. def MakeDirectory(path, mode=None, recursive=False):
  965. if os.path.isdir(path):
  966. return
  967. if recursive:
  968. parent = os.path.dirname(path)
  969. if parent and not os.path.isdir(parent):
  970. MakeDirectory(parent, mode=mode, recursive=True)
  971. if mode is not None:
  972. os.mkdir(path, mode)
  973. else:
  974. os.mkdir(path)
  975. def ReadFile(wfile):
  976. try:
  977. srchandle = open(wfile, "r")
  978. data = srchandle.read()
  979. srchandle.close()
  980. return data
  981. except:
  982. ex = sys.exc_info()[1]
  983. exit("Cannot read %s: %s" % (wfile, ex))
  984. def ReadBinaryFile(wfile):
  985. try:
  986. srchandle = open(wfile, "rb")
  987. data = srchandle.read()
  988. srchandle.close()
  989. return data
  990. except:
  991. ex = sys.exc_info()[1]
  992. exit("Cannot read %s: %s" % (wfile, ex))
  993. def WriteFile(wfile, data, newline=None):
  994. if newline is not None:
  995. data = data.replace('\r\n', '\n')
  996. data = data.replace('\r', '\n')
  997. data = data.replace('\n', newline)
  998. try:
  999. if sys.version_info >= (3, 0):
  1000. dsthandle = open(wfile, "w", newline='')
  1001. else:
  1002. dsthandle = open(wfile, "w")
  1003. dsthandle.write(data)
  1004. dsthandle.close()
  1005. except:
  1006. ex = sys.exc_info()[1]
  1007. exit("Cannot write to %s: %s" % (wfile, ex))
  1008. def WriteBinaryFile(wfile, data):
  1009. try:
  1010. dsthandle = open(wfile, "wb")
  1011. dsthandle.write(data)
  1012. dsthandle.close()
  1013. except:
  1014. ex = sys.exc_info()[1]
  1015. exit("Cannot write to %s: %s" % (wfile, ex))
  1016. def ConditionalWriteFile(dest, data, newline=None):
  1017. if newline is not None:
  1018. data = data.replace('\r\n', '\n')
  1019. data = data.replace('\r', '\n')
  1020. data = data.replace('\n', newline)
  1021. try:
  1022. rfile = open(dest, 'r')
  1023. contents = rfile.read(-1)
  1024. rfile.close()
  1025. except:
  1026. contents = 0
  1027. if contents != data:
  1028. if VERBOSE:
  1029. print("Writing %s" % (dest))
  1030. sys.stdout.flush()
  1031. WriteFile(dest, data)
  1032. def DeleteVCS(dir):
  1033. if dir == "": dir = "."
  1034. for entry in os.listdir(dir):
  1035. subdir = os.path.join(dir, entry)
  1036. if (os.path.isdir(subdir)):
  1037. if entry in VCS_DIRS:
  1038. shutil.rmtree(subdir)
  1039. else:
  1040. DeleteVCS(subdir)
  1041. elif (os.path.isfile(subdir) and (entry in VCS_FILES or entry.startswith(".#"))):
  1042. os.remove(subdir)
  1043. def DeleteBuildFiles(dir):
  1044. if dir == "": dir = "."
  1045. for entry in os.listdir(dir):
  1046. subdir = os.path.join(dir, entry)
  1047. if (os.path.isfile(subdir) and os.path.splitext(subdir)[-1] in [".pp", ".moved"]):
  1048. os.remove(subdir)
  1049. elif (os.path.isdir(subdir)):
  1050. if (os.path.basename(subdir)[:3] == "Opt" and os.path.basename(subdir)[4] == "-"):
  1051. shutil.rmtree(subdir)
  1052. else:
  1053. DeleteBuildFiles(subdir)
  1054. def DeleteEmptyDirs(dir):
  1055. if dir == "": dir = "."
  1056. entries = os.listdir(dir)
  1057. if not entries:
  1058. os.rmdir(dir)
  1059. return
  1060. for entry in entries:
  1061. subdir = os.path.join(dir, entry)
  1062. if (os.path.isdir(subdir)):
  1063. if (not os.listdir(subdir)):
  1064. os.rmdir(subdir)
  1065. else:
  1066. DeleteEmptyDirs(subdir)
  1067. def CreateFile(file):
  1068. if (os.path.exists(file)==0):
  1069. WriteFile(file, "")
  1070. ########################################################################
  1071. #
  1072. # Create the panda build tree.
  1073. #
  1074. ########################################################################
  1075. def MakeBuildTree():
  1076. MakeDirectory(OUTPUTDIR)
  1077. MakeDirectory(OUTPUTDIR + "/bin")
  1078. MakeDirectory(OUTPUTDIR + "/lib")
  1079. MakeDirectory(OUTPUTDIR + "/tmp")
  1080. MakeDirectory(OUTPUTDIR + "/etc")
  1081. MakeDirectory(OUTPUTDIR + "/plugins")
  1082. MakeDirectory(OUTPUTDIR + "/include")
  1083. MakeDirectory(OUTPUTDIR + "/models")
  1084. MakeDirectory(OUTPUTDIR + "/models/audio")
  1085. MakeDirectory(OUTPUTDIR + "/models/audio/sfx")
  1086. MakeDirectory(OUTPUTDIR + "/models/icons")
  1087. MakeDirectory(OUTPUTDIR + "/models/maps")
  1088. MakeDirectory(OUTPUTDIR + "/models/misc")
  1089. MakeDirectory(OUTPUTDIR + "/models/gui")
  1090. MakeDirectory(OUTPUTDIR + "/pandac")
  1091. MakeDirectory(OUTPUTDIR + "/pandac/input")
  1092. MakeDirectory(OUTPUTDIR + "/panda3d")
  1093. if GetTarget() == 'darwin':
  1094. MakeDirectory(OUTPUTDIR + "/Frameworks")
  1095. elif GetTarget() == 'android':
  1096. MakeDirectory(OUTPUTDIR + "/classes")
  1097. ########################################################################
  1098. #
  1099. # Make sure that you are in the root of the panda tree.
  1100. #
  1101. ########################################################################
  1102. def CheckPandaSourceTree():
  1103. dir = os.getcwd()
  1104. if ((os.path.exists(os.path.join(dir, "makepanda/makepanda.py"))==0) or
  1105. (os.path.exists(os.path.join(dir, "dtool", "src", "dtoolbase", "dtoolbase.h"))==0) or
  1106. (os.path.exists(os.path.join(dir, "panda", "src", "pandabase", "pandabase.h"))==0)):
  1107. exit("Current directory is not the root of the panda tree.")
  1108. ########################################################################
  1109. ##
  1110. ## Thirdparty libraries paths
  1111. ##
  1112. ########################################################################
  1113. def GetThirdpartyBase():
  1114. """Returns the location of the 'thirdparty' directory.
  1115. Normally, this is simply the thirdparty directory relative
  1116. to the root of the source root, but if a MAKEPANDA_THIRDPARTY
  1117. environment variable was set, it is used as the location of the
  1118. thirdparty directory. This is useful when wanting to use a single
  1119. system-wide thirdparty directory, for instance on a build machine."""
  1120. global THIRDPARTYBASE
  1121. if (THIRDPARTYBASE != None):
  1122. return THIRDPARTYBASE
  1123. THIRDPARTYBASE = "thirdparty"
  1124. if "MAKEPANDA_THIRDPARTY" in os.environ:
  1125. THIRDPARTYBASE = os.environ["MAKEPANDA_THIRDPARTY"]
  1126. return THIRDPARTYBASE
  1127. def GetThirdpartyDir():
  1128. """Returns the thirdparty directory for the target platform,
  1129. ie. thirdparty/win-libs-vc10/. May return None in the future."""
  1130. global THIRDPARTYDIR
  1131. if THIRDPARTYDIR != None:
  1132. return THIRDPARTYDIR
  1133. base = GetThirdpartyBase()
  1134. target = GetTarget()
  1135. target_arch = GetTargetArch()
  1136. if (target == 'windows'):
  1137. vc = str(SDK["MSVC_VERSION"][0])
  1138. if target_arch == 'x64':
  1139. THIRDPARTYDIR = base + "/win-libs-vc" + vc + "-x64/"
  1140. else:
  1141. THIRDPARTYDIR = base + "/win-libs-vc" + vc + "/"
  1142. elif (target == 'darwin'):
  1143. # OSX thirdparty binaries are universal, where possible.
  1144. THIRDPARTYDIR = base + "/darwin-libs-a/"
  1145. elif (target == 'linux'):
  1146. if (target_arch.startswith("arm")):
  1147. THIRDPARTYDIR = base + "/linux-libs-arm/"
  1148. elif (target_arch in ("x86_64", "amd64")):
  1149. THIRDPARTYDIR = base + "/linux-libs-x64/"
  1150. else:
  1151. THIRDPARTYDIR = base + "/linux-libs-a/"
  1152. elif (target == 'freebsd'):
  1153. if (target_arch.startswith("arm")):
  1154. THIRDPARTYDIR = base + "/freebsd-libs-arm/"
  1155. elif (target_arch in ("x86_64", "amd64")):
  1156. THIRDPARTYDIR = base + "/freebsd-libs-x64/"
  1157. else:
  1158. THIRDPARTYDIR = base + "/freebsd-libs-a/"
  1159. elif (target == 'android'):
  1160. THIRDPARTYDIR = GetThirdpartyBase()+"/android-libs-%s/" % (GetTargetArch())
  1161. else:
  1162. Warn("Unsupported platform:", target)
  1163. return
  1164. if (GetVerbose()):
  1165. print("Using thirdparty directory: %s" % THIRDPARTYDIR)
  1166. return THIRDPARTYDIR
  1167. ########################################################################
  1168. ##
  1169. ## Gets or sets the output directory, by default "built".
  1170. ## Gets or sets the optimize level.
  1171. ## Gets or sets the verbose flag.
  1172. ##
  1173. ########################################################################
  1174. def GetOutputDir():
  1175. return OUTPUTDIR
  1176. def IsCustomOutputDir():
  1177. return CUSTOM_OUTPUTDIR
  1178. def SetOutputDir(outputdir):
  1179. global OUTPUTDIR, CUSTOM_OUTPUTDIR
  1180. OUTPUTDIR = outputdir
  1181. CUSTOM_OUTPUTDIR = True
  1182. def GetOptimize():
  1183. return int(OPTIMIZE)
  1184. def SetOptimize(optimize):
  1185. global OPTIMIZE
  1186. OPTIMIZE = optimize
  1187. def GetVerbose():
  1188. return VERBOSE
  1189. def SetVerbose(verbose):
  1190. global VERBOSE
  1191. VERBOSE = verbose
  1192. def SetDebugDependencies(dd = True):
  1193. global DEBUG_DEPENDENCIES
  1194. DEBUG_DEPENDENCIES = dd
  1195. def GetLinkAllStatic():
  1196. return LINK_ALL_STATIC
  1197. def SetLinkAllStatic(val = True):
  1198. global LINK_ALL_STATIC
  1199. LINK_ALL_STATIC = val
  1200. def UnsetLinkAllStatic():
  1201. global LINK_ALL_STATIC
  1202. LINK_ALL_STATIC = False
  1203. ########################################################################
  1204. ##
  1205. ## Package Selection
  1206. ##
  1207. ## This facility enables makepanda to keep a list of packages selected
  1208. ## by the user for inclusion or omission.
  1209. ##
  1210. ########################################################################
  1211. PKG_LIST_ALL = []
  1212. PKG_LIST_OMIT = {}
  1213. PKG_LIST_CUSTOM = set()
  1214. def PkgListSet(pkgs):
  1215. global PKG_LIST_ALL
  1216. global PKG_LIST_OMIT
  1217. PKG_LIST_ALL=pkgs
  1218. PKG_LIST_OMIT={}
  1219. PkgEnableAll()
  1220. def PkgListGet():
  1221. return PKG_LIST_ALL
  1222. def PkgEnableAll():
  1223. for x in PKG_LIST_ALL:
  1224. PKG_LIST_OMIT[x] = 0
  1225. def PkgDisableAll():
  1226. for x in PKG_LIST_ALL:
  1227. PKG_LIST_OMIT[x] = 1
  1228. def PkgEnable(pkg):
  1229. PKG_LIST_OMIT[pkg] = 0
  1230. def PkgDisable(pkg):
  1231. PKG_LIST_OMIT[pkg] = 1
  1232. def PkgSetCustomLocation(pkg):
  1233. PKG_LIST_CUSTOM.add(pkg)
  1234. def PkgHasCustomLocation(pkg):
  1235. return pkg in PKG_LIST_CUSTOM
  1236. def PkgSkip(pkg):
  1237. return PKG_LIST_OMIT[pkg]
  1238. def PkgSelected(pkglist, pkg):
  1239. if (pkglist.count(pkg)==0): return 0
  1240. if (PKG_LIST_OMIT[pkg]): return 0
  1241. return 1
  1242. ########################################################################
  1243. ##
  1244. ## DTOOL/PRC Option value override
  1245. ##
  1246. ## This facility enables makepanda to keep a list of parameters
  1247. ## overriden by the command line.
  1248. ##
  1249. ########################################################################
  1250. OVERRIDES_LIST={}
  1251. def AddOverride(spec):
  1252. if (spec.find("=")==-1):return
  1253. pair = spec.split("=",1)
  1254. OVERRIDES_LIST[pair[0]] = pair[1]
  1255. def OverrideValue(parameter, value):
  1256. if parameter in OVERRIDES_LIST:
  1257. print("Overriding value of key \"" + parameter + "\" with value \"" + OVERRIDES_LIST[parameter] + "\"")
  1258. return OVERRIDES_LIST[parameter]
  1259. else:
  1260. return value
  1261. ########################################################################
  1262. ##
  1263. ## These functions are for libraries which use pkg-config.
  1264. ##
  1265. ########################################################################
  1266. def PkgConfigHavePkg(pkgname, tool = "pkg-config"):
  1267. """Returns a bool whether the pkg-config package is installed."""
  1268. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1269. return False
  1270. if (tool == "pkg-config"):
  1271. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --modversion " + pkgname)
  1272. else:
  1273. return bool(LocateBinary(tool) != None)
  1274. result = handle.read().strip()
  1275. returnval = handle.close()
  1276. if returnval != None and returnval != 0:
  1277. return False
  1278. return bool(len(result) > 0)
  1279. def PkgConfigGetLibs(pkgname, tool = "pkg-config"):
  1280. """Returns a list of libs for the package, prefixed by -l."""
  1281. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1282. return []
  1283. if (tool == "pkg-config"):
  1284. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-l " + pkgname)
  1285. elif (tool == "fltk-config"):
  1286. handle = os.popen(LocateBinary("fltk-config") + " --ldstaticflags")
  1287. else:
  1288. handle = os.popen(LocateBinary(tool) + " --libs")
  1289. result = handle.read().strip()
  1290. handle.close()
  1291. libs = []
  1292. # Walk through the result arguments carefully. Look for -lname as
  1293. # well as -framework name.
  1294. r = result.split(' ')
  1295. ri = 0
  1296. while ri < len(r):
  1297. l = r[ri]
  1298. if l.startswith("-l") or l.startswith("/"):
  1299. libs.append(l)
  1300. elif l == '-framework':
  1301. libs.append(l)
  1302. ri += 1
  1303. libs.append(r[ri])
  1304. ri += 1
  1305. return libs
  1306. def PkgConfigGetIncDirs(pkgname, tool = "pkg-config"):
  1307. """Returns a list of includes for the package, NOT prefixed by -I."""
  1308. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1309. return []
  1310. if (tool == "pkg-config"):
  1311. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags-only-I " + pkgname)
  1312. else:
  1313. handle = os.popen(LocateBinary(tool) + " --cflags")
  1314. result = handle.read().strip()
  1315. if len(result) == 0: return []
  1316. handle.close()
  1317. dirs = []
  1318. for opt in result.split(" "):
  1319. if (opt.startswith("-I")):
  1320. inc_dir = opt.replace("-I", "").replace("\"", "").strip()
  1321. # Hack for ODE, otherwise -S/usr/include gets added to interrogate
  1322. if inc_dir != '/usr/include' and inc_dir != '/usr/include/':
  1323. dirs.append(inc_dir)
  1324. return dirs
  1325. def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"):
  1326. """Returns a list of library paths for the package, NOT prefixed by -L."""
  1327. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1328. return []
  1329. if (tool == "pkg-config"):
  1330. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname)
  1331. elif (tool == "wx-config" or tool == "ode-config"):
  1332. return []
  1333. else:
  1334. handle = os.popen(LocateBinary(tool) + " --ldflags")
  1335. result = handle.read().strip()
  1336. handle.close()
  1337. if len(result) == 0: return []
  1338. libs = []
  1339. for l in result.split(" "):
  1340. if (l.startswith("-L")):
  1341. libs.append(l.replace("-L", "").replace("\"", "").strip())
  1342. return libs
  1343. def PkgConfigGetDefSymbols(pkgname, tool = "pkg-config"):
  1344. """Returns a dictionary of preprocessor definitions."""
  1345. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1346. return []
  1347. if (tool == "pkg-config"):
  1348. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags " + pkgname)
  1349. else:
  1350. handle = os.popen(LocateBinary(tool) + " --cflags")
  1351. result = handle.read().strip()
  1352. handle.close()
  1353. if len(result) == 0: return {}
  1354. defs = {}
  1355. for l in result.split(" "):
  1356. if (l.startswith("-D")):
  1357. d = l.replace("-D", "").replace("\"", "").strip().split("=")
  1358. if d[0] in ('NDEBUG', '_DEBUG'):
  1359. # Setting one of these flags by accident could cause serious harm.
  1360. if GetVerbose():
  1361. print("Ignoring %s flag provided by %s" % (l, tool))
  1362. elif len(d) == 1:
  1363. defs[d[0]] = ""
  1364. else:
  1365. defs[d[0]] = d[1]
  1366. return defs
  1367. def PkgConfigEnable(opt, pkgname, tool = "pkg-config"):
  1368. """Adds the libraries and includes to IncDirectory, LibName and LibDirectory."""
  1369. for i in PkgConfigGetIncDirs(pkgname, tool):
  1370. IncDirectory(opt, i)
  1371. for i in PkgConfigGetLibDirs(pkgname, tool):
  1372. LibDirectory(opt, i)
  1373. for i in PkgConfigGetLibs(pkgname, tool):
  1374. LibName(opt, i)
  1375. for i, j in PkgConfigGetDefSymbols(pkgname, tool).items():
  1376. DefSymbol(opt, i, j)
  1377. def LocateLibrary(lib, lpath=[], prefer_static=False):
  1378. """Searches for the library in the search path, returning its path if found,
  1379. or None if it was not found."""
  1380. target = GetTarget()
  1381. if prefer_static and target != 'windows':
  1382. for dir in lpath:
  1383. if os.path.isfile(os.path.join(dir, 'lib%s.a' % lib)):
  1384. return os.path.join(dir, 'lib%s.a' % lib)
  1385. for dir in lpath:
  1386. if target == 'darwin' and os.path.isfile(os.path.join(dir, 'lib%s.dylib' % lib)):
  1387. return os.path.join(dir, 'lib%s.dylib' % lib)
  1388. elif target != 'darwin' and os.path.isfile(os.path.join(dir, 'lib%s.so' % lib)):
  1389. return os.path.join(dir, 'lib%s.so' % lib)
  1390. elif os.path.isfile(os.path.join(dir, 'lib%s.a' % lib)):
  1391. return os.path.join(dir, 'lib%s.a' % lib)
  1392. return None
  1393. def SystemLibraryExists(lib):
  1394. result = LocateLibrary(lib, SYS_LIB_DIRS)
  1395. if result is not None:
  1396. return True
  1397. if GetHost() == "android" and GetTarget() == "android":
  1398. return ('lib%s.so' % lib) in ANDROID_SYS_LIBS
  1399. return False
  1400. def ChooseLib(libs, thirdparty=None):
  1401. """ Chooses a library from the parameters, in order of preference. Returns the first if none of them were found. """
  1402. lpath = []
  1403. if thirdparty is not None:
  1404. lpath.append(os.path.join(GetThirdpartyDir(), thirdparty.lower(), "lib"))
  1405. lpath += SYS_LIB_DIRS
  1406. for l in libs:
  1407. libname = l
  1408. if l.startswith("lib"):
  1409. libname = l[3:]
  1410. if LocateLibrary(libname, lpath):
  1411. return libname
  1412. if len(libs) > 0:
  1413. if VERBOSE:
  1414. print(ColorText("cyan", "Couldn't find any of the libraries " + ", ".join(libs)))
  1415. return libs[0]
  1416. def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None, framework = None, target_pkg = None, tool = "pkg-config", thirdparty_dir = None):
  1417. global PKG_LIST_ALL
  1418. if (pkg in PkgListGet() and PkgSkip(pkg)):
  1419. return
  1420. if (target_pkg == "" or target_pkg == None):
  1421. target_pkg = pkg
  1422. if (pkgconfig == ""):
  1423. pkgconfig = None
  1424. if (framework == ""):
  1425. framework = None
  1426. if (libs == None or libs == ""):
  1427. libs = ()
  1428. elif (isinstance(libs, str)):
  1429. libs = (libs, )
  1430. if (incs == None or incs == ""):
  1431. incs = ()
  1432. elif (isinstance(incs, str)):
  1433. incs = (incs, )
  1434. if (defs == None or defs == "" or len(defs) == 0):
  1435. defs = {}
  1436. elif (isinstance(incs, str)):
  1437. defs = {defs : ""}
  1438. elif (isinstance(incs, list) or isinstance(incs, tuple) or isinstance(incs, set)):
  1439. olddefs = defs
  1440. defs = {}
  1441. for d in olddefs:
  1442. defs[d] = ""
  1443. custom_loc = PkgHasCustomLocation(pkg)
  1444. # Determine the location of the thirdparty directory.
  1445. if not thirdparty_dir:
  1446. thirdparty_dir = pkg.lower()
  1447. pkg_dir = os.path.join(GetThirdpartyDir(), thirdparty_dir)
  1448. # First check if the library can be found in the thirdparty directory.
  1449. if not custom_loc and os.path.isdir(pkg_dir):
  1450. if framework and os.path.isdir(os.path.join(pkg_dir, framework + ".framework")):
  1451. FrameworkDirectory(target_pkg, pkg_dir)
  1452. LibName(target_pkg, "-framework " + framework)
  1453. return
  1454. if os.path.isdir(os.path.join(pkg_dir, "include")):
  1455. IncDirectory(target_pkg, os.path.join(pkg_dir, "include"))
  1456. # Handle cases like freetype2 where the include dir is a subdir under "include"
  1457. for i in incs:
  1458. if os.path.isdir(os.path.join(pkg_dir, "include", i)):
  1459. IncDirectory(target_pkg, os.path.join(pkg_dir, "include", i))
  1460. lpath = [os.path.join(pkg_dir, "lib")]
  1461. if not PkgSkip("PYTHON"):
  1462. py_lib_dir = os.path.join(pkg_dir, "lib", SDK["PYTHONVERSION"])
  1463. if os.path.isdir(py_lib_dir):
  1464. lpath.append(py_lib_dir)
  1465. # TODO: check for a .pc file in the lib/pkgconfig/ dir
  1466. if (tool != None and os.path.isfile(os.path.join(pkg_dir, "bin", tool))):
  1467. tool = os.path.join(pkg_dir, "bin", tool)
  1468. for i in PkgConfigGetLibs(None, tool):
  1469. if i.startswith('-l'):
  1470. # To make sure we don't pick up the system copy, write out
  1471. # the full path instead.
  1472. libname = i[2:]
  1473. location = LocateLibrary(libname, lpath, prefer_static=True)
  1474. if location is not None:
  1475. LibName(target_pkg, location)
  1476. else:
  1477. print(GetColor("cyan") + "Couldn't find library lib" + libname + " in thirdparty directory " + pkg.lower() + GetColor())
  1478. LibName(target_pkg, i)
  1479. else:
  1480. LibName(target_pkg, i)
  1481. for i, j in PkgConfigGetDefSymbols(None, tool).items():
  1482. DefSymbol(target_pkg, i, j)
  1483. return
  1484. # Now search for the libraries in the package's lib directories.
  1485. for l in libs:
  1486. libname = l
  1487. if l.startswith("lib"):
  1488. libname = l[3:]
  1489. location = LocateLibrary(libname, lpath, prefer_static=True)
  1490. if location is not None:
  1491. # If it's a .so or .dylib we may have changed it and copied it to the built/lib dir.
  1492. if location.endswith('.so') or location.endswith('.dylib'):
  1493. location = os.path.join(GetOutputDir(), "lib", os.path.basename(location))
  1494. LibName(target_pkg, location)
  1495. else:
  1496. # This is for backward compatibility - in the thirdparty dir,
  1497. # we kept some libs with "panda" prefix, like libpandatiff.
  1498. location = LocateLibrary("panda" + libname, lpath, prefer_static=True)
  1499. if location is not None:
  1500. if location.endswith('.so') or location.endswith('.dylib'):
  1501. location = os.path.join(GetOutputDir(), "lib", os.path.basename(location))
  1502. LibName(target_pkg, location)
  1503. else:
  1504. print(GetColor("cyan") + "Couldn't find library lib" + libname + " in thirdparty directory " + thirdparty_dir + GetColor())
  1505. for d, v in defs.values():
  1506. DefSymbol(target_pkg, d, v)
  1507. return
  1508. elif not custom_loc and GetHost() == "darwin" and framework != None:
  1509. prefix = SDK["MACOSX"]
  1510. if (os.path.isdir(prefix + "/Library/Frameworks/%s.framework" % framework) or
  1511. os.path.isdir(prefix + "/System/Library/Frameworks/%s.framework" % framework) or
  1512. os.path.isdir(prefix + "/Developer/Library/Frameworks/%s.framework" % framework) or
  1513. os.path.isdir(prefix + "/Users/%s/System/Library/Frameworks/%s.framework" % (getpass.getuser(), framework))):
  1514. LibName(target_pkg, "-framework " + framework)
  1515. for d, v in defs.values():
  1516. DefSymbol(target_pkg, d, v)
  1517. return
  1518. elif VERBOSE:
  1519. print(ColorText("cyan", "Couldn't find the framework %s" % (framework)))
  1520. elif not custom_loc and LocateBinary(tool) != None and (tool != "pkg-config" or pkgconfig != None):
  1521. if (isinstance(pkgconfig, str) or tool != "pkg-config"):
  1522. if (PkgConfigHavePkg(pkgconfig, tool)):
  1523. return PkgConfigEnable(target_pkg, pkgconfig, tool)
  1524. else:
  1525. have_all_pkgs = True
  1526. for pc in pkgconfig:
  1527. if (PkgConfigHavePkg(pc, tool)):
  1528. PkgConfigEnable(target_pkg, pc, tool)
  1529. else:
  1530. have_all_pkgs = False
  1531. if (have_all_pkgs):
  1532. return
  1533. if not custom_loc and pkgconfig is not None and not libs:
  1534. # pkg-config is all we can do, abort if it wasn't found.
  1535. if pkg in PkgListGet():
  1536. Warn("Could not locate pkg-config package %s, excluding from build" % (pkgconfig))
  1537. PkgDisable(pkg)
  1538. else:
  1539. Error("Could not locate pkg-config package %s, aborting build" % (pkgconfig))
  1540. else:
  1541. # Okay, our pkg-config attempts failed. Let's try locating the libs by ourselves.
  1542. have_pkg = True
  1543. for l in libs:
  1544. libname = l
  1545. if l.startswith("lib"):
  1546. libname = l[3:]
  1547. if custom_loc:
  1548. # Try searching in the package's LibDirectories.
  1549. lpath = [dir for ppkg, dir in LIBDIRECTORIES if pkg == ppkg]
  1550. location = LocateLibrary(libname, lpath)
  1551. if location is not None:
  1552. LibName(target_pkg, location)
  1553. else:
  1554. have_pkg = False
  1555. print(GetColor("cyan") + "Couldn't find library lib" + libname + GetColor())
  1556. elif SystemLibraryExists(libname):
  1557. # It exists in a system library directory.
  1558. LibName(target_pkg, "-l" + libname)
  1559. else:
  1560. # Try searching in the package's LibDirectories.
  1561. lpath = [dir for ppkg, dir in LIBDIRECTORIES if pkg == ppkg or ppkg == "ALWAYS"]
  1562. location = LocateLibrary(libname, lpath)
  1563. if location is not None:
  1564. LibName(target_pkg, "-l" + libname)
  1565. else:
  1566. have_pkg = False
  1567. if VERBOSE or custom_loc:
  1568. print(GetColor("cyan") + "Couldn't find library lib" + libname + GetColor())
  1569. # Determine which include directories to look in.
  1570. incdirs = []
  1571. if not custom_loc:
  1572. incdirs += list(SYS_INC_DIRS)
  1573. for ppkg, pdir in INCDIRECTORIES[:]:
  1574. if pkg == ppkg or (ppkg == "ALWAYS" and not custom_loc):
  1575. incdirs.append(pdir)
  1576. if custom_loc and pkg != target_pkg:
  1577. IncDirectory(target_pkg, pdir)
  1578. # The incs list contains both subdirectories to explicitly add to
  1579. # the include path and header files to check the existence of.
  1580. for i in incs:
  1581. incdir = None
  1582. for dir in incdirs:
  1583. if len(glob.glob(os.path.join(dir, i))) > 0:
  1584. incdir = sorted(glob.glob(os.path.join(dir, i)))[-1]
  1585. # Note: It's possible to specify a file instead of a dir, for the sake of checking if it exists.
  1586. if incdir is None and (i.endswith('/Dense') or i.endswith(".h")):
  1587. have_pkg = False
  1588. if VERBOSE or custom_loc:
  1589. print(GetColor("cyan") + "Couldn't find header file " + i + GetColor())
  1590. if incdir is not None and os.path.isdir(incdir):
  1591. IncDirectory(target_pkg, incdir)
  1592. if not have_pkg:
  1593. if custom_loc:
  1594. Error("Could not locate thirdparty package %s in specified directory, aborting build" % (pkg.lower()))
  1595. elif pkg in PkgListGet():
  1596. Warn("Could not locate thirdparty package %s, excluding from build" % (pkg.lower()))
  1597. PkgDisable(pkg)
  1598. else:
  1599. Error("Could not locate thirdparty package %s, aborting build" % (pkg.lower()))
  1600. ########################################################################
  1601. ##
  1602. ## SDK Location
  1603. ##
  1604. ## This section is concerned with locating the install directories
  1605. ## for various third-party packages. The results are stored in the
  1606. ## SDK table.
  1607. ##
  1608. ## Microsoft keeps changing the &*#$*& registry key for the DirectX SDK.
  1609. ## The only way to reliably find it is to search through the installer's
  1610. ## uninstall-directories, look in each one, and see if it contains the
  1611. ## relevant files.
  1612. ##
  1613. ########################################################################
  1614. SDK = {}
  1615. def GetSdkDir(sdkname, sdkkey = None):
  1616. # Returns the default SDK directory. If it exists,
  1617. # and sdkkey is not None, it is put in SDK[sdkkey].
  1618. # Note: return value may not be an existing path.
  1619. sdkbase = "sdks"
  1620. if "MAKEPANDA_SDKS" in os.environ:
  1621. sdkbase = os.environ["MAKEPANDA_SDKS"]
  1622. sdir = sdkbase[:]
  1623. target = GetTarget()
  1624. target_arch = GetTargetArch()
  1625. if target == 'windows':
  1626. if target_arch == 'x64':
  1627. sdir += "/win64"
  1628. else:
  1629. sdir += "/win32"
  1630. elif target == 'linux':
  1631. sdir += "/linux"
  1632. sdir += platform.architecture()[0][:2]
  1633. elif target == 'darwin':
  1634. sdir += "/macosx"
  1635. sdir += "/" + sdkname
  1636. # If it does not exist, try the old location.
  1637. if (not os.path.isdir(sdir)):
  1638. sdir = sdkbase + "/" + sdir
  1639. if (target == 'linux'):
  1640. sdir += "-linux"
  1641. sdir += platform.architecture()[0][:2]
  1642. elif (target == "darwin"):
  1643. sdir += "-osx"
  1644. if (sdkkey and os.path.isdir(sdir)):
  1645. SDK[sdkkey] = sdir
  1646. return sdir
  1647. def SdkLocateDirectX( strMode = 'default' ):
  1648. if (GetHost() != "windows"): return
  1649. if strMode == 'default':
  1650. GetSdkDir("directx9", "DX9")
  1651. if ("DX9" not in SDK):
  1652. strMode = 'latest'
  1653. if strMode == 'latest':
  1654. ## We first try to locate the August SDK in 64 bits, then 32.
  1655. if ("DX9" not in SDK):
  1656. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1657. if (dir != 0):
  1658. print("Using DirectX SDK June 2010")
  1659. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1660. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1661. if ("DX9" not in SDK):
  1662. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1663. if (dir != 0):
  1664. print("Using DirectX SDK June 2010")
  1665. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1666. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1667. if ("DX9" not in SDK):
  1668. dir = "C:/Program Files (x86)/Microsoft DirectX SDK (June 2010)"
  1669. if os.path.isdir(dir):
  1670. print("Using DirectX SDK June 2010")
  1671. SDK["DX9"] = dir
  1672. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1673. if ("DX9" not in SDK):
  1674. dir = "C:/Program Files/Microsoft DirectX SDK (June 2010)"
  1675. if os.path.isdir(dir):
  1676. print("Using DirectX SDK June 2010")
  1677. SDK["DX9"] = dir
  1678. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1679. if ("DX9" not in SDK):
  1680. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1681. if (dir != 0):
  1682. print("Using DirectX SDK Aug 2009")
  1683. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1684. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1685. if ("DX9" not in SDK):
  1686. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1687. if (dir != 0):
  1688. print("Using DirectX SDK Aug 2009")
  1689. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1690. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1691. if ("DX9" not in SDK):
  1692. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1693. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1694. if (dir != 0):
  1695. print("Using DirectX SDK March 2009")
  1696. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1697. archStr = GetTargetArch()
  1698. if ("DX9" not in SDK):
  1699. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1700. for subdir in ListRegistryKeys(uninstaller):
  1701. if (subdir[0]=="{"):
  1702. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1703. if (dir != 0):
  1704. if (("DX9" not in SDK) and
  1705. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1706. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1707. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1708. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1709. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1710. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1711. if ("DX9" not in SDK):
  1712. return
  1713. elif strMode == 'jun2010':
  1714. if ("DX9" not in SDK):
  1715. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1716. if (dir != 0):
  1717. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1718. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1719. if ("DX9" not in SDK):
  1720. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1721. if (dir != 0):
  1722. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1723. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1724. if ("DX9" not in SDK):
  1725. dir = "C:/Program Files (x86)/Microsoft DirectX SDK (June 2010)"
  1726. if os.path.isdir(dir):
  1727. SDK["DX9"] = dir
  1728. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1729. if ("DX9" not in SDK):
  1730. dir = "C:/Program Files/Microsoft DirectX SDK (June 2010)"
  1731. if os.path.isdir(dir):
  1732. SDK["DX9"] = dir
  1733. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1734. if ("DX9" not in SDK):
  1735. exit("Couldn't find DirectX June2010 SDK")
  1736. else:
  1737. print("Found DirectX SDK June 2010")
  1738. elif strMode == 'aug2009':
  1739. if ("DX9" not in SDK):
  1740. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1741. if (dir != 0):
  1742. print("Found DirectX SDK Aug 2009")
  1743. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1744. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1745. if ("DX9" not in SDK):
  1746. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1747. if (dir != 0):
  1748. print("Found DirectX SDK Aug 2009")
  1749. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1750. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1751. if ("DX9" not in SDK):
  1752. exit("Couldn't find DirectX Aug 2009 SDK")
  1753. elif strMode == 'mar2009':
  1754. if ("DX9" not in SDK):
  1755. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1756. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1757. if (dir != 0):
  1758. print("Found DirectX SDK March 2009")
  1759. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1760. if ("DX9" not in SDK):
  1761. exit("Couldn't find DirectX March 2009 SDK")
  1762. elif strMode == 'aug2006':
  1763. archStr = GetTargetArch()
  1764. if ("DX9" not in SDK):
  1765. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1766. for subdir in ListRegistryKeys(uninstaller):
  1767. if (subdir[0]=="{"):
  1768. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1769. if (dir != 0):
  1770. if (("DX9" not in SDK) and
  1771. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1772. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1773. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1774. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1775. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1776. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1777. if ("DX9" not in SDK):
  1778. exit("Couldn't find a DirectX Aug 2006 SDK")
  1779. if ("DX9" in SDK):
  1780. SDK["DIRECTCAM"] = SDK["DX9"]
  1781. def SdkLocateMaya():
  1782. for (ver, key) in MAYAVERSIONINFO:
  1783. if (PkgSkip(ver)==0 and ver not in SDK):
  1784. GetSdkDir(ver.lower().replace("x",""), ver)
  1785. if (not ver in SDK):
  1786. if (GetHost() == "windows"):
  1787. for dev in ["Alias|Wavefront","Alias","Autodesk"]:
  1788. fullkey="SOFTWARE\\"+dev+"\\Maya\\"+key+"\\Setup\\InstallPath"
  1789. res = GetRegistryKey(fullkey, "MAYA_INSTALL_LOCATION", override64=False)
  1790. if (res != 0):
  1791. res = res.replace("\\", "/").rstrip("/")
  1792. SDK[ver] = res
  1793. elif (GetHost() == "darwin"):
  1794. ddir = "/Applications/Autodesk/maya"+key
  1795. if (os.path.isdir(ddir)): SDK[ver] = ddir
  1796. else:
  1797. if (GetTargetArch() in ("x86_64", "amd64")):
  1798. ddir1 = "/usr/autodesk/maya"+key+"-x64"
  1799. ddir2 = "/usr/aw/maya"+key+"-x64"
  1800. else:
  1801. ddir1 = "/usr/autodesk/maya"+key
  1802. ddir2 = "/usr/aw/maya"+key
  1803. if (os.path.isdir(ddir1)): SDK[ver] = ddir1
  1804. elif (os.path.isdir(ddir2)): SDK[ver] = ddir2
  1805. def SdkLocateMax():
  1806. if (GetHost() != "windows"): return
  1807. for version,key1,key2,subdir in MAXVERSIONINFO:
  1808. if (PkgSkip(version)==0):
  1809. if (version not in SDK):
  1810. GetSdkDir("maxsdk"+version.lower()[3:], version)
  1811. GetSdkDir("maxsdk"+version.lower()[3:], version+"CS")
  1812. if (not version in SDK):
  1813. top = GetRegistryKey(key1,key2)
  1814. if (top != 0):
  1815. SDK[version] = top + "maxsdk"
  1816. if (os.path.isdir(top + "\\" + subdir)!=0):
  1817. SDK[version+"CS"] = top + subdir
  1818. def SdkLocatePython(prefer_thirdparty_python=False):
  1819. if PkgSkip("PYTHON"):
  1820. # We're not compiling with Python support. We still need to set this
  1821. # in case we want to run any scripts that use Python, though.
  1822. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1823. return
  1824. abiflags = getattr(sys, 'abiflags', '')
  1825. if GetTarget() == 'windows':
  1826. sdkdir = GetThirdpartyBase() + "/win-python"
  1827. if sys.version_info >= (3, 0):
  1828. # Python 3 build...
  1829. sdkdir += "%d.%d" % sys.version_info[:2]
  1830. if GetOptimize() <= 2:
  1831. sdkdir += "-dbg"
  1832. if GetTargetArch() == 'x64':
  1833. sdkdir += "-x64"
  1834. SDK["PYTHON"] = sdkdir
  1835. SDK["PYTHONEXEC"] = SDK["PYTHON"].replace('\\', '/') + "/python"
  1836. if (GetOptimize() <= 2):
  1837. SDK["PYTHONEXEC"] += "_d.exe"
  1838. else:
  1839. SDK["PYTHONEXEC"] += ".exe"
  1840. if (not os.path.isfile(SDK["PYTHONEXEC"])):
  1841. exit("Could not find %s!" % SDK["PYTHONEXEC"])
  1842. # Determine which version it is by checking which dll is in the directory.
  1843. if (GetOptimize() <= 2):
  1844. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9]_d.dll")
  1845. else:
  1846. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9].dll")
  1847. if len(py_dlls) == 0:
  1848. exit("Could not find the Python dll in %s." % (SDK["PYTHON"]))
  1849. elif len(py_dlls) > 1:
  1850. exit("Found multiple Python dlls in %s." % (SDK["PYTHON"]))
  1851. py_dll = os.path.basename(py_dlls[0])
  1852. ver = py_dll[6] + "." + py_dll[7]
  1853. SDK["PYTHONVERSION"] = "python" + ver
  1854. os.environ["PYTHONHOME"] = SDK["PYTHON"]
  1855. if sys.version[:3] != ver:
  1856. Warn("running makepanda with Python %s, but building Panda3D with Python %s." % (sys.version[:3], ver))
  1857. elif CrossCompiling() or (prefer_thirdparty_python and os.path.isdir(os.path.join(GetThirdpartyDir(), "python"))):
  1858. tp_python = os.path.join(GetThirdpartyDir(), "python")
  1859. if GetTarget() == 'darwin':
  1860. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].dylib")
  1861. else:
  1862. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].so")
  1863. if len(py_libs) == 0:
  1864. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].a")
  1865. if len(py_libs) == 0:
  1866. exit("Could not find the Python library in %s." % (tp_python))
  1867. elif len(py_libs) > 1:
  1868. exit("Found multiple Python libraries in %s." % (tp_python))
  1869. py_lib = os.path.basename(py_libs[0])
  1870. SDK["PYTHONVERSION"] = "python" + py_lib[9] + "." + py_lib[11]
  1871. SDK["PYTHONEXEC"] = tp_python + "/bin/" + SDK["PYTHONVERSION"]
  1872. SDK["PYTHON"] = tp_python + "/include/" + SDK["PYTHONVERSION"]
  1873. elif GetTarget() == 'darwin':
  1874. # On macOS, search for the Python framework directory matching the
  1875. # version number of our current Python version.
  1876. sysroot = SDK.get("MACOSX", "")
  1877. version = sysconfig.get_python_version()
  1878. py_fwx = "{0}/System/Library/Frameworks/Python.framework/Versions/{1}".format(sysroot, version)
  1879. if not os.path.exists(py_fwx):
  1880. # Fall back to looking on the system.
  1881. py_fwx = "/Library/Frameworks/Python.framework/Versions/" + version
  1882. if not os.path.exists(py_fwx):
  1883. exit("Could not locate Python installation at %s" % (py_fwx))
  1884. SDK["PYTHON"] = py_fwx + "/Headers"
  1885. SDK["PYTHONVERSION"] = "python" + version + abiflags
  1886. SDK["PYTHONEXEC"] = py_fwx + "/bin/python" + version
  1887. # Avoid choosing the one in the thirdparty package dir.
  1888. PkgSetCustomLocation("PYTHON")
  1889. IncDirectory("PYTHON", py_fwx + "/include")
  1890. LibDirectory("PYTHON", py_fwx + "/lib")
  1891. #elif GetTarget() == 'windows':
  1892. # SDK["PYTHON"] = os.path.dirname(sysconfig.get_python_inc())
  1893. # SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1894. # SDK["PYTHONEXEC"] = sys.executable
  1895. else:
  1896. SDK["PYTHON"] = sysconfig.get_python_inc()
  1897. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version() + abiflags
  1898. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1899. if CrossCompiling():
  1900. # We need a version of Python we can run.
  1901. SDK["PYTHONEXEC"] = sys.executable
  1902. host_version = "python" + sysconfig.get_python_version() + abiflags
  1903. if SDK["PYTHONVERSION"] != host_version:
  1904. exit("Host Python version (%s) must be the same as target Python version (%s)!" % (host_version, SDK["PYTHONVERSION"]))
  1905. if GetVerbose():
  1906. print("Using Python %s build located at %s" % (SDK["PYTHONVERSION"][6:9], SDK["PYTHON"]))
  1907. else:
  1908. print("Using Python %s" % (SDK["PYTHONVERSION"][6:9]))
  1909. def SdkLocateVisualStudio(version=(10,0)):
  1910. if (GetHost() != "windows"): return
  1911. try:
  1912. msvcinfo = MSVCVERSIONINFO[version]
  1913. except:
  1914. exit("Couldn't get Visual Studio infomation with MSVC %s.%s version." % version)
  1915. vsversion = msvcinfo["vsversion"]
  1916. vsversion_str = "%s.%s" % vsversion
  1917. version_str = "%s.%s" % version
  1918. # try to use vswhere.exe
  1919. vswhere_path = LocateBinary("vswhere.exe")
  1920. if not vswhere_path:
  1921. if sys.platform == 'cygwin':
  1922. vswhere_path = "/cygdrive/c/Program Files/Microsoft Visual Studio/Installer/vswhere.exe"
  1923. else:
  1924. vswhere_path = "%s\\Microsoft Visual Studio\\Installer\\vswhere.exe" % GetProgramFiles()
  1925. if not os.path.isfile(vswhere_path):
  1926. vswhere_path = None
  1927. if not vswhere_path:
  1928. if sys.platform == 'cygwin':
  1929. vswhere_path = "/cygdrive/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe"
  1930. else:
  1931. vswhere_path = "%s\\Microsoft Visual Studio\\Installer\\vswhere.exe" % GetProgramFiles_x86()
  1932. if not os.path.isfile(vswhere_path):
  1933. vswhere_path = None
  1934. vsdir = 0
  1935. if vswhere_path:
  1936. min_vsversion = vsversion_str
  1937. max_vsversion = "%s.%s" % (vsversion[0]+1, 0)
  1938. vswhere_cmd = ["vswhere.exe", "-legacy", "-property", "installationPath",
  1939. "-version", "[{},{})".format(min_vsversion, max_vsversion)]
  1940. handle = subprocess.Popen(vswhere_cmd, executable=vswhere_path, stdout=subprocess.PIPE)
  1941. found_paths = handle.communicate()[0].splitlines()
  1942. if found_paths:
  1943. vsdir = found_paths[0].decode("utf-8") + "\\"
  1944. # try to use registry
  1945. if (vsdir == 0):
  1946. vsdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7", vsversion_str)
  1947. vcdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", version_str)
  1948. if (vsdir != 0):
  1949. SDK["VISUALSTUDIO"] = vsdir
  1950. elif (vcdir != 0) and (vcdir[-4:] == "\\VC\\"):
  1951. vcdir = vcdir[:-3]
  1952. SDK["VISUALSTUDIO"] = vcdir
  1953. elif (os.path.isfile("C:\\Program Files\\Microsoft Visual Studio %s\\VC\\bin\\cl.exe" % (vsversion_str))):
  1954. SDK["VISUALSTUDIO"] = "C:\\Program Files\\Microsoft Visual Studio %s\\" % (vsversion_str)
  1955. elif (os.path.isfile("C:\\Program Files (x86)\\Microsoft Visual Studio %s\\VC\\bin\\cl.exe" % (vsversion_str))):
  1956. SDK["VISUALSTUDIO"] = "C:\\Program Files (x86)\\Microsoft Visual Studio %s\\" % (vsversion_str)
  1957. elif "VCINSTALLDIR" in os.environ:
  1958. vcdir = os.environ["VCINSTALLDIR"]
  1959. if (vcdir[-3:] == "\\VC"):
  1960. vcdir = vcdir[:-2]
  1961. elif (vcdir[-4:] == "\\VC\\"):
  1962. vcdir = vcdir[:-3]
  1963. SDK["VISUALSTUDIO"] = vcdir
  1964. else:
  1965. exit("Couldn't find %s. To use a different version, use the --msvc-version option." % msvcinfo["vsname"])
  1966. SDK["MSVC_VERSION"] = version
  1967. SDK["VISUALSTUDIO_VERSION"] = vsversion
  1968. if GetVerbose():
  1969. print("Using %s located at %s" % (msvcinfo["vsname"], SDK["VISUALSTUDIO"]))
  1970. else:
  1971. print("Using %s" % (msvcinfo["vsname"]))
  1972. print("Using MSVC %s" % version_str)
  1973. def SdkLocateWindows(version = '7.1'):
  1974. if GetTarget() != "windows" or GetHost() != "windows":
  1975. return
  1976. version = version.upper()
  1977. if version == '10':
  1978. version = '10.0'
  1979. if version.startswith('10.') and version.count('.') == 1:
  1980. # Choose the latest version of the Windows 10 SDK.
  1981. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  1982. # Fallback in case we can't read the registry.
  1983. if not platsdk or not os.path.isdir(platsdk):
  1984. platsdk = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  1985. if platsdk and os.path.isdir(platsdk):
  1986. incdirs = glob.glob(os.path.join(platsdk, 'Include', version + '.*.*'))
  1987. max_version = ()
  1988. for dir in incdirs:
  1989. verstring = os.path.basename(dir)
  1990. # Check that the important include directories exist.
  1991. if not os.path.isdir(os.path.join(dir, 'ucrt')):
  1992. continue
  1993. if not os.path.isdir(os.path.join(dir, 'shared')):
  1994. continue
  1995. if not os.path.isdir(os.path.join(dir, 'um')):
  1996. continue
  1997. if not os.path.isdir(os.path.join(platsdk, 'Lib', verstring, 'ucrt')):
  1998. continue
  1999. if not os.path.isdir(os.path.join(platsdk, 'Lib', verstring, 'um')):
  2000. continue
  2001. print(verstring)
  2002. vertuple = tuple(map(int, verstring.split('.')))
  2003. if vertuple > max_version:
  2004. version = verstring
  2005. max_version = vertuple
  2006. if not max_version:
  2007. # No suitable version found.
  2008. platsdk = None
  2009. elif version.startswith('10.'):
  2010. # We chose a specific version of the Windows 10 SDK. Verify it exists.
  2011. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  2012. # Fallback in case we can't read the registry.
  2013. if not platsdk or not os.path.isdir(platsdk):
  2014. platsdk = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  2015. if version.count('.') == 2:
  2016. version += '.0'
  2017. if platsdk and not os.path.isdir(os.path.join(platsdk, 'Include', version)):
  2018. platsdk = None
  2019. elif version == '8.1':
  2020. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot81")
  2021. # Fallback in case we can't read the registry.
  2022. if not platsdk or not os.path.isdir(platsdk):
  2023. platsdk = "C:\\Program Files (x86)\\Windows Kits\\8.1\\"
  2024. elif version == '8.0':
  2025. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot")
  2026. else:
  2027. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v" + version, "InstallationFolder")
  2028. if not platsdk or not os.path.isdir(platsdk):
  2029. # Most common location. Worth a try.
  2030. platsdk = GetProgramFiles() + "\\Microsoft SDKs\\Windows\\v" + version
  2031. if not os.path.isdir(platsdk):
  2032. if not version.endswith('A'):
  2033. # Try the stripped-down version that is bundled with Visual Studio.
  2034. return SdkLocateWindows(version + 'A')
  2035. platsdk = None
  2036. if not platsdk or not os.path.isdir(platsdk):
  2037. exit("Couldn't find Windows SDK version %s. To use a different version, use the --windows-sdk option." % (version))
  2038. if not platsdk.endswith("\\"):
  2039. platsdk += "\\"
  2040. SDK["MSPLATFORM"] = platsdk
  2041. SDK["MSPLATFORM_VERSION"] = version
  2042. if GetVerbose():
  2043. print("Using Windows SDK %s located at %s" % (version, platsdk))
  2044. else:
  2045. print("Using Windows SDK %s" % (version))
  2046. def SdkLocateMacOSX(osxtarget = None):
  2047. if (GetHost() != "darwin"): return
  2048. if (osxtarget != None):
  2049. sdkname = "MacOSX%d.%d" % osxtarget
  2050. if (os.path.exists("/Developer/SDKs/%su.sdk" % sdkname)):
  2051. SDK["MACOSX"] = "/Developer/SDKs/%su.sdk" % sdkname
  2052. elif (os.path.exists("/Developer/SDKs/%s.sdk" % sdkname)):
  2053. SDK["MACOSX"] = "/Developer/SDKs/%s.sdk" % sdkname
  2054. elif (os.path.exists("/Developer/SDKs/%s.0.sdk" % sdkname)):
  2055. SDK["MACOSX"] = "/Developer/SDKs/%s.0.sdk" % sdkname
  2056. elif (os.path.exists("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % sdkname)):
  2057. SDK["MACOSX"] = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % sdkname
  2058. else:
  2059. handle = os.popen("xcode-select -print-path")
  2060. result = handle.read().strip().rstrip('/')
  2061. handle.close()
  2062. if (os.path.exists("%s/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % (result, sdkname))):
  2063. SDK["MACOSX"] = "%s/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % (result, sdkname)
  2064. else:
  2065. exit("Couldn't find any MacOSX SDK for OSX version %s!" % sdkname)
  2066. else:
  2067. SDK["MACOSX"] = ""
  2068. # Latest first
  2069. PHYSXVERSIONINFO = [
  2070. ("PHYSX284", "v2.8.4"),
  2071. ("PHYSX283", "v2.8.3"),
  2072. ("PHYSX281", "v2.8.1"),
  2073. ]
  2074. def SdkLocatePhysX():
  2075. # First check for a physx directory in sdks.
  2076. dir = GetSdkDir("physx")
  2077. if (dir and os.path.isdir(dir)):
  2078. SDK["PHYSX"] = dir
  2079. SDK["PHYSXLIBS"] = dir + "/lib"
  2080. return
  2081. if CrossCompiling():
  2082. return
  2083. # Try to find a PhysX installation on the system.
  2084. for (ver, key) in PHYSXVERSIONINFO:
  2085. if (GetHost() == "windows"):
  2086. folders = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders"
  2087. for folder in ListRegistryValues(folders):
  2088. if folder.endswith("NVIDIA PhysX SDK\\%s\\SDKs\\" % key) or \
  2089. folder.endswith("NVIDIA PhysX SDK\\%s_win\\SDKs\\" % key):
  2090. SDK["PHYSX"] = folder
  2091. if GetTargetArch() == 'x64':
  2092. SDK["PHYSXLIBS"] = folder + "/lib/win64"
  2093. AddToPathEnv("PATH", folder + "/../Bin/win64/")
  2094. else:
  2095. SDK["PHYSXLIBS"] = folder + "/lib/win32"
  2096. AddToPathEnv("PATH", folder + "/../Bin/win32/")
  2097. return
  2098. elif (GetHost() == "linux"):
  2099. incpath = "/usr/include/PhysX/%s/SDKs" % key
  2100. libpath = "/usr/lib/PhysX/%s" % key
  2101. if (os.path.isdir(incpath) and os.path.isdir(libpath)):
  2102. SDK["PHYSX"] = incpath
  2103. SDK["PHYSXLIBS"] = libpath
  2104. return
  2105. def SdkLocateSpeedTree():
  2106. # Look for all of the SpeedTree SDK directories within the
  2107. # sdks/win32/speedtree dir, and pick the highest-numbered one.
  2108. dir = GetSdkDir("speedtree")
  2109. if not os.path.exists(dir):
  2110. return
  2111. speedtrees = []
  2112. for dirname in os.listdir(dir):
  2113. if dirname.startswith('SpeedTree SDK v'):
  2114. version = dirname[15:].split()[0]
  2115. version = tuple(map(int, version.split('.')))
  2116. speedtrees.append((version, dirname))
  2117. if not speedtrees:
  2118. # No installed SpeedTree SDK.
  2119. return
  2120. speedtrees.sort()
  2121. version, dirname = speedtrees[-1]
  2122. SDK["SPEEDTREE"] = os.path.join(dir, dirname)
  2123. SDK["SPEEDTREEAPI"] = "OpenGL"
  2124. SDK["SPEEDTREEVERSION"] = '%s.%s' % (version[0], version[1])
  2125. def SdkLocateAndroid():
  2126. """This actually locates the Android NDK, not the Android SDK.
  2127. NDK_ROOT must be set to its root directory."""
  2128. global TOOLCHAIN_PREFIX
  2129. if GetTarget() != 'android':
  2130. return
  2131. # Allow ANDROID_API/ANDROID_ABI to be used in makepanda.py.
  2132. api = ANDROID_API
  2133. SDK["ANDROID_API"] = api
  2134. abi = ANDROID_ABI
  2135. SDK["ANDROID_ABI"] = abi
  2136. SDK["ANDROID_TRIPLE"] = ANDROID_TRIPLE
  2137. if GetHost() == 'android':
  2138. # Assume we're compiling from termux.
  2139. prefix = os.environ.get("PREFIX", "/data/data/com.termux/files/usr")
  2140. SDK["ANDROID_JAR"] = prefix + "/share/aapt/android.jar"
  2141. return
  2142. # Find the location of the Android SDK.
  2143. sdk_root = os.environ.get('ANDROID_HOME')
  2144. if not sdk_root or not os.path.isdir(sdk_root):
  2145. sdk_root = os.environ.get('ANDROID_SDK_ROOT')
  2146. # Try the default installation location on Windows.
  2147. if not sdk_root and GetHost() == 'windows':
  2148. sdk_root = os.path.expanduser(os.path.join('~', 'AppData', 'Local', 'Android', 'Sdk'))
  2149. if not sdk_root:
  2150. exit('ANDROID_SDK_ROOT must be set when compiling for Android!')
  2151. elif not os.path.isdir(sdk_root):
  2152. exit('Cannot find %s. Please install Android SDK and set ANDROID_SDK_ROOT or ANDROID_HOME.' % (sdk_root))
  2153. # Determine the NDK installation directory.
  2154. if os.environ.get('NDK_ROOT') or os.environ.get('ANDROID_NDK_ROOT'):
  2155. # We have an explicit setting from an environment variable.
  2156. ndk_root = os.environ.get('ANDROID_NDK_ROOT')
  2157. if not ndk_root or not os.path.isdir(ndk_root):
  2158. ndk_root = os.environ.get('NDK_ROOT')
  2159. if not ndk_root or not os.path.isdir(ndk_root):
  2160. exit("Cannot find %s. Please install Android NDK and set ANDROID_NDK_ROOT." % (ndk_root))
  2161. else:
  2162. # Often, it's installed in the ndk-bundle subdirectory of the SDK.
  2163. ndk_root = os.path.join(sdk_root, 'ndk-bundle')
  2164. if not os.path.isdir(os.path.join(ndk_root, 'toolchains')):
  2165. exit('Cannot find the Android NDK. Install it via the SDK manager or set the ANDROID_NDK_ROOT variable if you have installed it in a different location.')
  2166. SDK["ANDROID_NDK"] = ndk_root
  2167. # Determine the toolchain location.
  2168. prebuilt_dir = os.path.join(ndk_root, 'toolchains', 'llvm', 'prebuilt')
  2169. if not os.path.isdir(prebuilt_dir):
  2170. exit('Not found: %s (is the Android NDK installed?)' % (prebuilt_dir))
  2171. host_tag = GetHost() + '-x86'
  2172. if host_64:
  2173. host_tag += '_64'
  2174. elif host_tag == 'windows-x86':
  2175. host_tag = 'windows'
  2176. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  2177. if host_tag == 'windows-x86_64' and not os.path.isdir(prebuilt_dir):
  2178. # Try the 32-bits toolchain instead.
  2179. host_tag = 'windows'
  2180. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  2181. SDK["ANDROID_TOOLCHAIN"] = prebuilt_dir
  2182. # And locate the GCC toolchain, which is needed for some tools (eg. as/ld)
  2183. arch = GetTargetArch()
  2184. for opt in (TOOLCHAIN_PREFIX + '4.9', arch + '-4.9', TOOLCHAIN_PREFIX + '4.8', arch + '-4.8'):
  2185. if os.path.isdir(os.path.join(ndk_root, 'toolchains', opt)):
  2186. SDK["ANDROID_GCC_TOOLCHAIN"] = os.path.join(ndk_root, 'toolchains', opt, 'prebuilt', host_tag)
  2187. break
  2188. # The prebuilt binaries have no toolchain prefix.
  2189. TOOLCHAIN_PREFIX = ''
  2190. # Determine the sysroot directory.
  2191. if arch == 'armv7a':
  2192. arch_dir = 'arch-arm'
  2193. elif arch == 'aarch64':
  2194. arch_dir = 'arch-arm64'
  2195. else:
  2196. arch_dir = 'arch-' + arch
  2197. SDK["SYSROOT"] = os.path.join(ndk_root, 'platforms', 'android-%s' % (api), arch_dir).replace('\\', '/')
  2198. #IncDirectory("ALWAYS", os.path.join(SDK["SYSROOT"], 'usr', 'include'))
  2199. # Starting with NDK r16, libc++ is the recommended STL to use.
  2200. stdlibc = os.path.join(ndk_root, 'sources', 'cxx-stl', 'llvm-libc++')
  2201. IncDirectory("ALWAYS", os.path.join(stdlibc, 'include').replace('\\', '/'))
  2202. LibDirectory("ALWAYS", os.path.join(stdlibc, 'libs', abi).replace('\\', '/'))
  2203. stl_lib = os.path.join(stdlibc, 'libs', abi, 'libc++_shared.so')
  2204. LibName("ALWAYS", stl_lib.replace('\\', '/'))
  2205. CopyFile(os.path.join(GetOutputDir(), 'lib', 'libc++_shared.so'), stl_lib)
  2206. # The Android support library polyfills C++ features not available in the
  2207. # STL that ships with Android.
  2208. support = os.path.join(ndk_root, 'sources', 'android', 'support', 'include')
  2209. IncDirectory("ALWAYS", support.replace('\\', '/'))
  2210. if api < 21:
  2211. LibName("ALWAYS", "-landroid_support")
  2212. # Determine the location of android.jar.
  2213. SDK["ANDROID_JAR"] = os.path.join(sdk_root, 'platforms', 'android-%s' % (api), 'android.jar')
  2214. if not os.path.isfile(SDK["ANDROID_JAR"]):
  2215. exit("Cannot find %s. Install platform API level %s via the SDK manager or change the targeted API level with --target=android-#" % (SDK["ANDROID_JAR"], api))
  2216. # Which build tools versions do we have? Pick the latest.
  2217. versions = []
  2218. for version in os.listdir(os.path.join(sdk_root, "build-tools")):
  2219. match = re.match('([0-9]+)\\.([0-9]+)\\.([0-9]+)', version)
  2220. if match:
  2221. version_tuple = int(match.group(1)), int(match.group(2)), int(match.group(3))
  2222. versions.append(version_tuple)
  2223. versions.sort()
  2224. if versions:
  2225. version = versions[-1]
  2226. SDK["ANDROID_BUILD_TOOLS"] = os.path.join(sdk_root, "build-tools", "{0}.{1}.{2}".format(*version))
  2227. # And find the location of the Java compiler.
  2228. if GetHost() == "windows":
  2229. jdk_home = os.environ.get("JDK_HOME") or os.environ.get("JAVA_HOME")
  2230. if not jdk_home:
  2231. # Try to use the Java shipped with Android Studio.
  2232. studio_path = GetRegistryKey("SOFTWARE\\Android Studio", "Path", override64=False)
  2233. if studio_path and os.path.isdir(studio_path):
  2234. jdk_home = os.path.join(studio_path, "jre")
  2235. if not jdk_home or not os.path.isdir(jdk_home):
  2236. exit("Cannot find JDK. Please set JDK_HOME or JAVA_HOME.")
  2237. javac = os.path.join(jdk_home, "bin", "javac.exe")
  2238. if not os.path.isfile(javac):
  2239. exit("Cannot find %s. Install the JDK and set JDK_HOME or JAVA_HOME." % (javac))
  2240. SDK["JDK"] = jdk_home
  2241. ########################################################################
  2242. ##
  2243. ## SDK Auto-Disables
  2244. ##
  2245. ## Disable packages whose SDKs could not be found.
  2246. ##
  2247. ########################################################################
  2248. def SdkAutoDisableDirectX():
  2249. for ver in DXVERSIONS + ["DIRECTCAM"]:
  2250. if (PkgSkip(ver)==0):
  2251. if (ver not in SDK):
  2252. if (GetHost() == "windows"):
  2253. WARNINGS.append("I cannot locate SDK for "+ver)
  2254. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  2255. PkgDisable(ver)
  2256. else:
  2257. WARNINGS.append("Using "+ver+" sdk: "+SDK[ver])
  2258. def SdkAutoDisableMaya():
  2259. for (ver,key) in MAYAVERSIONINFO:
  2260. if (ver not in SDK) and (PkgSkip(ver)==0):
  2261. if (GetHost() == "windows"):
  2262. WARNINGS.append("The registry does not appear to contain a pointer to the "+ver+" SDK.")
  2263. else:
  2264. WARNINGS.append("I cannot locate SDK for "+ver)
  2265. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  2266. PkgDisable(ver)
  2267. def SdkAutoDisableMax():
  2268. for version,key1,key2,subdir in MAXVERSIONINFO:
  2269. if (PkgSkip(version)==0) and ((version not in SDK) or (version+"CS" not in SDK)):
  2270. if (GetHost() == "windows"):
  2271. if (version in SDK):
  2272. WARNINGS.append("Your copy of "+version+" does not include the character studio SDK")
  2273. else:
  2274. WARNINGS.append("The registry does not appear to contain a pointer to "+version)
  2275. WARNINGS.append("I have automatically added this command-line option: --no-"+version.lower())
  2276. PkgDisable(version)
  2277. def SdkAutoDisablePhysX():
  2278. if ("PHYSX" not in SDK) and (PkgSkip("PHYSX")==0):
  2279. PkgDisable("PHYSX")
  2280. WARNINGS.append("I cannot locate SDK for PhysX")
  2281. WARNINGS.append("I have automatically added this command-line option: --no-physx")
  2282. def SdkAutoDisableSpeedTree():
  2283. if ("SPEEDTREE" not in SDK) and (PkgSkip("SPEEDTREE")==0):
  2284. PkgDisable("SPEEDTREE")
  2285. WARNINGS.append("I cannot locate SDK for SpeedTree")
  2286. WARNINGS.append("I have automatically added this command-line option: --no-speedtree")
  2287. ########################################################################
  2288. ##
  2289. ## Visual Studio comes with a script called VSVARS32.BAT, which
  2290. ## you need to run before using visual studio command-line tools.
  2291. ## The following python subroutine serves the same purpose.
  2292. ##
  2293. ########################################################################
  2294. def AddToPathEnv(path,add):
  2295. if path in os.environ:
  2296. if sys.platform == 'cygwin' and path != "PATH":
  2297. # INCLUDE, LIB, etc. must remain in Windows-style in cygwin.
  2298. os.environ[path] = add + ';' + os.environ[path]
  2299. else:
  2300. os.environ[path] = add + os.pathsep + os.environ[path]
  2301. else:
  2302. os.environ[path] = add
  2303. def SetupVisualStudioEnviron():
  2304. if ("VISUALSTUDIO" not in SDK):
  2305. exit("Could not find Visual Studio install directory")
  2306. if ("MSPLATFORM" not in SDK):
  2307. exit("Could not find the Microsoft Platform SDK")
  2308. if (SDK["VISUALSTUDIO_VERSION"] >= (15,0)):
  2309. try:
  2310. vsver_file = open(os.path.join(SDK["VISUALSTUDIO"],
  2311. "VC\\Auxiliary\\Build\\Microsoft.VCToolsVersion.default.txt"), "r")
  2312. SDK["VCTOOLSVERSION"] = vsver_file.readline().strip()
  2313. vcdir_suffix = "VC\\Tools\\MSVC\\%s\\" % SDK["VCTOOLSVERSION"]
  2314. except:
  2315. exit("Couldn't find tool version of %s." % MSVCVERSIONINFO[SDK["MSVC_VERSION"]]["vsname"])
  2316. else:
  2317. vcdir_suffix = "VC\\"
  2318. os.environ["VCINSTALLDIR"] = SDK["VISUALSTUDIO"] + vcdir_suffix
  2319. os.environ["WindowsSdkDir"] = SDK["MSPLATFORM"]
  2320. winsdk_ver = SDK["MSPLATFORM_VERSION"]
  2321. # Determine the directories to look in based on the architecture.
  2322. arch = GetTargetArch()
  2323. bindir = ""
  2324. libdir = ""
  2325. if ("VCTOOLSVERSION" in SDK):
  2326. bindir = "Host" + GetHostArch().upper() + "\\" + arch
  2327. libdir = arch
  2328. else:
  2329. if (arch == 'x64'):
  2330. bindir = 'amd64'
  2331. libdir = 'amd64'
  2332. elif (arch != 'x86'):
  2333. bindir = arch
  2334. libdir = arch
  2335. if (arch != 'x86' and GetHostArch() == 'x86'):
  2336. # Special version of the tools that run on x86.
  2337. bindir = 'x86_' + bindir
  2338. vc_binpath = SDK["VISUALSTUDIO"] + vcdir_suffix + "bin"
  2339. binpath = os.path.join(vc_binpath, bindir)
  2340. if not os.path.isfile(binpath + "\\cl.exe"):
  2341. # Try the x86 tools, those should work just as well.
  2342. if arch == 'x64' and os.path.isfile(vc_binpath + "\\x86_amd64\\cl.exe"):
  2343. binpath = "{0}\\x86_amd64;{0}".format(vc_binpath)
  2344. elif winsdk_ver.startswith('10.'):
  2345. exit("Couldn't find compilers in %s. You may need to install the Windows SDK 7.1 and the Visual C++ 2010 SP1 Compiler Update for Windows SDK 7.1." % binpath)
  2346. else:
  2347. exit("Couldn't find compilers in %s." % binpath)
  2348. AddToPathEnv("PATH", binpath)
  2349. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "Common7\\IDE")
  2350. AddToPathEnv("INCLUDE", os.environ["VCINSTALLDIR"] + "include")
  2351. AddToPathEnv("INCLUDE", os.environ["VCINSTALLDIR"] + "atlmfc\\include")
  2352. AddToPathEnv("LIB", os.environ["VCINSTALLDIR"] + "lib\\" + libdir)
  2353. AddToPathEnv("LIB", os.environ["VCINSTALLDIR"] + "atlmfc\\lib\\" + libdir)
  2354. winsdk_ver = SDK["MSPLATFORM_VERSION"]
  2355. if winsdk_ver.startswith('10.'):
  2356. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + arch)
  2357. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + winsdk_ver + "\\" + arch)
  2358. # Windows Kit 10 introduces the "universal CRT".
  2359. inc_dir = SDK["MSPLATFORM"] + "Include\\" + winsdk_ver + "\\"
  2360. lib_dir = SDK["MSPLATFORM"] + "Lib\\" + winsdk_ver + "\\"
  2361. AddToPathEnv("INCLUDE", inc_dir + "shared")
  2362. AddToPathEnv("INCLUDE", inc_dir + "ucrt")
  2363. AddToPathEnv("INCLUDE", inc_dir + "um")
  2364. AddToPathEnv("LIB", lib_dir + "ucrt\\" + arch)
  2365. AddToPathEnv("LIB", lib_dir + "um\\" + arch)
  2366. elif winsdk_ver == '8.1':
  2367. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + arch)
  2368. inc_dir = SDK["MSPLATFORM"] + "Include\\"
  2369. lib_dir = SDK["MSPLATFORM"] + "Lib\\winv6.3\\"
  2370. AddToPathEnv("INCLUDE", inc_dir + "shared")
  2371. AddToPathEnv("INCLUDE", inc_dir + "ucrt")
  2372. AddToPathEnv("INCLUDE", inc_dir + "um")
  2373. AddToPathEnv("LIB", lib_dir + "ucrt\\" + arch)
  2374. AddToPathEnv("LIB", lib_dir + "um\\" + arch)
  2375. else:
  2376. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin")
  2377. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include")
  2378. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\atl")
  2379. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\mfc")
  2380. if arch != 'x64':
  2381. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib")
  2382. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.CRT")
  2383. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.MFC")
  2384. elif os.path.isdir(SDK["MSPLATFORM"] + "lib\\x64"):
  2385. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\x64")
  2386. elif os.path.isdir(SDK["MSPLATFORM"] + "lib\\amd64"):
  2387. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\amd64")
  2388. else:
  2389. exit("Could not locate 64-bits libraries in Windows SDK directory!\nUsing directory: %s" % SDK["MSPLATFORM"])
  2390. # Targeting the 7.1 SDK (which is the only way to have Windows XP support)
  2391. # with Visual Studio 2015 requires use of the Universal CRT.
  2392. if winsdk_ver in ('7.1', '7.1A') and SDK["VISUALSTUDIO_VERSION"] >= (14,0):
  2393. win_kit = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  2394. # Fallback in case we can't read the registry.
  2395. if not win_kit or not os.path.isdir(win_kit):
  2396. win_kit = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  2397. elif not win_kit.endswith('\\'):
  2398. win_kit += '\\'
  2399. for vnum in 10150, 10240, 10586, 14393, 15063, 16299, 17134, 17763:
  2400. version = "10.0.{0}.0".format(vnum)
  2401. if os.path.isfile(win_kit + "Include\\" + version + "\\ucrt\\assert.h"):
  2402. print("Using Universal CRT %s" % (version))
  2403. break
  2404. AddToPathEnv("LIB", "%s\\Lib\\%s\\ucrt\\%s" % (win_kit, version, arch))
  2405. AddToPathEnv("INCLUDE", "%s\\Include\\%s\\ucrt" % (win_kit, version))
  2406. # Copy the DLLs to the bin directory.
  2407. CopyAllFiles(GetOutputDir() + "/bin/", win_kit + "Redist\\ucrt\\DLLs\\" + arch + "\\")
  2408. ########################################################################
  2409. #
  2410. # Include and Lib directories.
  2411. #
  2412. # These allow you to add include and lib directories to the
  2413. # compiler search paths. These methods accept a "package"
  2414. # parameter, which specifies which package the directory is
  2415. # associated with. The include/lib directory is not used
  2416. # if the package is not selected. The package can be 'ALWAYS'.
  2417. #
  2418. ########################################################################
  2419. INCDIRECTORIES = []
  2420. LIBDIRECTORIES = []
  2421. FRAMEWORKDIRECTORIES = []
  2422. LIBNAMES = []
  2423. DEFSYMBOLS = []
  2424. def IncDirectory(opt, dir):
  2425. INCDIRECTORIES.append((opt, dir))
  2426. def LibDirectory(opt, dir):
  2427. LIBDIRECTORIES.append((opt, dir))
  2428. def FrameworkDirectory(opt, dir):
  2429. FRAMEWORKDIRECTORIES.append((opt, dir))
  2430. def LibName(opt, name):
  2431. # Check to see if the lib file actually exists for the thirdparty library given
  2432. # Are we a thirdparty library?
  2433. if name.startswith(GetThirdpartyDir()):
  2434. # Does this lib exist?
  2435. if not os.path.exists(name):
  2436. WARNINGS.append(name + " not found. Skipping Package " + opt)
  2437. if (opt in PkgListGet()):
  2438. if not PkgSkip(opt):
  2439. Warn("Could not locate thirdparty package %s, excluding from build" % (opt.lower()))
  2440. PkgDisable(opt)
  2441. return
  2442. else:
  2443. Error("Could not locate thirdparty package %s, aborting build" % (opt.lower()))
  2444. LIBNAMES.append((opt, name))
  2445. def DefSymbol(opt, sym, val=""):
  2446. DEFSYMBOLS.append((opt, sym, val))
  2447. ########################################################################
  2448. #
  2449. # This subroutine prepares the environment for the build.
  2450. #
  2451. ########################################################################
  2452. def SetupBuildEnvironment(compiler):
  2453. if GetVerbose():
  2454. print("Using compiler: %s" % compiler)
  2455. print("Host OS: %s" % GetHost())
  2456. print("Host arch: %s" % GetHostArch())
  2457. target = GetTarget()
  2458. if target != 'android':
  2459. print("Target OS: %s" % GetTarget())
  2460. else:
  2461. print("Target OS: %s (API level %d)" % (GetTarget(), ANDROID_API))
  2462. print("Target arch: %s" % GetTargetArch())
  2463. # Set to English so we can safely parse the result of gcc commands.
  2464. # Setting it to UTF-8 is necessary for Python 3 modules to import
  2465. # correctly.
  2466. os.environ["LC_ALL"] = "en_US.UTF-8"
  2467. os.environ["LANGUAGE"] = "en"
  2468. # In the case of Android, we have to put the toolchain on the PATH in order to use it.
  2469. if GetTarget() == 'android' and GetHost() != 'android':
  2470. AddToPathEnv("PATH", os.path.join(SDK["ANDROID_TOOLCHAIN"], "bin"))
  2471. if "ANDROID_BUILD_TOOLS" in SDK:
  2472. AddToPathEnv("PATH", SDK["ANDROID_BUILD_TOOLS"])
  2473. if "JDK" in SDK:
  2474. AddToPathEnv("PATH", os.path.join(SDK["JDK"], "bin"))
  2475. os.environ["JAVA_HOME"] = SDK["JDK"]
  2476. if compiler == "MSVC":
  2477. # Add the visual studio tools to PATH et al.
  2478. SetupVisualStudioEnviron()
  2479. if compiler == "GCC":
  2480. # Invoke gcc to determine the system library directories.
  2481. global SYS_LIB_DIRS, SYS_INC_DIRS
  2482. if sys.platform == "darwin":
  2483. # We need to add this one explicitly for some reason.
  2484. SYS_LIB_DIRS.append(SDK["MACOSX"] + "/usr/lib")
  2485. if not SDK.get("MACOSX"):
  2486. # gcc doesn't add this one, but we do want it:
  2487. local_lib = SDK.get("SYSROOT", "") + "/usr/local/lib"
  2488. if os.path.isdir(local_lib):
  2489. SYS_LIB_DIRS.append(local_lib)
  2490. sysroot_flag = ""
  2491. if SDK.get("MACOSX"):
  2492. # The default compiler in Leopard does not respect --sysroot correctly.
  2493. sysroot_flag = " -isysroot " + SDK["MACOSX"]
  2494. if SDK.get("SYSROOT"):
  2495. sysroot_flag = ' --sysroot=%s -no-canonical-prefixes' % (SDK["SYSROOT"])
  2496. # Extract the dirs from the line that starts with 'libraries: ='.
  2497. cmd = GetCXX() + " -print-search-dirs" + sysroot_flag
  2498. handle = os.popen(cmd)
  2499. for line in handle:
  2500. if not line.startswith('libraries: ='):
  2501. continue
  2502. line = line[12:].strip()
  2503. libdirs = line.split(':')
  2504. while libdirs:
  2505. libdir = os.path.normpath(libdirs.pop(0))
  2506. if os.path.isdir(libdir):
  2507. if libdir not in SYS_LIB_DIRS:
  2508. SYS_LIB_DIRS.append(libdir)
  2509. elif len(libdir) == 1:
  2510. # Oops, is this a drive letter? Prepend it to the next.
  2511. libdirs[0] = libdir + ':' + libdirs[0]
  2512. elif GetVerbose():
  2513. print("Ignoring non-existent library directory %s" % (libdir))
  2514. returnval = handle.close()
  2515. if returnval != None and returnval != 0:
  2516. Warn("%s failed" % (cmd))
  2517. SYS_LIB_DIRS += [SDK.get("SYSROOT", "") + "/usr/lib"]
  2518. # The Android toolchain on Windows doesn't actually add this one.
  2519. if target == 'android' and GetHost() == 'windows':
  2520. libdir = SDK.get("SYSROOT", "") + "/usr/lib"
  2521. if GetTargetArch() == 'x86_64':
  2522. libdir += '64'
  2523. SYS_LIB_DIRS += [libdir]
  2524. # Now extract the preprocessor's include directories.
  2525. cmd = GetCXX() + " -x c++ -v -E " + os.devnull
  2526. if "ANDROID_NDK" in SDK:
  2527. ndk_dir = SDK["ANDROID_NDK"].replace('\\', '/')
  2528. cmd += ' -isystem %s/sysroot/usr/include' % (ndk_dir)
  2529. cmd += ' -isystem %s/sysroot/usr/include/%s' % (ndk_dir, SDK["ANDROID_TRIPLE"])
  2530. else:
  2531. cmd += sysroot_flag
  2532. null = open(os.devnull, 'w')
  2533. handle = subprocess.Popen(cmd, stdout=null, stderr=subprocess.PIPE, shell=True)
  2534. scanning = False
  2535. for line in handle.communicate()[1].splitlines():
  2536. line = line.decode('utf-8', 'replace')
  2537. # Start looking at a line that says: #include "..." search starts here
  2538. if not scanning:
  2539. if line.startswith('#include'):
  2540. scanning = True
  2541. continue
  2542. if sys.platform == "win32":
  2543. if not line.startswith(' '):
  2544. continue
  2545. else:
  2546. if not line.startswith(' /'):
  2547. continue
  2548. line = line.strip()
  2549. if line.endswith(" (framework directory)"):
  2550. pass
  2551. elif os.path.isdir(line):
  2552. SYS_INC_DIRS.append(os.path.normpath(line))
  2553. elif GetVerbose():
  2554. print("Ignoring non-existent include directory %s" % (line))
  2555. if handle.returncode != 0 or not SYS_INC_DIRS:
  2556. Warn("%s failed or did not produce the expected result" % (cmd))
  2557. sysroot = SDK.get("SYSROOT", "")
  2558. # Add some sensible directories as a fallback.
  2559. SYS_INC_DIRS = [
  2560. sysroot + "/usr/include",
  2561. sysroot + "/usr/local/include"
  2562. ]
  2563. pcbsd_inc = sysroot + "/usr/PCBSD/local/include"
  2564. if os.path.isdir(pcbsd_inc):
  2565. SYS_INC_DIRS.append(pcbsd_inc)
  2566. null.close()
  2567. # Print out the search paths
  2568. if GetVerbose():
  2569. print("System library search path:")
  2570. for dir in SYS_LIB_DIRS:
  2571. print(" " + dir)
  2572. print("System include search path:")
  2573. for dir in SYS_INC_DIRS:
  2574. print(" " + dir)
  2575. # If we're cross-compiling, no point in putting our output dirs on the path.
  2576. if CrossCompiling():
  2577. return
  2578. # Add our output directories to the environment.
  2579. builtdir = GetOutputDir()
  2580. AddToPathEnv("PYTHONPATH", builtdir)
  2581. AddToPathEnv("PANDA_PRC_DIR", os.path.join(builtdir, "etc"))
  2582. AddToPathEnv("PATH", os.path.join(builtdir, "bin"))
  2583. if GetHost() == 'windows':
  2584. # extension_native_helpers.py currently expects to find libpandaexpress on sys.path.
  2585. AddToPathEnv("PYTHONPATH", os.path.join(builtdir, "bin"))
  2586. AddToPathEnv("PATH", os.path.join(builtdir, "plugins"))
  2587. # Now for the special (DY)LD_LIBRARY_PATH on Unix-esque systems.
  2588. if GetHost() != 'windows':
  2589. # Get the current
  2590. ldpath = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep)
  2591. if GetHost() == 'darwin':
  2592. dyldpath = os.environ.get("DYLD_LIBRARY_PATH", "").split(os.pathsep)
  2593. # Remove any potential current Panda installation lib dirs
  2594. for i in ldpath[:]:
  2595. if i.startswith("/usr/lib/panda3d") or \
  2596. i.startswith("/usr/local/panda"):
  2597. ldpath.remove(i)
  2598. if GetHost() == 'darwin':
  2599. for i in dyldpath[:]:
  2600. if i.startswith("/Applications/Panda3D") or \
  2601. i.startswith("/Developer/Panda3D"):
  2602. dyldpath.remove(i)
  2603. # Add built/lib/ to (DY)LD_LIBRARY_PATH
  2604. ldpath.insert(0, os.path.join(builtdir, 'lib'))
  2605. os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(ldpath)
  2606. if GetHost() == 'darwin':
  2607. dyldpath.insert(0, os.path.join(builtdir, 'lib'))
  2608. os.environ["DYLD_LIBRARY_PATH"] = os.pathsep.join(dyldpath)
  2609. # OS X 10.11 removed DYLD_LIBRARY_PATH, but we still need to pass
  2610. # on our lib directory to ppackage, so add it to PATH instead.
  2611. os.environ["PATH"] = os.path.join(builtdir, 'lib') + ':' + os.environ.get("PATH", "")
  2612. # Workaround around compile issue on PCBSD
  2613. if (os.path.exists("/usr/PCBSD")):
  2614. os.environ["LD_LIBRARY_PATH"] += os.pathsep + "/usr/PCBSD/local/lib"
  2615. ########################################################################
  2616. ##
  2617. ## Routines to copy files into the build tree
  2618. ##
  2619. ########################################################################
  2620. def CopyFile(dstfile, srcfile):
  2621. if dstfile[-1] == '/':
  2622. dstfile += os.path.basename(srcfile)
  2623. if NeedsBuild([dstfile], [srcfile]):
  2624. if os.path.islink(srcfile):
  2625. # Preserve symlinks
  2626. if os.path.isfile(dstfile) or os.path.islink(dstfile):
  2627. print("Removing file %s" % (dstfile))
  2628. os.unlink(dstfile)
  2629. elif os.path.isdir(dstfile):
  2630. print("Removing directory %s" % (dstfile))
  2631. shutil.rmtree(dstfile)
  2632. os.symlink(os.readlink(srcfile), dstfile)
  2633. else:
  2634. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2635. if sys.platform == 'cygwin' and os.path.splitext(dstfile)[1].lower() in ('.dll', '.exe'):
  2636. os.chmod(dstfile, 0o755)
  2637. JustBuilt([dstfile], [srcfile])
  2638. def CopyAllFiles(dstdir, srcdir, suffix=""):
  2639. for x in GetDirectoryContents(srcdir, ["*"+suffix]):
  2640. CopyFile(dstdir + x, srcdir + x)
  2641. def CopyAllHeaders(dir, skip=[]):
  2642. for filename in GetDirectoryContents(dir, ["*.h", "*.I", "*.T"], skip):
  2643. srcfile = dir + "/" + filename
  2644. dstfile = OUTPUTDIR + "/include/" + filename
  2645. if (NeedsBuild([dstfile], [srcfile])):
  2646. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2647. JustBuilt([dstfile], [srcfile])
  2648. def CopyTree(dstdir, srcdir, omitVCS=True):
  2649. if os.path.isdir(dstdir):
  2650. source_entries = os.listdir(srcdir)
  2651. for entry in source_entries:
  2652. srcpth = os.path.join(srcdir, entry)
  2653. dstpth = os.path.join(dstdir, entry)
  2654. if os.path.islink(srcpth) or os.path.isfile(srcpth):
  2655. if not omitVCS or entry not in VCS_FILES:
  2656. CopyFile(dstpth, srcpth)
  2657. else:
  2658. if not omitVCS or entry not in VCS_DIRS:
  2659. CopyTree(dstpth, srcpth)
  2660. # Delete files in dstdir that are not in srcdir.
  2661. for entry in os.listdir(dstdir):
  2662. if entry not in source_entries:
  2663. path = os.path.join(dstdir, entry)
  2664. if os.path.islink(path) or os.path.isfile(path):
  2665. os.remove(path)
  2666. elif os.path.isdir(path):
  2667. shutil.rmtree(path)
  2668. else:
  2669. if GetHost() == 'windows':
  2670. srcdir = srcdir.replace('/', '\\')
  2671. dstdir = dstdir.replace('/', '\\')
  2672. cmd = 'xcopy /I/Y/E/Q "' + srcdir + '" "' + dstdir + '"'
  2673. oscmd(cmd)
  2674. else:
  2675. if subprocess.call(['cp', '-R', '-f', srcdir, dstdir]) != 0:
  2676. exit("Copy failed.")
  2677. if omitVCS:
  2678. DeleteVCS(dstdir)
  2679. def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[], threads=0):
  2680. if (not os.path.isdir(dstdir)):
  2681. os.mkdir(dstdir)
  2682. lib2to3 = None
  2683. lib2to3_args = ['-w', '-n', '--no-diffs']
  2684. if len(lib2to3_fixers) > 0 and sys.version_info >= (3, 0):
  2685. from lib2to3.main import main as lib2to3
  2686. if lib2to3_fixers == ['all']:
  2687. lib2to3_args += ['-x', 'buffer', '-x', 'idioms', '-x', 'set_literal', '-x', 'ws_comma']
  2688. else:
  2689. for fixer in lib2to3_fixers:
  2690. lib2to3_args += ['-f', fixer]
  2691. if threads:
  2692. lib2to3_args += ['-j', str(threads)]
  2693. exclude_files = set(VCS_FILES)
  2694. exclude_files.add('panda3d.py')
  2695. refactor = []
  2696. for entry in os.listdir(srcdir):
  2697. srcpth = os.path.join(srcdir, entry)
  2698. dstpth = os.path.join(dstdir, entry)
  2699. if os.path.isfile(srcpth):
  2700. base, ext = os.path.splitext(entry)
  2701. if entry not in exclude_files and ext not in SUFFIX_INC + ['.pyc', '.pyo']:
  2702. if (NeedsBuild([dstpth], [srcpth])):
  2703. WriteBinaryFile(dstpth, ReadBinaryFile(srcpth))
  2704. if ext == '.py' and not entry.endswith('-extensions.py'):
  2705. refactor.append((dstpth, srcpth))
  2706. lib2to3_args.append(dstpth)
  2707. else:
  2708. JustBuilt([dstpth], [srcpth])
  2709. elif entry not in VCS_DIRS:
  2710. CopyPythonTree(dstpth, srcpth, lib2to3_fixers, threads=threads)
  2711. if refactor and lib2to3 is not None:
  2712. ret = lib2to3("lib2to3.fixes", lib2to3_args)
  2713. if ret != 0:
  2714. for dstpth, srcpth in refactor:
  2715. os.remove(dstpth)
  2716. exit("Error in lib2to3.")
  2717. else:
  2718. for dstpth, srcpth in refactor:
  2719. JustBuilt([dstpth], [srcpth])
  2720. ########################################################################
  2721. ##
  2722. ## Parse PandaVersion.pp to extract the version number.
  2723. ##
  2724. ########################################################################
  2725. cfg_parser = None
  2726. def GetMetadataValue(key):
  2727. global cfg_parser
  2728. if not cfg_parser:
  2729. # Parse the metadata from the setup.cfg file.
  2730. cfg_parser = configparser.ConfigParser()
  2731. path = os.path.join(os.path.dirname(__file__), '..', 'setup.cfg')
  2732. assert cfg_parser.read(path), "Could not read setup.cfg file."
  2733. value = cfg_parser.get('metadata', key)
  2734. if key == 'classifiers':
  2735. value = value.strip().split('\n')
  2736. return value
  2737. # This function is being phased out.
  2738. def ParsePandaVersion(fn):
  2739. try:
  2740. f = open(fn, "r")
  2741. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2742. for line in f:
  2743. match = pattern.match(line, 0)
  2744. if (match):
  2745. f.close()
  2746. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2747. f.close()
  2748. except: pass
  2749. return "0.0.0"
  2750. def ParsePluginVersion(fn):
  2751. try:
  2752. f = open(fn, "r")
  2753. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_PLUGIN_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2754. for line in f:
  2755. match = pattern.match(line,0)
  2756. if (match):
  2757. f.close()
  2758. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2759. f.close()
  2760. except: pass
  2761. return "0.0.0"
  2762. def ParseCoreapiVersion(fn):
  2763. try:
  2764. f = open(fn, "r")
  2765. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_COREAPI_VERSION.*([0-9]+)[ \t]*$')
  2766. for line in f:
  2767. match = pattern.match(line,0)
  2768. if (match):
  2769. f.close()
  2770. return match.group(1)
  2771. f.close()
  2772. except: pass
  2773. return "0"
  2774. ##########################################################################################
  2775. #
  2776. # Utility function to generate a resource file
  2777. #
  2778. ##########################################################################################
  2779. RESOURCE_FILE_TEMPLATE = """VS_VERSION_INFO VERSIONINFO
  2780. FILEVERSION %(commaversion)s
  2781. PRODUCTVERSION %(commaversion)s
  2782. FILEFLAGSMASK 0x3fL
  2783. FILEFLAGS %(debugflag)s
  2784. FILEOS 0x40004L
  2785. FILETYPE 0x2L
  2786. FILESUBTYPE 0x0L
  2787. BEGIN
  2788. BLOCK "StringFileInfo"
  2789. BEGIN
  2790. BLOCK "040904e4"
  2791. BEGIN
  2792. VALUE "FileDescription", "%(description)s\\0"
  2793. VALUE "FileVersion", "%(dotversion)s"
  2794. VALUE "LegalTrademarks", "\\0"
  2795. VALUE "MIMEType", "%(mimetype)s\\0"
  2796. VALUE "FileExtents", "%(extension)s\\0"
  2797. VALUE "FileOpenName", "%(filedesc)s\\0"
  2798. VALUE "OLESelfRegister", "\\0"
  2799. VALUE "OriginalFilename", "%(filename)s\\0"
  2800. VALUE "ProductName", "%(name)s %(version)s\\0"
  2801. VALUE "ProductVersion", "%(dotversion)s"
  2802. END
  2803. END
  2804. BLOCK "VarFileInfo"
  2805. BEGIN
  2806. VALUE "Translation", 0x409, 1252
  2807. END
  2808. END
  2809. """
  2810. def GenerateResourceFile(**kwargs):
  2811. if "debugflag" not in kwargs:
  2812. if GetOptimize() <= 2:
  2813. kwargs["debugflag"] = "0x1L"
  2814. else:
  2815. kwargs["debugflag"] = "0x0L"
  2816. kwargs["dotversion"] = kwargs["version"]
  2817. if len(kwargs["dotversion"].split(".")) == 3:
  2818. kwargs["dotversion"] += ".0"
  2819. if "commaversion" not in kwargs:
  2820. kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
  2821. rcdata = ""
  2822. if not "noinclude" in kwargs:
  2823. rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
  2824. rcdata += "#include \"winresrc.h\"\n"
  2825. rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
  2826. rcdata += RESOURCE_FILE_TEMPLATE % kwargs
  2827. if "icon" in kwargs:
  2828. rcdata += "\nICON_FILE ICON \"%s\"\n" % kwargs["icon"]
  2829. return rcdata
  2830. def WriteResourceFile(basename, **kwargs):
  2831. if not basename.endswith(".rc"):
  2832. basename += ".rc"
  2833. basename = GetOutputDir() + "/include/" + basename
  2834. ConditionalWriteFile(basename, GenerateResourceFile(**kwargs))
  2835. return basename
  2836. def WriteEmbeddedStringFile(basename, inputs, string_name=None):
  2837. if os.path.splitext(basename)[1] not in SUFFIX_INC:
  2838. basename += '.cxx'
  2839. target = GetOutputDir() + "/tmp/" + basename
  2840. if string_name is None:
  2841. string_name = os.path.basename(os.path.splitext(target)[0])
  2842. string_name = string_name.replace('-', '_')
  2843. data = bytearray()
  2844. for input in inputs:
  2845. fp = open(input, 'rb')
  2846. # Insert a #line so that we get meaningful compile/assert errors when
  2847. # the result is inserted by interrogate_module into generated code.
  2848. if os.path.splitext(input)[1] in SUFFIX_INC:
  2849. line = '#line 1 "%s"\n' % (input)
  2850. data += bytearray(line.encode('ascii', 'replace'))
  2851. data += bytearray(fp.read())
  2852. fp.close()
  2853. data.append(0)
  2854. output = 'extern const char %s[] = {\n' % (string_name)
  2855. i = 0
  2856. for byte in data:
  2857. if i == 0:
  2858. output += ' '
  2859. output += ' 0x%02x,' % (byte)
  2860. i += 1
  2861. if i >= 12:
  2862. output += '\n'
  2863. i = 0
  2864. output += '\n};\n'
  2865. ConditionalWriteFile(target, output)
  2866. return target
  2867. ########################################################################
  2868. ##
  2869. ## FindLocation
  2870. ##
  2871. ########################################################################
  2872. ORIG_EXT = {}
  2873. PYABI_SPECIFIC = set()
  2874. WARNED_FILES = set()
  2875. def GetOrigExt(x):
  2876. return ORIG_EXT[x]
  2877. def SetOrigExt(x, v):
  2878. ORIG_EXT[x] = v
  2879. def GetExtensionSuffix():
  2880. if sys.version_info >= (3, 0):
  2881. import _imp
  2882. return _imp.extension_suffixes()[0]
  2883. target = GetTarget()
  2884. if target == 'windows':
  2885. return '.pyd'
  2886. else:
  2887. return '.so'
  2888. def GetPythonABI():
  2889. soabi = sysconfig.get_config_var('SOABI')
  2890. if soabi:
  2891. return soabi
  2892. soabi = 'cpython-%d%d' % (sys.version_info[:2])
  2893. if sys.version_info >= (3, 8):
  2894. return soabi
  2895. debug_flag = sysconfig.get_config_var('Py_DEBUG')
  2896. if (debug_flag is None and hasattr(sys, 'gettotalrefcount')) or debug_flag:
  2897. soabi += 'd'
  2898. malloc_flag = sysconfig.get_config_var('WITH_PYMALLOC')
  2899. if malloc_flag is None or malloc_flag:
  2900. soabi += 'm'
  2901. if sys.version_info < (3, 3):
  2902. usize = sysconfig.get_config_var('Py_UNICODE_SIZE')
  2903. if (usize is None and sys.maxunicode == 0x10ffff) or usize == 4:
  2904. soabi += 'u'
  2905. return soabi
  2906. def CalcLocation(fn, ipath):
  2907. if fn.startswith("panda3d/") and fn.endswith(".py"):
  2908. return OUTPUTDIR + "/" + fn
  2909. if (fn.endswith(".class")):return OUTPUTDIR+"/classes/"+fn
  2910. if (fn.count("/")): return fn
  2911. dllext = ""
  2912. target = GetTarget()
  2913. if (GetOptimize() <= 2 and target == 'windows'): dllext = "_d"
  2914. if (fn == "AndroidManifest.xml"): return OUTPUTDIR+"/"+fn
  2915. if (fn.endswith(".cxx")): return CxxFindSource(fn, ipath)
  2916. if (fn.endswith(".I")): return CxxFindSource(fn, ipath)
  2917. if (fn.endswith(".h")): return CxxFindSource(fn, ipath)
  2918. if (fn.endswith(".c")): return CxxFindSource(fn, ipath)
  2919. if (fn.endswith(".py")): return CxxFindSource(fn, ipath)
  2920. if (fn.endswith(".yxx")): return CxxFindSource(fn, ipath)
  2921. if (fn.endswith(".lxx")): return CxxFindSource(fn, ipath)
  2922. if (fn.endswith(".pdef")):return CxxFindSource(fn, ipath)
  2923. if (fn.endswith(".xml")): return CxxFindSource(fn, ipath)
  2924. if (fn.endswith(".java")):return CxxFindSource(fn, ipath)
  2925. if (fn.endswith(".egg")): return OUTPUTDIR+"/models/"+fn
  2926. if (fn.endswith(".egg.pz")):return OUTPUTDIR+"/models/"+fn
  2927. if (fn.endswith(".pyd")): return OUTPUTDIR+"/panda3d/"+fn[:-4]+GetExtensionSuffix()
  2928. if (target == 'windows'):
  2929. if (fn.endswith(".def")): return CxxFindSource(fn, ipath)
  2930. if (fn.endswith(".rc")): return CxxFindSource(fn, ipath)
  2931. if (fn.endswith(".idl")): return CxxFindSource(fn, ipath)
  2932. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn
  2933. if (fn.endswith(".res")): return OUTPUTDIR+"/tmp/"+fn
  2934. if (fn.endswith(".tlb")): return OUTPUTDIR+"/tmp/"+fn
  2935. if (fn.endswith(".dll")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".dll"
  2936. if (fn.endswith(".ocx")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".ocx"
  2937. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".mll"
  2938. if (fn.endswith(".dlo")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dlo"
  2939. if (fn.endswith(".dli")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dli"
  2940. if (fn.endswith(".dle")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dle"
  2941. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".dll"
  2942. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn
  2943. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn
  2944. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+dllext+".lib"
  2945. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+dllext+".lib"
  2946. elif (target == 'darwin'):
  2947. if (fn.endswith(".mm")): return CxxFindSource(fn, ipath)
  2948. if (fn.endswith(".r")): return CxxFindSource(fn, ipath)
  2949. if (fn.endswith(".plist")): return CxxFindSource(fn, ipath)
  2950. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2951. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  2952. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2953. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2954. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2955. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2956. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2957. if (fn.endswith(".rsrc")): return OUTPUTDIR+"/tmp/"+fn
  2958. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn
  2959. if (fn.endswith(".app")): return OUTPUTDIR+"/bin/"+fn
  2960. else:
  2961. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2962. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  2963. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2964. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  2965. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2966. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2967. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2968. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2969. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  2970. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  2971. return fn
  2972. def FindLocation(fn, ipath, pyabi=None):
  2973. if GetLinkAllStatic():
  2974. if fn.endswith(".dll"):
  2975. fn = fn[:-4] + ".lib"
  2976. elif fn.endswith(".pyd"):
  2977. fn = "libpy.panda3d." \
  2978. + os.path.splitext(fn[:-4] + GetExtensionSuffix())[0] + ".lib"
  2979. loc = CalcLocation(fn, ipath)
  2980. base, ext = os.path.splitext(fn)
  2981. # If this is a target created with PyTargetAdd, we need to make sure it
  2982. # it put in a Python-version-specific directory.
  2983. if loc in PYABI_SPECIFIC:
  2984. if loc.startswith(OUTPUTDIR + "/tmp"):
  2985. if pyabi is not None:
  2986. loc = OUTPUTDIR + "/tmp/" + pyabi + loc[len(OUTPUTDIR) + 4:]
  2987. else:
  2988. raise RuntimeError("%s is a Python-specific target, use PyTargetAdd instead of TargetAdd" % (fn))
  2989. elif ext != ".pyd" and loc not in WARNED_FILES:
  2990. WARNED_FILES.add(loc)
  2991. Warn("file depends on Python but is not in an ABI-specific directory:", loc)
  2992. ORIG_EXT[loc] = ext
  2993. return loc
  2994. ########################################################################
  2995. ##
  2996. ## These files maintain a python_versions.json file in the built/tmp
  2997. ## directory that can be used by the other scripts in this directory.
  2998. ##
  2999. ########################################################################
  3000. def GetCurrentPythonVersionInfo():
  3001. if PkgSkip("PYTHON"):
  3002. return
  3003. from distutils.sysconfig import get_python_lib
  3004. return {
  3005. "version": SDK["PYTHONVERSION"][6:9],
  3006. "soabi": GetPythonABI(),
  3007. "ext_suffix": GetExtensionSuffix(),
  3008. "executable": sys.executable,
  3009. "purelib": get_python_lib(False),
  3010. "platlib": get_python_lib(True),
  3011. }
  3012. def UpdatePythonVersionInfoFile(new_info):
  3013. import json
  3014. json_file = os.path.join(GetOutputDir(), "tmp", "python_versions.json")
  3015. json_data = []
  3016. if os.path.isfile(json_file) and not PkgSkip("PYTHON"):
  3017. try:
  3018. json_data = json.load(open(json_file, 'r'))
  3019. except:
  3020. json_data = []
  3021. # Prune the list by removing the entries that conflict with our build,
  3022. # plus the entries that no longer exist
  3023. for version_info in json_data[:]:
  3024. core_pyd = os.path.join(GetOutputDir(), "panda3d", "core" + version_info["ext_suffix"])
  3025. if version_info["ext_suffix"] == new_info["ext_suffix"] or \
  3026. version_info["soabi"] == new_info["soabi"] or \
  3027. not os.path.isfile(core_pyd):
  3028. json_data.remove(version_info)
  3029. if not PkgSkip("PYTHON"):
  3030. json_data.append(new_info)
  3031. if VERBOSE:
  3032. print("Writing %s" % (json_file))
  3033. json.dump(json_data, open(json_file, 'w'), indent=4)
  3034. def ReadPythonVersionInfoFile():
  3035. import json
  3036. json_file = os.path.join(GetOutputDir(), "tmp", "python_versions.json")
  3037. if os.path.isfile(json_file):
  3038. try:
  3039. return json.load(open(json_file, 'r'))
  3040. except:
  3041. pass
  3042. return []
  3043. ########################################################################
  3044. ##
  3045. ## TargetAdd
  3046. ##
  3047. ## Makepanda maintains a list of make-targets. Each target has
  3048. ## these attributes:
  3049. ##
  3050. ## name - the name of the file being created.
  3051. ## ext - the original file extension, prior to OS-specific translation
  3052. ## inputs - the names of the input files to the compiler
  3053. ## deps - other input files that the target also depends on
  3054. ## opts - compiler options, a catch-all category
  3055. ##
  3056. ## TargetAdd will create the target if it does not exist. Then,
  3057. ## depending on what options you pass, it will push data onto these
  3058. ## various target attributes. This is cumulative: for example, if
  3059. ## you use TargetAdd to add compiler options, then use TargetAdd
  3060. ## again with more compiler options, both sets of options will be
  3061. ## included.
  3062. ##
  3063. ## TargetAdd does some automatic dependency generation on C++ files.
  3064. ## It will scan these files for include-files and automatically push
  3065. ## the include files onto the list of dependencies. In order to do
  3066. ## this, it needs an include-file search path. So if you supply
  3067. ## any C++ input, you also need to supply compiler options containing
  3068. ## include-directories, or alternately, a separate ipath parameter.
  3069. ##
  3070. ## The main body of 'makepanda' is a long list of TargetAdd
  3071. ## directives building up a giant list of make targets. Then,
  3072. ## finally, the targets are run and panda is built.
  3073. ##
  3074. ## Makepanda's dependency system does not understand multiple
  3075. ## outputs from a single build step. When a build step generates
  3076. ## a primary output file and a secondary output file, it is
  3077. ## necessary to trick the dependency system. Insert a dummy
  3078. ## build step that "generates" the secondary output file, using
  3079. ## the primary output file as an input. There is a special
  3080. ## compiler option DEPENDENCYONLY that creates such a dummy
  3081. ## build-step. There are two cases where dummy build steps must
  3082. ## be inserted: bison generates an OBJ and a secondary header
  3083. ## file, interrogate generates an IN and a secondary IGATE.OBJ.
  3084. ##
  3085. ## PyTargetAdd is a special version for targets that depend on Python.
  3086. ## It will create a target for each Python version we are building with,
  3087. ## ensuring that builds with different Python versions won't conflict
  3088. ## when we build for multiple Python ABIs side-by-side.
  3089. ##
  3090. ########################################################################
  3091. class Target:
  3092. pass
  3093. TARGET_LIST = []
  3094. TARGET_TABLE = {}
  3095. def TargetAdd(target, dummy=0, opts=[], input=[], dep=[], ipath=None, winrc=None, pyabi=None):
  3096. if (dummy != 0):
  3097. exit("Syntax error in TargetAdd "+target)
  3098. if ipath is None: ipath = opts
  3099. if not ipath: ipath = []
  3100. if (type(input) == str): input = [input]
  3101. if (type(dep) == str): dep = [dep]
  3102. if target.endswith(".pyd") and not pyabi:
  3103. raise RuntimeError("Use PyTargetAdd to build .pyd targets")
  3104. full = FindLocation(target, [OUTPUTDIR + "/include"], pyabi=pyabi)
  3105. if (full not in TARGET_TABLE):
  3106. t = Target()
  3107. t.name = full
  3108. t.inputs = []
  3109. t.deps = {}
  3110. t.opts = []
  3111. TARGET_TABLE[full] = t
  3112. TARGET_LIST.append(t)
  3113. else:
  3114. t = TARGET_TABLE[full]
  3115. for x in opts:
  3116. if x not in t.opts:
  3117. t.opts.append(x)
  3118. ipath = [OUTPUTDIR + "/tmp"] + GetListOption(ipath, "DIR:") + [OUTPUTDIR+"/include"]
  3119. for x in input:
  3120. fullinput = FindLocation(x, ipath, pyabi=pyabi)
  3121. t.inputs.append(fullinput)
  3122. # Don't re-link a library or binary if just its dependency dlls have been altered.
  3123. # This should work out fine in most cases, and often reduces recompilation time.
  3124. if (os.path.splitext(x)[-1] not in SUFFIX_DLL):
  3125. t.deps[fullinput] = 1
  3126. (base,suffix) = os.path.splitext(x)
  3127. if (SUFFIX_INC.count(suffix)):
  3128. for d in CxxCalcDependencies(fullinput, ipath, []):
  3129. t.deps[d] = 1
  3130. elif suffix == '.java':
  3131. for d in JavaCalcDependencies(fullinput, OUTPUTDIR + "/classes"):
  3132. t.deps[d] = 1
  3133. # If we are linking statically, add the source DLL's dynamic dependencies.
  3134. if GetLinkAllStatic() and ORIG_EXT[fullinput] == '.lib' and fullinput in TARGET_TABLE:
  3135. tdep = TARGET_TABLE[fullinput]
  3136. for y in tdep.inputs:
  3137. if ORIG_EXT[y] == '.lib':
  3138. t.inputs.append(y)
  3139. for opt, _ in LIBNAMES + LIBDIRECTORIES + FRAMEWORKDIRECTORIES:
  3140. if opt in tdep.opts and opt not in t.opts:
  3141. t.opts.append(opt)
  3142. if x.endswith(".in"):
  3143. # Mark the _igate.cxx file as a dependency also.
  3144. outbase = os.path.basename(x)[:-3]
  3145. woutc = GetOutputDir()+"/tmp/"+outbase+"_igate.cxx"
  3146. t.deps[woutc] = 1
  3147. if target.endswith(".in"):
  3148. # Add any .N files.
  3149. base, ext = os.path.splitext(fullinput)
  3150. fulln = base + ".N"
  3151. if os.path.isfile(fulln):
  3152. t.deps[fulln] = 1
  3153. for x in dep:
  3154. fulldep = FindLocation(x, ipath, pyabi=pyabi)
  3155. t.deps[fulldep] = 1
  3156. if winrc and GetTarget() == 'windows':
  3157. TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc))
  3158. ext = os.path.splitext(target)[1]
  3159. if ext == ".in":
  3160. if not CrossCompiling():
  3161. t.deps[FindLocation("interrogate.exe", [])] = 1
  3162. t.deps[FindLocation("dtool_have_python.dat", [])] = 1
  3163. if ext in (".obj", ".tlb", ".res", ".plugin", ".app") or ext in SUFFIX_DLL or ext in SUFFIX_LIB:
  3164. t.deps[FindLocation("platform.dat", [])] = 1
  3165. if target.endswith(".obj") and any(x.endswith(".in") for x in input):
  3166. if not CrossCompiling():
  3167. t.deps[FindLocation("interrogate_module.exe", [])] = 1
  3168. if target.endswith(".pz") and not CrossCompiling():
  3169. t.deps[FindLocation("pzip.exe", [])] = 1
  3170. if target.endswith(".in"):
  3171. # Also add a target to compile the _igate.cxx file into an _igate.obj.
  3172. outbase = os.path.basename(target)[:-3]
  3173. woutc = OUTPUTDIR + "/tmp/" + outbase + "_igate.cxx"
  3174. CxxDependencyCache[woutc] = []
  3175. PyTargetAdd(outbase + "_igate.obj", opts=opts+['PYTHON','BIGOBJ'], input=woutc, dep=target)
  3176. def PyTargetAdd(target, opts=[], **kwargs):
  3177. if PkgSkip("PYTHON"):
  3178. return
  3179. if 'PYTHON' not in opts:
  3180. opts = opts + ['PYTHON']
  3181. abi = GetPythonABI()
  3182. MakeDirectory(OUTPUTDIR + "/tmp/" + abi)
  3183. # Mark this target as being a Python-specific target.
  3184. orig = CalcLocation(target, [OUTPUTDIR + "/include"])
  3185. PYABI_SPECIFIC.add(orig)
  3186. if orig.startswith(OUTPUTDIR + "/tmp/") and os.path.exists(orig):
  3187. print("Removing file %s" % (orig))
  3188. os.unlink(orig)
  3189. TargetAdd(target, opts=opts, pyabi=abi, **kwargs)