makepandacore.py 99 KB

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