makepandacore.py 113 KB

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