makepandacore.py 110 KB

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