makepandacore.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082
  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,cPickle,fnmatch,threading,Queue,signal,shutil,platform,glob,getpass,signal
  12. from distutils import sysconfig
  13. SUFFIX_INC=[".cxx",".c",".h",".I",".yxx",".lxx",".mm",".rc",".r",".plist",".idl"]
  14. SUFFIX_DLL=[".dll",".dlo",".dle",".dli",".dlm",".mll",".exe",".pyd",".ocx"]
  15. SUFFIX_LIB=[".lib",".ilb"]
  16. STARTTIME=time.time()
  17. MAINTHREAD=threading.currentThread()
  18. OUTPUTDIR="built"
  19. CUSTOM_OUTPUTDIR=False
  20. THIRDPARTYBASE=None
  21. THIRDPARTYDIR=None
  22. OPTIMIZE="3"
  23. VERBOSE=False
  24. LINK_ALL_STATIC=False
  25. # platform.architecture isn't reliable on OSX.
  26. is_64 = (sys.maxint > 0x100000000L)
  27. ########################################################################
  28. ##
  29. ## Maya and Max Version List (with registry keys)
  30. ##
  31. ########################################################################
  32. MAYAVERSIONINFO=[("MAYA6", "6.0"),
  33. ("MAYA65", "6.5"),
  34. ("MAYA7", "7.0"),
  35. ("MAYA8", "8.0"),
  36. ("MAYA85", "8.5"),
  37. ("MAYA2008","2008"),
  38. ("MAYA2009","2009"),
  39. ("MAYA2010","2010"),
  40. ("MAYA2011","2011"),
  41. ("MAYA2012","2012"),
  42. ]
  43. MAXVERSIONINFO = [("MAX6", "SOFTWARE\\Autodesk\\3DSMAX\\6.0", "installdir", "maxsdk\\cssdk\\include"),
  44. ("MAX7", "SOFTWARE\\Autodesk\\3DSMAX\\7.0", "Installdir", "maxsdk\\include\\CS"),
  45. ("MAX8", "SOFTWARE\\Autodesk\\3DSMAX\\8.0", "Installdir", "maxsdk\\include\\CS"),
  46. ("MAX9", "SOFTWARE\\Autodesk\\3DSMAX\\9.0", "Installdir", "maxsdk\\include\\CS"),
  47. ("MAX2009", "SOFTWARE\\Autodesk\\3DSMAX\\11.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  48. ("MAX2010", "SOFTWARE\\Autodesk\\3DSMAX\\12.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  49. ("MAX2011", "SOFTWARE\\Autodesk\\3DSMAX\\13.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  50. ("MAX2012", "SOFTWARE\\Autodesk\\3DSMAX\\14.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  51. ]
  52. MAYAVERSIONS=[]
  53. MAXVERSIONS=[]
  54. DXVERSIONS=["DX8","DX9"]
  55. for (ver,key) in MAYAVERSIONINFO:
  56. MAYAVERSIONS.append(ver)
  57. for (ver,key1,key2,subdir) in MAXVERSIONINFO:
  58. MAXVERSIONS.append(ver)
  59. ########################################################################
  60. ##
  61. ## Potentially Conflicting Files
  62. ##
  63. ## The next few functions can automatically move away files that
  64. ## are commonly generated by ppremake that may conflict with the
  65. ## build. When makepanda exits, those files will automatically be
  66. ## put back to their original location.
  67. ##
  68. ########################################################################
  69. CONFLICTING_FILES=["dtool/src/dtoolutil/pandaVersion.h",
  70. "dtool/src/dtoolutil/checkPandaVersion.h",
  71. "dtool/src/dtoolutil/checkPandaVersion.cxx",
  72. "dtool/src/prc/prc_parameters.h",
  73. "panda/src/speedtree/speedtree_parameters.h",
  74. "direct/src/plugin/p3d_plugin_config.h",
  75. "direct/src/plugin_activex/P3DActiveX.rc",
  76. "direct/src/plugin_npapi/nppanda3d.rc",
  77. "direct/src/plugin_standalone/panda3d.rc"]
  78. def MoveAwayConflictingFiles():
  79. for cfile in CONFLICTING_FILES:
  80. if os.path.exists(cfile):
  81. os.rename(cfile, cfile + ".moved")
  82. def MoveBackConflictingFiles():
  83. for cfile in CONFLICTING_FILES:
  84. if os.path.exists(cfile + ".moved"):
  85. os.rename(cfile + ".moved", cfile)
  86. ########################################################################
  87. ##
  88. ## The exit routine will normally
  89. ##
  90. ## - print a message
  91. ## - save the dependency cache
  92. ## - exit
  93. ##
  94. ## However, if it is invoked inside a thread, it instead:
  95. ##
  96. ## - prints a message
  97. ## - raises the "initiate-exit" exception
  98. ##
  99. ## If you create a thread, you must be prepared to catch this
  100. ## exception, save the dependency cache, and exit.
  101. ##
  102. ########################################################################
  103. WARNINGS=[]
  104. THREADS={}
  105. HAVE_COLORS=False
  106. SETF=""
  107. try:
  108. import curses
  109. curses.setupterm()
  110. SETF=curses.tigetstr("setf")
  111. if (SETF == None):
  112. SETF=curses.tigetstr("setaf")
  113. assert SETF != None
  114. HAVE_COLORS=sys.stdout.isatty()
  115. except: pass
  116. def DisableColors():
  117. global HAVE_COLORS
  118. HAVE_COLORS = False
  119. def GetColor(color = None):
  120. if not HAVE_COLORS: return ""
  121. if color != None: color = color.lower()
  122. if (color == "blue"):
  123. return curses.tparm(SETF, 1)
  124. elif (color == "green"):
  125. return curses.tparm(SETF, 2)
  126. elif (color == "cyan"):
  127. return curses.tparm(SETF, 3)
  128. elif (color == "red"):
  129. return curses.tparm(SETF, 4)
  130. elif (color == "magenta"):
  131. return curses.tparm(SETF, 5)
  132. elif (color == "yellow"):
  133. return curses.tparm(SETF, 6)
  134. else:
  135. return curses.tparm(curses.tigetstr("sgr0"))
  136. def PrettyTime(t):
  137. t = int(t)
  138. hours = t/3600
  139. t -= hours*3600
  140. minutes = t/60
  141. t -= minutes*60
  142. seconds = t
  143. if (hours): return str(hours)+" hours "+str(minutes)+" min"
  144. if (minutes): return str(minutes)+" min "+str(seconds)+" sec"
  145. return str(seconds)+" sec"
  146. def ProgressOutput(progress, msg, target = None):
  147. if (threading.currentThread() == MAINTHREAD):
  148. if (progress == None):
  149. print msg
  150. elif (progress >= 100.0):
  151. print "%s[%s%d%%%s] %s" % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"), msg),
  152. elif (progress < 10.0):
  153. print "%s[%s %d%%%s] %s" % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"), msg),
  154. else:
  155. print "%s[%s %d%%%s] %s" % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"), msg),
  156. else:
  157. global THREADS
  158. ident = threading.currentThread().ident
  159. if (ident not in THREADS):
  160. THREADS[ident] = len(THREADS) + 1
  161. print "%s[%sT%d%s] %s" % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow"), msg),
  162. if (target == None):
  163. print GetColor()
  164. else:
  165. print "%s%s%s" % (GetColor("green"), target, GetColor())
  166. def exit(msg = ""):
  167. sys.stdout.flush()
  168. sys.stderr.flush()
  169. if (threading.currentThread() == MAINTHREAD):
  170. SaveDependencyCache()
  171. MoveBackConflictingFiles()
  172. print "Elapsed Time: "+PrettyTime(time.time() - STARTTIME)
  173. print msg
  174. print GetColor("red") + "Build terminated." + GetColor()
  175. sys.stdout.flush()
  176. sys.stderr.flush()
  177. os._exit(1)
  178. else:
  179. print msg
  180. raise "initiate-exit"
  181. ########################################################################
  182. ##
  183. ## LocateBinary
  184. ##
  185. ## This function searches the system PATH for the binary. Returns its
  186. ## full path when it is found, or None when it was not found.
  187. ##
  188. ########################################################################
  189. def LocateBinary(binary):
  190. if os.path.isfile(binary):
  191. return binary
  192. if "PATH" not in os.environ or os.environ["PATH"] == "":
  193. p = os.defpath
  194. else:
  195. p = os.environ["PATH"]
  196. for path in p.split(os.pathsep):
  197. binpath = os.path.join(os.path.expanduser(path), binary)
  198. if os.access(binpath, os.X_OK):
  199. return os.path.abspath(os.path.realpath(binpath))
  200. return None
  201. ########################################################################
  202. ##
  203. ## Run a command.
  204. ##
  205. ########################################################################
  206. def oscmd(cmd, ignoreError = False):
  207. if VERBOSE:
  208. print GetColor("blue") + cmd.split(" ", 1)[0] + " " + GetColor("magenta") + cmd.split(" ", 1)[1] + GetColor()
  209. sys.stdout.flush()
  210. if sys.platform == "win32":
  211. exe = cmd.split()[0]
  212. if not (len(exe) > 4 and exe[-4:] == ".exe"):
  213. exe += ".exe"
  214. if os.path.isfile(exe)==0:
  215. for i in os.environ["PATH"].split(";"):
  216. if os.path.isfile(os.path.join(i, exe)):
  217. exe = os.path.join(i, exe)
  218. break
  219. if os.path.isfile(exe)==0:
  220. exit("Cannot find "+exe+" on search path")
  221. res = os.spawnl(os.P_WAIT, exe, cmd)
  222. else:
  223. res = os.system(cmd)
  224. sig = res & 0x7F
  225. if (GetVerbose() and res != 0):
  226. print GetColor("red") + "Process exited with exit status %d and signal code %d" % ((res & 0xFF00) >> 8, sig) + GetColor()
  227. if (sig == signal.SIGINT):
  228. exit("keyboard interrupt")
  229. # Don't ask me where the 35584 or 34304 come from...
  230. if (sig == signal.SIGSEGV or res == 35584 or res == 34304):
  231. if (LocateBinary("gdb") and GetVerbose()):
  232. print GetColor("red") + "Received SIGSEGV, retrieving traceback..." + GetColor()
  233. 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)
  234. else:
  235. print GetColor("red") + "Received SIGSEGV" + GetColor()
  236. exit("")
  237. if res != 0 and not ignoreError:
  238. if "interrogate" in cmd.split(" ", 1)[0] and GetVerbose():
  239. print GetColor("red") + "Interrogate failed, retrieving debug output..." + GetColor()
  240. os.system(cmd.split(" ", 1)[0] + " -v " + cmd.split(" ", 1)[1])
  241. exit("")
  242. return res
  243. ########################################################################
  244. ##
  245. ## GetDirectoryContents
  246. ##
  247. ## At times, makepanda will use a function like "os.listdir" to process
  248. ## all the files in a directory. Unfortunately, that means that any
  249. ## accidental addition of a file to a directory could cause makepanda
  250. ## to misbehave without warning.
  251. ##
  252. ## To alleviate this weakness, we created GetDirectoryContents. This
  253. ## uses "os.listdir" to fetch the directory contents, but then it
  254. ## compares the results to the appropriate CVS/Entries to see if
  255. ## they match. If not, it prints a big warning message.
  256. ##
  257. ########################################################################
  258. def GetDirectoryContents(dir, filters="*", skip=[]):
  259. if (type(filters)==str):
  260. filters = [filters]
  261. actual = {}
  262. files = os.listdir(dir)
  263. for filter in filters:
  264. for file in fnmatch.filter(files, filter):
  265. if (skip.count(file)==0) and (os.path.isfile(dir + "/" + file)):
  266. actual[file] = 1
  267. if (os.path.isfile(dir + "/CVS/Entries")):
  268. cvs = {}
  269. srchandle = open(dir+"/CVS/Entries", "r")
  270. files = []
  271. for line in srchandle:
  272. if (line[0]=="/"):
  273. s = line.split("/",2)
  274. if (len(s)==3):
  275. files.append(s[1])
  276. srchandle.close()
  277. for filter in filters:
  278. for file in fnmatch.filter(files, filter):
  279. if (skip.count(file)==0):
  280. cvs[file] = 1
  281. for file in actual.keys():
  282. if (file not in cvs and VERBOSE):
  283. msg = "%sWARNING: %s is in %s, but not in CVS%s" % (GetColor("red"), GetColor("green") + file + GetColor(), GetColor("green") + dir + GetColor(), GetColor())
  284. print msg
  285. WARNINGS.append(msg)
  286. for file in cvs.keys():
  287. if (file not in actual and VERBOSE):
  288. msg = "%sWARNING: %s is not in %s, but is in CVS%s" % (GetColor("red"), GetColor("green") + file + GetColor(), GetColor("green") + dir + GetColor(), GetColor())
  289. print msg
  290. WARNINGS.append(msg)
  291. results = actual.keys()
  292. results.sort()
  293. return results
  294. def GetDirectorySize(dir):
  295. size = 0
  296. for (path, dirs, files) in os.walk(dir):
  297. for file in files:
  298. try:
  299. size += os.path.getsize(os.path.join(path, file))
  300. except: pass
  301. return size
  302. ########################################################################
  303. ##
  304. ## The Timestamp Cache
  305. ##
  306. ## The make utility is constantly fetching the timestamps of files.
  307. ## This can represent the bulk of the file accesses during the make
  308. ## process. The timestamp cache eliminates redundant checks.
  309. ##
  310. ########################################################################
  311. TIMESTAMPCACHE = {}
  312. def GetTimestamp(path):
  313. if path in TIMESTAMPCACHE:
  314. return TIMESTAMPCACHE[path]
  315. try: date = os.path.getmtime(path)
  316. except: date = 0
  317. TIMESTAMPCACHE[path] = date
  318. return date
  319. def ClearTimestamp(path):
  320. del TIMESTAMPCACHE[path]
  321. ########################################################################
  322. ##
  323. ## The Dependency cache.
  324. ##
  325. ## Makepanda's strategy for file dependencies is different from most
  326. ## make-utilities. Whenever a file is built, makepanda records
  327. ## that the file was built, and it records what the input files were,
  328. ## and what their dates were. Whenever a file is about to be built,
  329. ## panda compares the current list of input files and their dates,
  330. ## to the previous list of input files and their dates. If they match,
  331. ## there is no need to build the file.
  332. ##
  333. ########################################################################
  334. BUILTFROMCACHE = {}
  335. def JustBuilt(files,others):
  336. dates = []
  337. for file in files:
  338. del TIMESTAMPCACHE[file]
  339. dates.append(GetTimestamp(file))
  340. for file in others:
  341. dates.append(GetTimestamp(file))
  342. key = tuple(files)
  343. BUILTFROMCACHE[key] = [others,dates]
  344. def NeedsBuild(files,others):
  345. dates = []
  346. for file in files:
  347. dates.append(GetTimestamp(file))
  348. if (not os.path.exists(file)): return 1
  349. for file in others:
  350. dates.append(GetTimestamp(file))
  351. key = tuple(files)
  352. if (key in BUILTFROMCACHE):
  353. if (BUILTFROMCACHE[key] == [others,dates]):
  354. return 0
  355. else:
  356. oldothers = BUILTFROMCACHE[key][0]
  357. if (oldothers != others and VERBOSE):
  358. print "%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), str(files), GetColor())
  359. return 1
  360. ########################################################################
  361. ##
  362. ## The CXX include cache:
  363. ##
  364. ## The following routine scans a CXX file and returns a list of
  365. ## the include-directives inside that file. It's not recursive:
  366. ## it just returns the includes that are textually inside the
  367. ## file. If you need recursive dependencies, you need the higher-level
  368. ## routine CxxCalcDependencies, defined elsewhere.
  369. ##
  370. ## Since scanning a CXX file is slow, we cache the result. It records
  371. ## the date of the source file and the list of includes that it
  372. ## contains. It assumes that if the file date hasn't changed, that
  373. ## the list of include-statements inside the file has not changed
  374. ## either. Once again, this particular routine does not return
  375. ## recursive dependencies --- it only returns an explicit list of
  376. ## include statements that are textually inside the file. That
  377. ## is what the cache stores, as well.
  378. ##
  379. ########################################################################
  380. CXXINCLUDECACHE = {}
  381. global CxxIncludeRegex
  382. CxxIncludeRegex = re.compile('^[ \t]*[#][ \t]*include[ \t]+"([^"]+)"[ \t\r\n]*$')
  383. def CxxGetIncludes(path):
  384. date = GetTimestamp(path)
  385. if (path in CXXINCLUDECACHE):
  386. cached = CXXINCLUDECACHE[path]
  387. if (cached[0]==date): return cached[1]
  388. try: sfile = open(path, 'rb')
  389. except:
  390. exit("Cannot open source file \""+path+"\" for reading.")
  391. include = []
  392. for line in sfile:
  393. match = CxxIncludeRegex.match(line,0)
  394. if (match):
  395. incname = match.group(1)
  396. include.append(incname)
  397. sfile.close()
  398. CXXINCLUDECACHE[path] = [date, include]
  399. return include
  400. ########################################################################
  401. ##
  402. ## SaveDependencyCache / LoadDependencyCache
  403. ##
  404. ## This actually saves both the dependency and cxx-include caches.
  405. ##
  406. ########################################################################
  407. DCACHE_BACKED_UP = False
  408. def SaveDependencyCache():
  409. global DCACHE_BACKED_UP
  410. if not DCACHE_BACKED_UP:
  411. try:
  412. if (os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"))):
  413. os.rename(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),
  414. os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup"))
  415. except: pass
  416. DCACHE_BACKED_UP = True
  417. try: icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb')
  418. except: icache = 0
  419. if (icache!=0):
  420. print "Storing dependency cache."
  421. cPickle.dump(CXXINCLUDECACHE, icache, 1)
  422. cPickle.dump(BUILTFROMCACHE, icache, 1)
  423. icache.close()
  424. def LoadDependencyCache():
  425. global CXXINCLUDECACHE
  426. global BUILTFROMCACHE
  427. try: icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'rb')
  428. except: icache = 0
  429. if (icache!=0):
  430. CXXINCLUDECACHE = cPickle.load(icache)
  431. BUILTFROMCACHE = cPickle.load(icache)
  432. icache.close()
  433. ########################################################################
  434. ##
  435. ## CxxFindSource: given a source file name and a directory list,
  436. ## searches the directory list for the given source file. Returns
  437. ## the full pathname of the located file.
  438. ##
  439. ## CxxFindHeader: given a source file, an include directive, and a
  440. ## directory list, searches the directory list for the given header
  441. ## file. Returns the full pathname of the located file.
  442. ##
  443. ## Of course, CxxFindSource and CxxFindHeader cannot find a source
  444. ## file that has not been created yet. This can cause dependency
  445. ## problems. So the function CreateStubHeader can be used to create
  446. ## a file that CxxFindSource or CxxFindHeader can subsequently find.
  447. ##
  448. ########################################################################
  449. def CxxFindSource(name, ipath):
  450. for dir in ipath:
  451. if (dir == "."): full = name
  452. else: full = dir + "/" + name
  453. if GetTimestamp(full) > 0: return full
  454. exit("Could not find source file: "+name)
  455. def CxxFindHeader(srcfile, incfile, ipath):
  456. if (incfile.startswith(".")):
  457. last = srcfile.rfind("/")
  458. if (last < 0): exit("CxxFindHeader cannot handle this case #1")
  459. srcdir = srcfile[:last+1]
  460. while (incfile[:1]=="."):
  461. if (incfile[:2]=="./"):
  462. incfile = incfile[2:]
  463. elif (incfile[:3]=="../"):
  464. incfile = incfile[3:]
  465. last = srcdir[:-1].rfind("/")
  466. if (last < 0): exit("CxxFindHeader cannot handle this case #2")
  467. srcdir = srcdir[:last+1]
  468. else: exit("CxxFindHeader cannot handle this case #3")
  469. full = srcdir + incfile
  470. if GetTimestamp(full) > 0: return full
  471. return 0
  472. else:
  473. for dir in ipath:
  474. full = dir + "/" + incfile
  475. if GetTimestamp(full) > 0: return full
  476. return 0
  477. ########################################################################
  478. ##
  479. ## CxxCalcDependencies(srcfile, ipath, ignore)
  480. ##
  481. ## Calculate the dependencies of a source file given a
  482. ## particular include-path. Any file in the list of files to
  483. ## ignore is not considered.
  484. ##
  485. ########################################################################
  486. global CxxIgnoreHeader
  487. global CxxDependencyCache
  488. CxxIgnoreHeader = {}
  489. CxxDependencyCache = {}
  490. def CxxCalcDependencies(srcfile, ipath, ignore):
  491. if (srcfile in CxxDependencyCache):
  492. return CxxDependencyCache[srcfile]
  493. if (ignore.count(srcfile)): return []
  494. dep = {}
  495. dep[srcfile] = 1
  496. includes = CxxGetIncludes(srcfile)
  497. for include in includes:
  498. header = CxxFindHeader(srcfile, include, ipath)
  499. if (header!=0):
  500. if (ignore.count(header)==0):
  501. hdeps = CxxCalcDependencies(header, ipath, [srcfile]+ignore)
  502. for x in hdeps: dep[x] = 1
  503. result = dep.keys()
  504. CxxDependencyCache[srcfile] = result
  505. return result
  506. ########################################################################
  507. ##
  508. ## Registry Key Handling
  509. ##
  510. ## Of course, these routines will fail if you call them on a
  511. ## non win32 platform. If you use them on a win64 platform, they
  512. ## will look in the win32 private hive first, then look in the
  513. ## win64 hive.
  514. ##
  515. ########################################################################
  516. if sys.platform == "win32":
  517. import _winreg
  518. def TryRegistryKey(path):
  519. try:
  520. key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path, 0, _winreg.KEY_READ)
  521. return key
  522. except: pass
  523. try:
  524. key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path, 0, _winreg.KEY_READ | 256)
  525. return key
  526. except: pass
  527. return 0
  528. def ListRegistryKeys(path):
  529. result=[]
  530. index=0
  531. key = TryRegistryKey(path)
  532. if (key != 0):
  533. try:
  534. while (1):
  535. result.append(_winreg.EnumKey(key, index))
  536. index = index + 1
  537. except: pass
  538. _winreg.CloseKey(key)
  539. return result
  540. def ListRegistryValues(path):
  541. result = []
  542. index = 0
  543. key = TryRegistryKey(path)
  544. if (key != 0):
  545. try:
  546. while (1):
  547. result.append(_winreg.EnumValue(key, index)[0])
  548. index = index + 1
  549. except: pass
  550. _winreg.CloseKey(key)
  551. return result
  552. def GetRegistryKey(path, subkey, override64=True):
  553. if (is_64 and override64==True):
  554. path = path.replace("SOFTWARE\\", "SOFTWARE\\Wow6432Node\\")
  555. k1=0
  556. key = TryRegistryKey(path)
  557. if (key != 0):
  558. try:
  559. k1, k2 = _winreg.QueryValueEx(key, subkey)
  560. except: pass
  561. _winreg.CloseKey(key)
  562. return k1
  563. def GetProgramFiles():
  564. if ("PROGRAMFILES" in os.environ):
  565. return os.environ["PROGRAMFILES"]
  566. elif (os.path.isdir("C:\\Program Files")):
  567. return "C:\\Program Files"
  568. elif (os.path.isdir("D:\\Program Files")):
  569. return "D:\\Program Files"
  570. elif (os.path.isdir("E:\\Program Files")):
  571. return "E:\\Program Files"
  572. return 0
  573. ########################################################################
  574. ##
  575. ## Parsing Compiler Option Lists
  576. ##
  577. ########################################################################
  578. def GetListOption(opts, prefix):
  579. res=[]
  580. for x in opts:
  581. if (x.startswith(prefix)):
  582. res.append(x[len(prefix):])
  583. return res
  584. def GetValueOption(opts, prefix):
  585. for x in opts:
  586. if (x.startswith(prefix)):
  587. return x[len(prefix):]
  588. return 0
  589. def GetOptimizeOption(opts):
  590. val = GetValueOption(opts, "OPT:")
  591. if (val == 0):
  592. return OPTIMIZE
  593. return val
  594. ########################################################################
  595. ##
  596. ## General File Manipulation
  597. ##
  598. ########################################################################
  599. def MakeDirectory(path):
  600. if os.path.isdir(path): return 0
  601. os.mkdir(path)
  602. def ReadFile(wfile):
  603. try:
  604. srchandle = open(wfile, "rb")
  605. data = srchandle.read()
  606. srchandle.close()
  607. return data
  608. except: exit("Cannot read "+wfile)
  609. def WriteFile(wfile,data):
  610. try:
  611. dsthandle = open(wfile, "wb")
  612. dsthandle.write(data)
  613. dsthandle.close()
  614. except: exit("Cannot write "+wfile)
  615. def ConditionalWriteFile(dest,desiredcontents):
  616. try:
  617. rfile = open(dest, 'rb')
  618. contents = rfile.read(-1)
  619. rfile.close()
  620. except:
  621. contents=0
  622. if contents != desiredcontents:
  623. sys.stdout.flush()
  624. WriteFile(dest,desiredcontents)
  625. def DeleteCVS(dir):
  626. if dir == "": dir = "."
  627. for entry in os.listdir(dir):
  628. subdir = os.path.join(dir, entry)
  629. if (os.path.isdir(subdir)):
  630. if (entry == "CVS" or entry == "CVSROOT"):
  631. shutil.rmtree(subdir)
  632. else:
  633. DeleteCVS(subdir)
  634. elif (os.path.isfile(subdir) and (entry == ".cvsignore" or entry.startswith(".#"))):
  635. os.remove(subdir)
  636. def DeleteBuildFiles(dir):
  637. if dir == "": dir = "."
  638. for entry in os.listdir(dir):
  639. subdir = os.path.join(dir, entry)
  640. if (os.path.isfile(subdir) and os.path.splitext(subdir)[-1] in [".pp", ".moved"]):
  641. os.remove(subdir)
  642. elif (os.path.isdir(subdir)):
  643. if (os.path.basename(subdir)[:3] == "Opt" and os.path.basename(subdir)[4] == "-"):
  644. shutil.rmtree(subdir)
  645. else:
  646. DeleteBuildFiles(subdir)
  647. def DeleteEmptyDirs(dir):
  648. if dir == "": dir = "."
  649. entries = os.listdir(dir)
  650. if not entries:
  651. os.rmdir(dir)
  652. return
  653. for entry in entries:
  654. subdir = os.path.join(dir, entry)
  655. if (os.path.isdir(subdir)):
  656. if (not os.listdir(subdir)):
  657. os.rmdir(subdir)
  658. else:
  659. DeleteEmptyDirs(subdir)
  660. def CreateFile(file):
  661. if (os.path.exists(file)==0):
  662. WriteFile(file,"")
  663. ########################################################################
  664. #
  665. # Create the panda build tree.
  666. #
  667. ########################################################################
  668. def MakeBuildTree():
  669. MakeDirectory(OUTPUTDIR)
  670. MakeDirectory(OUTPUTDIR+"/bin")
  671. MakeDirectory(OUTPUTDIR+"/lib")
  672. MakeDirectory(OUTPUTDIR+"/tmp")
  673. MakeDirectory(OUTPUTDIR+"/etc")
  674. MakeDirectory(OUTPUTDIR+"/plugins")
  675. MakeDirectory(OUTPUTDIR+"/include")
  676. MakeDirectory(OUTPUTDIR+"/models")
  677. MakeDirectory(OUTPUTDIR+"/models/audio")
  678. MakeDirectory(OUTPUTDIR+"/models/audio/sfx")
  679. MakeDirectory(OUTPUTDIR+"/models/icons")
  680. MakeDirectory(OUTPUTDIR+"/models/maps")
  681. MakeDirectory(OUTPUTDIR+"/models/misc")
  682. MakeDirectory(OUTPUTDIR+"/models/gui")
  683. MakeDirectory(OUTPUTDIR+"/pandac")
  684. MakeDirectory(OUTPUTDIR+"/pandac/input")
  685. ########################################################################
  686. #
  687. # Make sure that you are in the root of the panda tree.
  688. #
  689. ########################################################################
  690. def CheckPandaSourceTree():
  691. dir = os.getcwd()
  692. if ((os.path.exists(os.path.join(dir, "makepanda/makepanda.py"))==0) or
  693. (os.path.exists(os.path.join(dir, "dtool","src","dtoolbase","dtoolbase.h"))==0) or
  694. (os.path.exists(os.path.join(dir, "panda","src","pandabase","pandabase.h"))==0)):
  695. exit("Current directory is not the root of the panda tree.")
  696. ########################################################################
  697. ##
  698. ## Thirdparty libraries paths
  699. ##
  700. ########################################################################
  701. def GetThirdpartyBase():
  702. global THIRDPARTYBASE
  703. if (THIRDPARTYBASE != None):
  704. return THIRDPARTYBASE
  705. THIRDPARTYBASE = "thirdparty"
  706. if "MAKEPANDA_THIRDPARTY" in os.environ:
  707. THIRDPARTYBASE = os.environ["MAKEPANDA_THIRDPARTY"]
  708. return THIRDPARTYBASE
  709. def GetThirdpartyDir():
  710. global THIRDPARTYDIR
  711. if (THIRDPARTYDIR != None):
  712. return THIRDPARTYDIR
  713. if (sys.platform.startswith("win")):
  714. if (is_64):
  715. THIRDPARTYDIR=GetThirdpartyBase()+"/win-libs-vc9-x64/"
  716. else:
  717. THIRDPARTYDIR=GetThirdpartyBase()+"/win-libs-vc9/"
  718. if not os.path.isdir(THIRDPARTYDIR):
  719. THIRDPARTYDIR=GetThirdpartyBase()+"/win-libs-vc9/"
  720. elif (sys.platform == "darwin"):
  721. THIRDPARTYDIR=GetThirdpartyBase()+"/darwin-libs-a/"
  722. elif (sys.platform.startswith("linux")):
  723. if (platform.machine().startswith("arm")):
  724. THIRDPARTYDIR=GetThirdpartyBase()+"/linux-libs-arm/"
  725. elif (is_64):
  726. THIRDPARTYDIR=GetThirdpartyBase()+"/linux-libs-x64/"
  727. else:
  728. THIRDPARTYDIR=GetThirdpartyBase()+"/linux-libs-a/"
  729. elif (sys.platform.startswith("freebsd")):
  730. if (platform.machine().startswith("arm")):
  731. THIRDPARTYDIR=GetThirdpartyBase()+"/freebsd-libs-arm/"
  732. elif (is_64):
  733. THIRDPARTYDIR=GetThirdpartyBase()+"/freebsd-libs-x64/"
  734. else:
  735. THIRDPARTYDIR=GetThirdpartyBase()+"/freebsd-libs-a/"
  736. else:
  737. print GetColor("red") + "WARNING:" + GetColor("Unsupported platform: " + sys.platform)
  738. return THIRDPARTYDIR
  739. ########################################################################
  740. ##
  741. ## Visual Studio Manifest Manipulation.
  742. ## These functions exist to make sure we are referencing the same
  743. ## version of the VC runtime in the manifests that we are shipping
  744. ## with Panda3D, to avoid side-by-side configuration errors. Also,
  745. ## it also removes any dependency the VC80 CRT (as we only want to
  746. ## depend on the VC90 CRT).
  747. ##
  748. ########################################################################
  749. VC90CRTVERSIONRE=re.compile("name=['\"]Microsoft.VC90.CRT['\"]\\s+version=['\"]([0-9.]+)['\"]")
  750. VC80CRTASSEMBLYRE=re.compile("<dependency>[\t \r\n]*<dependentAssembly>[\t \r\n]*<assemblyIdentity[\t \r\na-zA-Z0-9.'\"=]*name=['\"]Microsoft[.]VC80[.]CRT['\"][\t \r\na-zA-Z0-9.'\"=/]*>[\t \r\n]*(</assemblyIdentity>)?[\t \r\n]*</dependentAssembly>[\t \r\n]*</dependency>[\t \r\n]*")
  751. VC90CRTVERSION=None
  752. def GetVC90CRTVersion(fn = None):
  753. global VC90CRTVERSION
  754. if (VC90CRTVERSION != None):
  755. return VC90CRTVERSION
  756. if (not sys.platform.startswith("win")):
  757. VC90CRTVERSION = 0
  758. return 0
  759. if (fn == None):
  760. fn = GetThirdpartyDir()+"extras/bin/Microsoft.VC90.CRT.manifest"
  761. manifest = ReadFile(fn)
  762. version = VC90CRTVERSIONRE.search(manifest)
  763. if (version == None):
  764. exit("Cannot locate version number in "+fn)
  765. VC90CRTVERSION = version.group(1)
  766. return version.group(1)
  767. def SetVC90CRTVersion(fn, ver = None):
  768. if (ver == None): ver = GetVC90CRTVersion()
  769. manifest = ReadFile(fn)
  770. subst = " name='Microsoft.VC90.CRT' version='"+ver+"' "
  771. manifest = VC90CRTVERSIONRE.sub(subst, manifest)
  772. manifest = VC80CRTASSEMBLYRE.sub("", manifest)
  773. WriteFile(fn, manifest)
  774. ########################################################################
  775. ##
  776. ## Gets or sets the output directory, by default "built".
  777. ## Gets or sets the optimize level.
  778. ## Gets or sets the verbose flag.
  779. ##
  780. ########################################################################
  781. def GetOutputDir():
  782. return OUTPUTDIR
  783. def IsCustomOutputDir():
  784. return CUSTOM_OUTPUTDIR
  785. def SetOutputDir(outputdir):
  786. global OUTPUTDIR, CUSTOM_OUTPUTDIR
  787. OUTPUTDIR=outputdir
  788. CUSTOM_OUTPUTDIR=True
  789. def GetOptimize():
  790. return int(OPTIMIZE)
  791. def SetOptimize(optimize):
  792. global OPTIMIZE
  793. OPTIMIZE=optimize
  794. def GetVerbose():
  795. return VERBOSE
  796. def SetVerbose(verbose):
  797. global VERBOSE
  798. VERBOSE=verbose
  799. def GetLinkAllStatic():
  800. return LINK_ALL_STATIC
  801. def SetLinkAllStatic(val = True):
  802. global LINK_ALL_STATIC
  803. LINK_ALL_STATIC = val
  804. def UnsetLinkAllStatic():
  805. global LINK_ALL_STATIC
  806. LINK_ALL_STATIC = False
  807. ########################################################################
  808. ##
  809. ## Package Selection
  810. ##
  811. ## This facility enables makepanda to keep a list of packages selected
  812. ## by the user for inclusion or omission.
  813. ##
  814. ########################################################################
  815. PKG_LIST_ALL=[]
  816. PKG_LIST_OMIT={}
  817. def PkgListSet(pkgs):
  818. global PKG_LIST_ALL
  819. global PKG_LIST_OMIT
  820. PKG_LIST_ALL=pkgs
  821. PKG_LIST_OMIT={}
  822. PkgEnableAll()
  823. def PkgListGet():
  824. return PKG_LIST_ALL
  825. def PkgEnableAll():
  826. for x in PKG_LIST_ALL:
  827. PKG_LIST_OMIT[x] = 0
  828. def PkgDisableAll():
  829. for x in PKG_LIST_ALL:
  830. PKG_LIST_OMIT[x] = 1
  831. def PkgEnable(pkg):
  832. PKG_LIST_OMIT[pkg] = 0
  833. def PkgDisable(pkg):
  834. PKG_LIST_OMIT[pkg] = 1
  835. def PkgSkip(pkg):
  836. return PKG_LIST_OMIT[pkg]
  837. def PkgSelected(pkglist, pkg):
  838. if (pkglist.count(pkg)==0): return 0
  839. if (PKG_LIST_OMIT[pkg]): return 0
  840. return 1
  841. ########################################################################
  842. ##
  843. ## DTOOL/PRC Option value override
  844. ##
  845. ## This facility enables makepanda to keep a list of parameters
  846. ## overriden by the command line.
  847. ##
  848. ########################################################################
  849. OVERRIDES_LIST={}
  850. def AddOverride(spec):
  851. if (spec.find("=")==-1):return
  852. pair = spec.split("=",1)
  853. OVERRIDES_LIST[pair[0]] = pair[1]
  854. def OverrideValue(parameter, value):
  855. if parameter in OVERRIDES_LIST:
  856. print "Overriding value of key \"" + parameter + "\" with value \"" + OVERRIDES_LIST[parameter] + "\""
  857. return OVERRIDES_LIST[parameter]
  858. else:
  859. return value
  860. ########################################################################
  861. ##
  862. ## These functions are for libraries which use pkg-config.
  863. ##
  864. ########################################################################
  865. def PkgConfigHavePkg(pkgname, tool = "pkg-config"):
  866. """Returns a bool whether the pkg-config package is installed."""
  867. if (sys.platform == "win32" or not LocateBinary(tool)):
  868. return False
  869. if (tool == "pkg-config"):
  870. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --modversion " + pkgname)
  871. else:
  872. return bool(LocateBinary(tool) != None)
  873. result = handle.read().strip()
  874. returnval = handle.close()
  875. if returnval != None and returnval != 0:
  876. return False
  877. return bool(len(result) > 0)
  878. def PkgConfigGetLibs(pkgname, tool = "pkg-config"):
  879. """Returns a list of libs for the package, prefixed by -l."""
  880. if (sys.platform == "win32" or not LocateBinary(tool)):
  881. return []
  882. if (tool == "pkg-config"):
  883. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-l " + pkgname)
  884. elif (tool == "fltk-config"):
  885. handle = os.popen(LocateBinary("fltk-config") + " --ldstaticflags")
  886. else:
  887. handle = os.popen(LocateBinary(tool) + " --libs")
  888. result = handle.read().strip()
  889. handle.close()
  890. libs = []
  891. for l in result.split(" "):
  892. if l.startswith("-l") or l.startswith("/"):
  893. libs.append(l)
  894. return libs
  895. def PkgConfigGetIncDirs(pkgname, tool = "pkg-config"):
  896. """Returns a list of includes for the package, NOT prefixed by -I."""
  897. if (sys.platform == "win32" or not LocateBinary(tool)):
  898. return []
  899. if (tool == "pkg-config"):
  900. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags-only-I " + pkgname)
  901. else:
  902. handle = os.popen(LocateBinary(tool) + " --cflags")
  903. result = handle.read().strip()
  904. if len(result) == 0: return []
  905. handle.close()
  906. libs = []
  907. for l in result.split(" "):
  908. if (l.startswith("-I")):
  909. libs.append(l.replace("-I", "").replace("\"", "").strip())
  910. return libs
  911. def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"):
  912. """Returns a list of library paths for the package, NOT prefixed by -L."""
  913. if (sys.platform == "win32" or not LocateBinary(tool)):
  914. return []
  915. if (tool == "pkg-config"):
  916. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname)
  917. elif (tool == "wx-config"):
  918. return []
  919. else:
  920. handle = os.popen(LocateBinary(tool) + " --ldflags")
  921. result = handle.read().strip()
  922. handle.close()
  923. if len(result) == 0: return []
  924. libs = []
  925. for l in result.split(" "):
  926. if (l.startswith("-L")):
  927. libs.append(l.replace("-L", "").replace("\"", "").strip())
  928. return libs
  929. def PkgConfigGetDefSymbols(pkgname, tool = "pkg-config"):
  930. """Returns a dictionary of preprocessor definitions."""
  931. if (sys.platform == "win32" or not LocateBinary(tool)):
  932. return []
  933. if (tool == "pkg-config"):
  934. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags " + pkgname)
  935. else:
  936. handle = os.popen(LocateBinary(tool) + " --cflags")
  937. result = handle.read().strip()
  938. handle.close()
  939. if len(result) == 0: return {}
  940. defs = {}
  941. for l in result.split(" "):
  942. if (l.startswith("-D")):
  943. d = l.replace("-D", "").replace("\"", "").strip().split("=")
  944. if (len(d) == 1):
  945. defs[d[0]] = ""
  946. else:
  947. defs[d[0]] = d[1]
  948. return defs
  949. def PkgConfigEnable(opt, pkgname, tool = "pkg-config"):
  950. """Adds the libraries and includes to IncDirectory, LibName and LibDirectory."""
  951. for i in PkgConfigGetIncDirs(pkgname, tool):
  952. IncDirectory(opt, i)
  953. for i in PkgConfigGetLibDirs(pkgname, tool):
  954. LibDirectory(opt, i)
  955. for i in PkgConfigGetLibs(pkgname, tool):
  956. LibName(opt, i)
  957. for i, j in PkgConfigGetDefSymbols(pkgname, tool).items():
  958. DefSymbol(opt, i, j)
  959. LD_CACHE = None
  960. STATIC_CACHE = None
  961. def GetLibCache():
  962. # Returns a list of cached libraries, not prefixed by lib and not suffixed by .so* or .a!
  963. global LD_CACHE
  964. if (LD_CACHE == None):
  965. LD_CACHE = []
  966. print "Generating library cache..."
  967. if (LocateBinary("ldconfig") != None and not sys.platform.startswith("freebsd")):
  968. handle = os.popen(LocateBinary("ldconfig") + " -NXp")
  969. result = handle.read().strip().split("\n")
  970. for line in result:
  971. lib = line.strip().split(" ", 1)[0]
  972. if (lib.endswith(".so") or ".so " in lib):
  973. lib = lib.split(".so", 1)[0][3:]
  974. LD_CACHE.append(lib)
  975. libdirs = ["/lib", "/usr/lib", "/usr/local/lib", "/usr/PCBSD/local/lib", "/usr/X11/lib", "/usr/X11R6/lib"]
  976. if is_64:
  977. libdirs += ["/lib64", "/usr/lib64"]
  978. if "LD_LIBRARY_PATH" in os.environ:
  979. libdirs += os.environ["LD_LIBRARY_PATH"].split(":")
  980. libdirs = list(set(libdirs))
  981. libs = []
  982. for path in libdirs:
  983. if os.path.isdir(path):
  984. libs += glob.glob(path + "/lib*.so")
  985. libs += glob.glob(path + "/lib*.a")
  986. if (sys.platform == "darwin"):
  987. libs += glob.glob(path + "/lib*.dylib")
  988. for l in libs:
  989. lib = os.path.basename(l).split(".so", 1)[0].split(".a", 1)[0].split(".dylib", 1)[0][3:]
  990. if lib not in LD_CACHE:
  991. LD_CACHE.append(lib)
  992. return LD_CACHE
  993. def ChooseLib(*libs):
  994. # Chooses a library from the parameters, in order of preference. Returns the first if none of them were found.
  995. for l in libs:
  996. libname = l
  997. if (l.startswith("lib")):
  998. libname = l[3:]
  999. if (libname in GetLibCache()):
  1000. return libname
  1001. if (len(libs) > 0):
  1002. if (VERBOSE):
  1003. print GetColor("cyan") + "Couldn't find any of the libraries " + ", ".join(libs) + GetColor()
  1004. return libs[0]
  1005. def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None, framework = None, target_pkg = None, tool = "pkg-config"):
  1006. global PKG_LIST_ALL
  1007. if (pkg in PkgListGet() and PkgSkip(pkg)):
  1008. return
  1009. if (target_pkg == "" or target_pkg == None):
  1010. target_pkg = pkg
  1011. if (pkgconfig == ""):
  1012. pkgconfig = None
  1013. if (framework == ""):
  1014. framework = None
  1015. if (libs == None or libs == ""):
  1016. libs = ()
  1017. elif (isinstance(libs, str)):
  1018. libs = (libs, )
  1019. if (incs == None or incs == ""):
  1020. incs = ()
  1021. elif (isinstance(incs, str)):
  1022. incs = (incs, )
  1023. if (defs == None or defs == "" or len(defs) == 0):
  1024. defs = {}
  1025. elif (isinstance(incs, str)):
  1026. defs = {defs : ""}
  1027. elif (isinstance(incs, list) or isinstance(incs, tuple) or isinstance(incs, set)):
  1028. olddefs = defs
  1029. defs = {}
  1030. for d in olddefs:
  1031. defs[d] = ""
  1032. if (pkg.lower() == "swscale" and os.path.isfile(GetThirdpartyDir() + "ffmpeg/include/libswscale/swscale.h")):
  1033. # Let it be handled by the ffmpeg package
  1034. LibName(target_pkg, "-lswscale")
  1035. return
  1036. if (os.path.isdir(GetThirdpartyDir() + pkg.lower())):
  1037. IncDirectory(target_pkg, GetThirdpartyDir() + pkg.lower() + "/include")
  1038. LibDirectory(target_pkg, GetThirdpartyDir() + pkg.lower() + "/lib")
  1039. # TODO: check for a .pc file in the lib/pkg-config/ dir
  1040. if (tool != None and os.path.isfile(GetThirdpartyDir() + pkg.lower() + "/bin/" + tool)):
  1041. tool = GetThirdpartyDir() + pkg.lower() + "/bin/" + tool
  1042. for i in PkgConfigGetLibs(None, tool):
  1043. LibName(target_pkg, i)
  1044. for i, j in PkgConfigGetDefSymbols(None, tool).items():
  1045. DefSymbol(target_pkg, i, j)
  1046. return
  1047. for l in libs:
  1048. libname = l
  1049. if (l.startswith("lib")):
  1050. libname = l[3:]
  1051. # This is for backward compatibility - in the thirdparty dir, we kept some libs with "panda" prefix, like libpandatiff.
  1052. if (len(glob.glob(GetThirdpartyDir() + pkg.lower() + "/lib/libpanda%s.*" % libname)) > 0 and
  1053. len(glob.glob(GetThirdpartyDir() + pkg.lower() + "/lib/lib%s.*" % libname)) == 0):
  1054. libname = "panda" + libname
  1055. LibName(target_pkg, "-l" + libname)
  1056. for d, v in defs.values():
  1057. DefSymbol(target_pkg, d, v)
  1058. return
  1059. elif (sys.platform == "darwin" and framework != None):
  1060. if (os.path.isdir("/Library/Frameworks/%s.framework" % framework) or
  1061. os.path.isdir("/System/Library/Frameworks/%s.framework" % framework) or
  1062. os.path.isdir("/Developer/Library/Frameworks/%s.framework" % framework) or
  1063. os.path.isdir("/Users/%s/System/Library/Frameworks/%s.framework" % (getpass.getuser(), framework))):
  1064. LibName(target_pkg, "-framework " + framework)
  1065. for d, v in defs.values():
  1066. DefSymbol(target_pkg, d, v)
  1067. elif (pkg in PkgListGet()):
  1068. print "%sWARNING:%s Could not locate framework %s, excluding from build" % (GetColor("red"), GetColor(), framework)
  1069. PkgDisable(pkg)
  1070. else:
  1071. print "%sERROR:%s Could not locate framework %s, aborting build" % (GetColor("red"), GetColor(), framework)
  1072. exit()
  1073. return
  1074. elif (LocateBinary(tool) != None and (tool != "pkg-config" or pkgconfig != None)):
  1075. if (isinstance(pkgconfig, str) or tool != "pkg-config"):
  1076. if (PkgConfigHavePkg(pkgconfig, tool)):
  1077. return PkgConfigEnable(target_pkg, pkgconfig, tool)
  1078. else:
  1079. have_all_pkgs = True
  1080. for pc in pkgconfig:
  1081. if (PkgConfigHavePkg(pc, tool)):
  1082. PkgConfigEnable(target_pkg, pc, tool)
  1083. else:
  1084. have_all_pkgs = False
  1085. if (have_all_pkgs):
  1086. return
  1087. if (pkgconfig != None and (libs == None or len(libs) == 0)):
  1088. if (pkg in PkgListGet()):
  1089. print "%sWARNING:%s Could not locate pkg-config package %s, excluding from build" % (GetColor("red"), GetColor(), pkgconfig)
  1090. PkgDisable(pkg)
  1091. else:
  1092. print "%sERROR:%s Could not locate pkg-config package %s, aborting build" % (GetColor("red"), GetColor(), pkgconfig)
  1093. exit()
  1094. else:
  1095. # Okay, our pkg-config attempts failed. Let's try locating the libs by ourselves.
  1096. have_pkg = True
  1097. for l in libs:
  1098. libname = l
  1099. if (l.startswith("lib")):
  1100. libname = l[3:]
  1101. if (libname in GetLibCache()):
  1102. LibName(target_pkg, "-l" + libname)
  1103. else:
  1104. if (VERBOSE):
  1105. print GetColor("cyan") + "Couldn't find library lib" + libname + GetColor()
  1106. have_pkg = False
  1107. for i in incs:
  1108. incdir = None
  1109. if (len(glob.glob("/usr/include/" + i)) > 0):
  1110. incdir = sorted(glob.glob("/usr/include/" + i))[-1]
  1111. elif (len(glob.glob("/usr/local/include/" + i)) > 0):
  1112. incdir = sorted(glob.glob("/usr/local/include/" + i))[-1]
  1113. elif (os.path.isdir("/usr/PCBSD") and len(glob.glob("/usr/PCBSD/local/include/" + i)) > 0):
  1114. incdir = sorted(glob.glob("/usr/PCBSD/local/include/" + i))[-1]
  1115. else:
  1116. have_pkg = False
  1117. # Try searching in the package's IncDirectories.
  1118. for ppkg, pdir in INCDIRECTORIES:
  1119. if (pkg == ppkg and len(glob.glob(os.path.join(pdir, i))) > 0):
  1120. incdir = sorted(glob.glob(os.path.join(pdir, i)))[-1]
  1121. have_pkg = True
  1122. if (incdir == None and VERBOSE and i.endswith(".h")):
  1123. print GetColor("cyan") + "Couldn't find header file " + i + GetColor()
  1124. # Note: It's possible to specify a file instead of a dir, for the sake of checking if it exists.
  1125. if (incdir != None and os.path.isdir(incdir)):
  1126. IncDirectory(target_pkg, incdir)
  1127. if (not have_pkg):
  1128. if (pkg in PkgListGet()):
  1129. print "%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), pkg.lower())
  1130. PkgDisable(pkg)
  1131. else:
  1132. print "%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), pkg.lower())
  1133. exit()
  1134. ########################################################################
  1135. ##
  1136. ## SDK Location
  1137. ##
  1138. ## This section is concerned with locating the install directories
  1139. ## for various third-party packages. The results are stored in the
  1140. ## SDK table.
  1141. ##
  1142. ## Microsoft keeps changing the &*#$*& registry key for the DirectX SDK.
  1143. ## The only way to reliably find it is to search through the installer's
  1144. ## uninstall-directories, look in each one, and see if it contains the
  1145. ## relevant files.
  1146. ##
  1147. ########################################################################
  1148. SDK = {}
  1149. def GetSdkDir(sdkname, sdkkey = None):
  1150. # Returns the default SDK directory. If it exists,
  1151. # and sdkkey is not None, it is put in SDK[sdkkey].
  1152. # Note: return value may not be an existing path.
  1153. sdkbase = "sdks"
  1154. if "MAKEPANDA_SDKS" in os.environ:
  1155. sdkbase = os.environ["MAKEPANDA_SDKS"]
  1156. sdir = sdkbase[:]
  1157. if (sys.platform.startswith("win")):
  1158. sdir += "/win"
  1159. sdir += platform.architecture()[0][:2]
  1160. elif (sys.platform.startswith("linux")):
  1161. sdir += "/linux"
  1162. sdir += platform.architecture()[0][:2]
  1163. elif (sys.platform == "darwin"):
  1164. sdir += "/macosx"
  1165. sdir += "/" + sdkname
  1166. # If it does not exist, try the old location.
  1167. if (not os.path.isdir(sdir)):
  1168. sdir = sdkbase + "/" + sdir
  1169. if (sys.platform.startswith("linux")):
  1170. sdir += "-linux"
  1171. sdir += platform.architecture()[0][:2]
  1172. elif (sys.platform == "darwin"):
  1173. sdir += "-osx"
  1174. if (sdkkey and os.path.isdir(sdir)):
  1175. SDK[sdkkey] = sdir
  1176. return sdir
  1177. def SdkLocateDirectX():
  1178. if (sys.platform != "win32"): return
  1179. GetSdkDir("directx8", "DX8")
  1180. GetSdkDir("directx9", "DX9")
  1181. ## We first try to locate the August SDK in 64 bits, then 32.
  1182. if ("DX9" not in SDK):
  1183. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1184. if (dir != 0):
  1185. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1186. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1187. if ("DX9" not in SDK):
  1188. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1189. if (dir != 0):
  1190. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1191. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1192. if ("DX9" not in SDK):
  1193. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1194. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1195. if (dir != 0):
  1196. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1197. archStr = "x86"
  1198. if (is_64): archStr = "x64"
  1199. if ("DX9" not in SDK) or ("DX8" not in SDK):
  1200. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
  1201. for subdir in ListRegistryKeys(uninstaller):
  1202. if (subdir[0]=="{"):
  1203. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1204. if (dir != 0):
  1205. if (("DX8" not in SDK) and
  1206. (os.path.isfile(dir+"\\Include\\d3d8.h")) and
  1207. (os.path.isfile(dir+"\\Include\\d3dx8.h")) and
  1208. (os.path.isfile(dir+"\\Lib\\d3d8.lib")) and
  1209. (os.path.isfile(dir+"\\Lib\\d3dx8.lib"))):
  1210. SDK["DX8"] = dir.replace("\\", "/").rstrip("/")
  1211. if (("DX9" not in SDK) and
  1212. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1213. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1214. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1215. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1216. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1217. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1218. if ("DX9" in SDK):
  1219. SDK["DIRECTCAM"] = SDK["DX9"]
  1220. def SdkLocateMaya():
  1221. for (ver,key) in MAYAVERSIONINFO:
  1222. if (PkgSkip(ver)==0 and ver not in SDK):
  1223. GetSdkDir(ver.lower().replace("x",""), ver)
  1224. if (not ver in SDK):
  1225. if (sys.platform == "win32"):
  1226. for dev in ["Alias|Wavefront","Alias","Autodesk"]:
  1227. fullkey="SOFTWARE\\"+dev+"\\Maya\\"+key+"\\Setup\\InstallPath"
  1228. res = GetRegistryKey(fullkey, "MAYA_INSTALL_LOCATION", override64=False)
  1229. if (res != 0):
  1230. res = res.replace("\\", "/").rstrip("/")
  1231. SDK[ver] = res
  1232. elif (sys.platform == "darwin"):
  1233. ddir = "/Applications/Autodesk/maya"+key
  1234. if (os.path.isdir(ddir)): SDK[ver] = ddir
  1235. else:
  1236. if (is_64):
  1237. ddir1 = "/usr/autodesk/maya"+key+"-x64"
  1238. ddir2 = "/usr/aw/maya"+key+"-x64"
  1239. else:
  1240. ddir1 = "/usr/autodesk/maya"+key
  1241. ddir2 = "/usr/aw/maya"+key
  1242. if (os.path.isdir(ddir1)): SDK[ver] = ddir1
  1243. elif (os.path.isdir(ddir2)): SDK[ver] = ddir2
  1244. def SdkLocateMax():
  1245. if (sys.platform != "win32"): return
  1246. for version,key1,key2,subdir in MAXVERSIONINFO:
  1247. if (PkgSkip(version)==0):
  1248. if (version not in SDK):
  1249. GetSdkDir("maxsdk"+version.lower()[3:], version)
  1250. GetSdkDir("maxsdk"+version.lower()[3:], version+"CS")
  1251. if (not version in SDK):
  1252. top = GetRegistryKey(key1,key2)
  1253. if (top != 0):
  1254. SDK[version] = top + "maxsdk"
  1255. if (os.path.isdir(top + "\\" + subdir)!=0):
  1256. SDK[version+"CS"] = top + subdir
  1257. def SdkLocatePython(force_use_sys_executable = False):
  1258. if (PkgSkip("PYTHON")==0):
  1259. if (sys.platform == "win32" and not force_use_sys_executable):
  1260. SDK["PYTHON"] = GetThirdpartyBase()+"/win-python"
  1261. if (GetOptimize() <= 2):
  1262. SDK["PYTHON"] += "-dbg"
  1263. if (is_64 and os.path.isdir(SDK["PYTHON"] + "-x64")):
  1264. SDK["PYTHON"] += "-x64"
  1265. SDK["PYTHONEXEC"] = SDK["PYTHON"] + "/python"
  1266. if (GetOptimize() <= 2): SDK["PYTHONEXEC"] += "_d.exe"
  1267. else: SDK["PYTHONEXEC"] += ".exe"
  1268. if (not os.path.isfile(SDK["PYTHONEXEC"])):
  1269. exit("Could not find %s!" % SDK["PYTHONEXEC"])
  1270. os.system(SDK["PYTHONEXEC"].replace("/", "\\") + " -V > "+OUTPUTDIR+"/tmp/pythonversion 2>&1")
  1271. pv=ReadFile(OUTPUTDIR+"/tmp/pythonversion")
  1272. if (pv.startswith("Python ")==0):
  1273. exit("python -V did not produce the expected output")
  1274. pv = pv[7:10]
  1275. SDK["PYTHONVERSION"]="python"+pv
  1276. elif (sys.platform == "win32"):
  1277. SDK["PYTHON"] = os.path.dirname(sysconfig.get_python_inc())
  1278. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1279. SDK["PYTHONEXEC"] = sys.executable
  1280. else:
  1281. SDK["PYTHON"] = sysconfig.get_python_inc()
  1282. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1283. if (os.path.islink(sys.executable)):
  1284. SDK["PYTHONEXEC"] = os.path.join(os.path.dirname(sys.executable), os.readlink(sys.executable))
  1285. else:
  1286. SDK["PYTHONEXEC"] = sys.executable
  1287. elif (os.path.islink(sys.executable)):
  1288. SDK["PYTHONEXEC"] = os.path.join(os.path.dirname(sys.executable), os.readlink(sys.executable))
  1289. else:
  1290. SDK["PYTHONEXEC"] = sys.executable
  1291. def SdkLocateVisualStudio():
  1292. if (sys.platform != "win32"): return
  1293. vcdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", "9.0")
  1294. if (vcdir != 0) and (vcdir[-4:] == "\\VC\\"):
  1295. vcdir = vcdir[:-3]
  1296. SDK["VISUALSTUDIO"] = vcdir
  1297. elif "VCINSTALLDIR" in os.environ:
  1298. vcdir = os.environ["VCINSTALLDIR"]
  1299. if (vcdir[-3:] == "\\VC"):
  1300. vcdir = vcdir[:-2]
  1301. elif (vcdir[-4:] == "\\VC\\"):
  1302. vcdir = vcdir[:-3]
  1303. SDK["VISUALSTUDIO"] = vcdir
  1304. def SdkLocateMSPlatform():
  1305. if (sys.platform != "win32"): return
  1306. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.0", "InstallationFolder")
  1307. if (platsdk):
  1308. if os.path.isdir(platsdk):
  1309. print "Windows 7 SDK detected. Enabling special features (multi-touch)."
  1310. else:
  1311. platsdk = 0
  1312. if (platsdk == 0):
  1313. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\MicrosoftSDK\\InstalledSDKs\\D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1", "Install Dir")
  1314. if (platsdk and not os.path.isdir(platsdk)): platsdk = 0
  1315. if (platsdk == 0):
  1316. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.1","InstallationFolder")
  1317. if (platsdk and not os.path.isdir(platsdk)): platsdk = 0
  1318. if (platsdk == 0):
  1319. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v6.0A","InstallationFolder")
  1320. if (platsdk and not os.path.isdir(platsdk)): platsdk = 0
  1321. if (platsdk == 0 and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2"))):
  1322. if (not is_64 or os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2", "Lib", "AMD64"))):
  1323. platsdk = os.path.join(GetProgramFiles(), "Microsoft Platform SDK for Windows Server 2003 R2")
  1324. if (not os.path.isdir(platsdk)): platsdk = 0
  1325. # Doesn't work with the Express versions, so we're checking for the "atlmfc" dir, which is not in the Express
  1326. if (platsdk == 0 and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Visual Studio 9\\VC\\atlmfc"))
  1327. and os.path.isdir(os.path.join(GetProgramFiles(), "Microsoft Visual Studio 9\\VC\\PlatformSDK"))):
  1328. platsdk = os.path.join(GetProgramFiles(), "Microsoft Visual Studio 9\\VC\\PlatformSDK")
  1329. if (not os.path.isdir(platsdk)): platsdk = 0
  1330. # This may not be the best idea but it does give a warning
  1331. if (platsdk == 0):
  1332. if ("WindowsSdkDir" in os.environ):
  1333. WARNINGS.append("Windows SDK directory not found in registry, found in Environment variables instead")
  1334. platsdk = os.environ["WindowsSdkDir"]
  1335. if (platsdk != 0):
  1336. if (not platsdk.endswith("\\")):
  1337. platsdk += "\\"
  1338. SDK["MSPLATFORM"] = platsdk
  1339. def SdkLocateMacOSX(osxtarget=None):
  1340. if (sys.platform != "darwin"): return
  1341. if (osxtarget != None):
  1342. if (os.path.exists("/Developer/SDKs/MacOSX%su.sdk" % osxtarget)):
  1343. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%su.sdk" % osxtarget
  1344. elif (os.path.exists("/Developer/SDKs/MacOSX%s.sdk" % osxtarget)):
  1345. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%s.sdk" % osxtarget
  1346. elif (os.path.exists("/Developer/SDKs/MacOSX%s.0.sdk" % osxtarget)):
  1347. SDK["MACOSX"] = "/Developer/SDKs/MacOSX%s.0.sdk" % osxtarget
  1348. else:
  1349. exit("Couldn't find any MacOSX SDK for OSX version %s!" % osxtarget)
  1350. else:
  1351. SDK["MACOSX"] = ""
  1352. # Latest first
  1353. PHYSXVERSIONINFO=[
  1354. ("PHYSX284","v2.8.4"),
  1355. ("PHYSX283","v2.8.3"),
  1356. ("PHYSX281","v2.8.1"),
  1357. ]
  1358. def SdkLocatePhysX():
  1359. # First check for a physx directory in sdks.
  1360. dir = GetSdkDir("physx")
  1361. if (dir and os.path.isdir(dir)):
  1362. SDK["PHYSX"] = dir
  1363. SDK["PHYSXLIBS"] = dir + "/lib"
  1364. return
  1365. # Try to find a PhysX installation on the system.
  1366. for (ver, key) in PHYSXVERSIONINFO:
  1367. if (sys.platform == "win32"):
  1368. folders = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders"
  1369. for folder in ListRegistryValues(folders):
  1370. if folder.endswith("NVIDIA PhysX SDK\\%s\\SDKs\\" % key) or \
  1371. folder.endswith("NVIDIA PhysX SDK\\%s_win\\SDKs\\" % key):
  1372. SDK["PHYSX"] = folder
  1373. return
  1374. elif (sys.platform.startswith("linux")):
  1375. incpath = "/usr/include/PhysX/%s/SDKs" % key
  1376. libpath = "/usr/lib/PhysX/%s" % key
  1377. if (os.path.isdir(incpath) and os.path.isdir(libpath)):
  1378. SDK["PHYSX"] = incpath
  1379. SDK["PHYSXLIBS"] = libpath
  1380. return
  1381. def SdkLocateSpeedTree():
  1382. # Look for all of the SpeedTree SDK directories within the
  1383. # sdks/win32/speedtree dir, and pick the highest-numbered one.
  1384. dir = GetSdkDir("speedtree")
  1385. if not os.path.exists(dir):
  1386. return
  1387. speedtrees = []
  1388. for dirname in os.listdir(dir):
  1389. if dirname.startswith('SpeedTree SDK v'):
  1390. version = dirname[15:].split()[0]
  1391. version = map(int, version.split('.'))
  1392. speedtrees.append((version, dirname))
  1393. if not speedtrees:
  1394. # No installed SpeedTree SDK.
  1395. return
  1396. speedtrees.sort()
  1397. version, dirname = speedtrees[-1]
  1398. SDK["SPEEDTREE"] = os.path.join(dir, dirname)
  1399. SDK["SPEEDTREEAPI"] = "OpenGL"
  1400. SDK["SPEEDTREEVERSION"] = '%s.%s' % (version[0], version[1])
  1401. ########################################################################
  1402. ##
  1403. ## SDK Auto-Disables
  1404. ##
  1405. ## Disable packages whose SDKs could not be found.
  1406. ##
  1407. ########################################################################
  1408. def SdkAutoDisableDirectX():
  1409. for ver in ["DX8","DX9","DIRECTCAM"]:
  1410. if (PkgSkip(ver)==0):
  1411. if (ver not in SDK):
  1412. if (sys.platform.startswith("win")):
  1413. WARNINGS.append("I cannot locate SDK for "+ver)
  1414. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  1415. PkgDisable(ver)
  1416. else:
  1417. WARNINGS.append("Using "+ver+" sdk: "+SDK[ver])
  1418. def SdkAutoDisableMaya():
  1419. for (ver,key) in MAYAVERSIONINFO:
  1420. if (ver not in SDK) and (PkgSkip(ver)==0):
  1421. if (sys.platform == "win32"):
  1422. WARNINGS.append("The registry does not appear to contain a pointer to the "+ver+" SDK.")
  1423. else:
  1424. WARNINGS.append("I cannot locate SDK for "+ver)
  1425. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  1426. PkgDisable(ver)
  1427. def SdkAutoDisableMax():
  1428. for version,key1,key2,subdir in MAXVERSIONINFO:
  1429. if (PkgSkip(version)==0) and ((version not in SDK) or (version+"CS" not in SDK)):
  1430. if (sys.platform.startswith("win")):
  1431. if (version in SDK):
  1432. WARNINGS.append("Your copy of "+version+" does not include the character studio SDK")
  1433. else:
  1434. WARNINGS.append("The registry does not appear to contain a pointer to "+version)
  1435. WARNINGS.append("I have automatically added this command-line option: --no-"+version.lower())
  1436. PkgDisable(version)
  1437. def SdkAutoDisablePhysX():
  1438. if ("PHYSX" not in SDK) and (PkgSkip("PHYSX")==0):
  1439. PkgDisable("PHYSX")
  1440. WARNINGS.append("I cannot locate SDK for PhysX")
  1441. WARNINGS.append("I have automatically added this command-line option: --no-physx")
  1442. def SdkAutoDisableSpeedTree():
  1443. if ("SPEEDTREE" not in SDK) and (PkgSkip("SPEEDTREE")==0):
  1444. PkgDisable("SPEEDTREE")
  1445. WARNINGS.append("I cannot locate SDK for SpeedTree")
  1446. WARNINGS.append("I have automatically added this command-line option: --no-speedtree")
  1447. ########################################################################
  1448. ##
  1449. ## Visual Studio comes with a script called VSVARS32.BAT, which
  1450. ## you need to run before using visual studio command-line tools.
  1451. ## The following python subroutine serves the same purpose.
  1452. ##
  1453. ########################################################################
  1454. def AddToPathEnv(path,add):
  1455. if (path in os.environ):
  1456. if (sys.platform.startswith("win")):
  1457. os.environ[path] = add + ";" + os.environ[path]
  1458. else:
  1459. os.environ[path] = add + ":" + os.environ[path]
  1460. else:
  1461. os.environ[path] = add
  1462. def SetupVisualStudioEnviron():
  1463. if ("VISUALSTUDIO" not in SDK):
  1464. exit("Could not find Visual Studio install directory")
  1465. if ("MSPLATFORM" not in SDK):
  1466. exit("Could not find the Microsoft Platform SDK")
  1467. os.environ["VCINSTALLDIR"] = SDK["VISUALSTUDIO"] + "VC"
  1468. os.environ["WindowsSdkDir"] = SDK["MSPLATFORM"]
  1469. suffix=""
  1470. if (is_64): suffix = "\\amd64"
  1471. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "VC\\bin"+suffix)
  1472. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "Common7\\IDE")
  1473. AddToPathEnv("INCLUDE", SDK["VISUALSTUDIO"] + "VC\\include")
  1474. AddToPathEnv("INCLUDE", SDK["VISUALSTUDIO"] + "VC\\atlmfc\\include")
  1475. AddToPathEnv("LIB", SDK["VISUALSTUDIO"] + "VC\\lib"+suffix)
  1476. AddToPathEnv("LIB", SDK["VISUALSTUDIO"] + "VC\\atlmfc\\lib")
  1477. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin")
  1478. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include")
  1479. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\atl")
  1480. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\mfc")
  1481. if (not is_64):
  1482. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib")
  1483. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC90.CRT")
  1484. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC90.MFC")
  1485. elif (os.path.isdir(SDK["MSPLATFORM"] + "lib\\x64")):
  1486. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\x64")
  1487. elif (os.path.isdir(SDK["MSPLATFORM"] + "lib\\amd64")):
  1488. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\amd64")
  1489. else:
  1490. exit("Could not locate 64-bits libraries in Platform SDK!")
  1491. ########################################################################
  1492. #
  1493. # Include and Lib directories.
  1494. #
  1495. # These allow you to add include and lib directories to the
  1496. # compiler search paths. These methods accept a "package"
  1497. # parameter, which specifies which package the directory is
  1498. # associated with. The include/lib directory is not used
  1499. # if the package is not selected. The package can be 'ALWAYS'.
  1500. #
  1501. ########################################################################
  1502. INCDIRECTORIES = []
  1503. LIBDIRECTORIES = []
  1504. LIBNAMES = []
  1505. DEFSYMBOLS = []
  1506. def IncDirectory(opt, dir):
  1507. INCDIRECTORIES.append((opt, dir))
  1508. def LibDirectory(opt, dir):
  1509. LIBDIRECTORIES.append((opt, dir))
  1510. def LibName(opt, name):
  1511. # Check to see if the lib file actually exists for the thirdparty library given
  1512. # Are we a thirdparty library?
  1513. if name.startswith(GetThirdpartyDir()):
  1514. # Does this lib exist?
  1515. if not os.path.exists(name):
  1516. WARNINGS.append(name + " not found. Skipping Package " + opt)
  1517. if (opt in PkgListGet()):
  1518. print "%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), opt.lower())
  1519. PkgDisable(opt)
  1520. return
  1521. else:
  1522. print "%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), opt.lower())
  1523. exit()
  1524. LIBNAMES.append((opt, name))
  1525. def DefSymbol(opt, sym, val):
  1526. DEFSYMBOLS.append((opt, sym, val))
  1527. ########################################################################
  1528. #
  1529. # On Linux/OSX, to run panda, the dynamic linker needs to know how to
  1530. # find the shared libraries. This subroutine verifies that the dynamic
  1531. # linker is properly configured. If not, it sets it up on a temporary
  1532. # basis and issues a warning.
  1533. #
  1534. ########################################################################
  1535. def CheckLinkerLibraryPath():
  1536. if (sys.platform == "win32"): return
  1537. builtlib = os.path.abspath(os.path.join(OUTPUTDIR,"lib"))
  1538. dyldpath = []
  1539. try:
  1540. ldpath = []
  1541. f = file("/etc/ld.so.conf","r")
  1542. for line in f: ldpath.append(line.rstrip())
  1543. f.close()
  1544. except: ldpath = []
  1545. # Get the current
  1546. if ("LD_LIBRARY_PATH" in os.environ):
  1547. ldpath = ldpath + os.environ["LD_LIBRARY_PATH"].split(":")
  1548. if (sys.platform == "darwin" and "DYLD_LIBRARY_PATH" in os.environ):
  1549. dyldpath = os.environ["DYLD_LIBRARY_PATH"].split(":")
  1550. # Remove any potential current Panda installation lib dirs
  1551. for i in ldpath:
  1552. if i.startswith("/usr/lib/panda"): ldpath.remove(i)
  1553. for i in ldpath:
  1554. if i.startswith("/usr/local/panda"): ldpath.remove(i)
  1555. for i in dyldpath:
  1556. if i.startswith("/Applications/Panda3D"): dyldpath.remove(i)
  1557. if i.startswith("/Developer/Panda3D"): dyldpath.remove(i)
  1558. # Add built/lib/ to (DY)LD_LIBRARY_PATH if it's not already there
  1559. if (ldpath.count(builtlib)==0):
  1560. if ("LD_LIBRARY_PATH" in os.environ):
  1561. os.environ["LD_LIBRARY_PATH"] = builtlib + ":" + os.environ["LD_LIBRARY_PATH"]
  1562. else:
  1563. os.environ["LD_LIBRARY_PATH"] = builtlib
  1564. if (sys.platform == "darwin" and dyldpath.count(builtlib)==0):
  1565. if ("DYLD_LIBRARY_PATH" in os.environ):
  1566. os.environ["DYLD_LIBRARY_PATH"] = builtlib + ":" + os.environ["DYLD_LIBRARY_PATH"]
  1567. else:
  1568. os.environ["DYLD_LIBRARY_PATH"] = builtlib
  1569. # Workaround around compile issue on PCBSD
  1570. if (os.path.exists("/usr/PCBSD")):
  1571. os.environ["LD_LIBRARY_PATH"] += ":/usr/PCBSD/local/lib"
  1572. ########################################################################
  1573. ##
  1574. ## Routines to copy files into the build tree
  1575. ##
  1576. ########################################################################
  1577. def CopyFile(dstfile,srcfile):
  1578. if (dstfile[-1]=='/'):
  1579. dstdir = dstfile
  1580. fnl = srcfile.rfind("/")
  1581. if (fnl < 0): fn = srcfile
  1582. else: fn = srcfile[fnl+1:]
  1583. dstfile = dstdir + fn
  1584. if (NeedsBuild([dstfile],[srcfile])):
  1585. WriteFile(dstfile,ReadFile(srcfile))
  1586. JustBuilt([dstfile], [srcfile])
  1587. def CopyAllFiles(dstdir, srcdir, suffix=""):
  1588. for x in GetDirectoryContents(srcdir, ["*"+suffix]):
  1589. CopyFile(dstdir+x, srcdir+x)
  1590. def CopyAllHeaders(dir, skip=[]):
  1591. for filename in GetDirectoryContents(dir, ["*.h", "*.I", "*.T"], skip):
  1592. srcfile = dir + "/" + filename
  1593. dstfile = OUTPUTDIR+"/include/" + filename
  1594. if (NeedsBuild([dstfile],[srcfile])):
  1595. WriteFile(dstfile,ReadFile(srcfile))
  1596. JustBuilt([dstfile],[srcfile])
  1597. def CopyTree(dstdir,srcdir):
  1598. if (os.path.isdir(dstdir)): return 0
  1599. if (sys.platform == "win32"):
  1600. cmd = 'xcopy /I/Y/E/Q "' + srcdir + '" "' + dstdir + '"'
  1601. else:
  1602. cmd = 'cp -R -f ' + srcdir + ' ' + dstdir
  1603. oscmd(cmd)
  1604. ########################################################################
  1605. ##
  1606. ## Parse PandaVersion.pp to extract the version number.
  1607. ##
  1608. ########################################################################
  1609. def ParsePandaVersion(fn):
  1610. try:
  1611. f = file(fn, "r")
  1612. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  1613. for line in f:
  1614. match = pattern.match(line,0)
  1615. if (match):
  1616. f.close()
  1617. return match.group(1)+"."+match.group(2)+"."+match.group(3)
  1618. f.close()
  1619. except: pass
  1620. return "0.0.0"
  1621. def ParsePluginVersion(fn):
  1622. try:
  1623. f = file(fn, "r")
  1624. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_PLUGIN_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  1625. for line in f:
  1626. match = pattern.match(line,0)
  1627. if (match):
  1628. f.close()
  1629. return match.group(1)+"."+match.group(2)+"."+match.group(3)
  1630. f.close()
  1631. except: pass
  1632. return "0.0.0"
  1633. def ParseCoreapiVersion(fn):
  1634. try:
  1635. f = file(fn, "r")
  1636. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_COREAPI_VERSION.*([0-9]+)[ \t]*$')
  1637. for line in f:
  1638. match = pattern.match(line,0)
  1639. if (match):
  1640. f.close()
  1641. return match.group(1)
  1642. f.close()
  1643. except: pass
  1644. return "0"
  1645. ##########################################################################################
  1646. #
  1647. # Utility function to generate a resource file
  1648. #
  1649. ##########################################################################################
  1650. RESOURCE_FILE_TEMPLATE = """VS_VERSION_INFO VERSIONINFO
  1651. FILEVERSION %(commaversion)s
  1652. PRODUCTVERSION %(commaversion)s
  1653. FILEFLAGSMASK 0x3fL
  1654. FILEFLAGS %(debugflag)s
  1655. FILEOS 0x40004L
  1656. FILETYPE 0x2L
  1657. FILESUBTYPE 0x0L
  1658. BEGIN
  1659. BLOCK "StringFileInfo"
  1660. BEGIN
  1661. BLOCK "040904e4"
  1662. BEGIN
  1663. VALUE "FileDescription", "%(description)s\\0"
  1664. VALUE "FileVersion", "%(dotversion)s"
  1665. VALUE "LegalTrademarks", "\\0"
  1666. VALUE "MIMEType", "%(mimetype)s\\0"
  1667. VALUE "FileExtents", "%(extension)s\\0"
  1668. VALUE "FileOpenName", "%(filedesc)s\\0"
  1669. VALUE "OLESelfRegister", "\\0"
  1670. VALUE "OriginalFilename", "%(filename)s\\0"
  1671. VALUE "ProductName", "%(name)s %(version)s\\0"
  1672. VALUE "ProductVersion", "%(dotversion)s"
  1673. END
  1674. END
  1675. BLOCK "VarFileInfo"
  1676. BEGIN
  1677. VALUE "Translation", 0x409, 1252
  1678. END
  1679. END
  1680. """
  1681. def GenerateResourceFile(**kwargs):
  1682. if "debugflag" not in kwargs:
  1683. if GetOptimize() <= 2:
  1684. kwargs["debugflag"] = "0x1L"
  1685. else:
  1686. kwargs["debugflag"] = "0x0L"
  1687. kwargs["dotversion"] = kwargs["version"]
  1688. if len(kwargs["dotversion"].split(".")) == 3:
  1689. kwargs["dotversion"] += ".0"
  1690. if "commaversion" not in kwargs:
  1691. kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
  1692. rcdata = ""
  1693. if not "noinclude" in kwargs:
  1694. rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
  1695. rcdata += "#include \"winresrc.h\"\n"
  1696. rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
  1697. rcdata += RESOURCE_FILE_TEMPLATE % kwargs
  1698. if "icon" in kwargs:
  1699. rcdata += "\nICON_FILE ICON \"%s\"\n" % kwargs["icon"]
  1700. return rcdata
  1701. def WriteResourceFile(basename, **kwargs):
  1702. if not basename.endswith(".rc"):
  1703. basename += ".rc"
  1704. basename = GetOutputDir() + "/include/" + basename
  1705. ConditionalWriteFile(basename, GenerateResourceFile(**kwargs))
  1706. return basename
  1707. ########################################################################
  1708. ##
  1709. ## FindLocation
  1710. ##
  1711. ########################################################################
  1712. ORIG_EXT={}
  1713. def GetOrigExt(x):
  1714. return ORIG_EXT[x]
  1715. def SetOrigExt(x, v):
  1716. ORIG_EXT[x] = v
  1717. def CalcLocation(fn, ipath):
  1718. if (fn.count("/")): return fn
  1719. dllext = ""
  1720. if (GetOptimize() <= 2 and sys.platform.startswith("win")): dllext = "_d"
  1721. if (fn == "PandaModules.py"): return "pandac/" + fn
  1722. if (fn.endswith(".cxx")): return CxxFindSource(fn, ipath)
  1723. if (fn.endswith(".I")): return CxxFindSource(fn, ipath)
  1724. if (fn.endswith(".h")): return CxxFindSource(fn, ipath)
  1725. if (fn.endswith(".c")): return CxxFindSource(fn, ipath)
  1726. if (fn.endswith(".yxx")): return CxxFindSource(fn, ipath)
  1727. if (fn.endswith(".lxx")): return CxxFindSource(fn, ipath)
  1728. if (fn.endswith(".pdef")):return CxxFindSource(fn, ipath)
  1729. if (fn.endswith(".egg")): return OUTPUTDIR+"/models/"+fn
  1730. if (fn.endswith(".egg.pz")):return OUTPUTDIR+"/models/"+fn
  1731. if (sys.platform.startswith("win")):
  1732. if (fn.endswith(".def")): return CxxFindSource(fn, ipath)
  1733. if (fn.endswith(".rc")): return CxxFindSource(fn, ipath)
  1734. if (fn.endswith(".idl")): return CxxFindSource(fn, ipath)
  1735. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn
  1736. if (fn.endswith(".res")): return OUTPUTDIR+"/tmp/"+fn
  1737. if (fn.endswith(".tlb")): return OUTPUTDIR+"/tmp/"+fn
  1738. if (fn.endswith(".dll")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".dll"
  1739. if (fn.endswith(".pyd")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".pyd"
  1740. if (fn.endswith(".ocx")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".ocx"
  1741. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".mll"
  1742. if (fn.endswith(".dlo")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dlo"
  1743. if (fn.endswith(".dli")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dli"
  1744. if (fn.endswith(".dle")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dle"
  1745. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".dll"
  1746. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn
  1747. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+dllext+".lib"
  1748. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+dllext+".lib"
  1749. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  1750. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  1751. elif (sys.platform == "darwin"):
  1752. if (fn.endswith(".mm")): return CxxFindSource(fn, ipath)
  1753. if (fn.endswith(".r")): return CxxFindSource(fn, ipath)
  1754. if (fn.endswith(".plist")): return CxxFindSource(fn, ipath)
  1755. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  1756. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  1757. if (fn.endswith(".pyd")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  1758. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  1759. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  1760. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  1761. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  1762. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  1763. if (fn.endswith(".rsrc")): return OUTPUTDIR+"/tmp/"+fn
  1764. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn
  1765. if (fn.endswith(".app")): return OUTPUTDIR+"/bin/"+fn
  1766. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  1767. else:
  1768. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  1769. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  1770. if (fn.endswith(".pyd")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  1771. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  1772. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  1773. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  1774. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  1775. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  1776. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  1777. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  1778. return fn
  1779. def FindLocation(fn, ipath):
  1780. if (GetLinkAllStatic() and fn.endswith(".dll")):
  1781. fn = fn[:-4]+".lib"
  1782. loc = CalcLocation(fn, ipath)
  1783. (base,ext) = os.path.splitext(fn)
  1784. ORIG_EXT[loc] = ext
  1785. return loc
  1786. ########################################################################
  1787. ##
  1788. ## TargetAdd
  1789. ##
  1790. ## Makepanda maintains a list of make-targets. Each target has
  1791. ## these attributes:
  1792. ##
  1793. ## name - the name of the file being created.
  1794. ## ext - the original file extension, prior to OS-specific translation
  1795. ## inputs - the names of the input files to the compiler
  1796. ## deps - other input files that the target also depends on
  1797. ## opts - compiler options, a catch-all category
  1798. ##
  1799. ## TargetAdd will create the target if it does not exist. Then,
  1800. ## depending on what options you pass, it will push data onto these
  1801. ## various target attributes. This is cumulative: for example, if
  1802. ## you use TargetAdd to add compiler options, then use TargetAdd
  1803. ## again with more compiler options, both sets of options will be
  1804. ## included.
  1805. ##
  1806. ## TargetAdd does some automatic dependency generation on C++ files.
  1807. ## It will scan these files for include-files and automatically push
  1808. ## the include files onto the list of dependencies. In order to do
  1809. ## this, it needs an include-file search path. So if you supply
  1810. ## any C++ input, you also need to supply compiler options containing
  1811. ## include-directories, or alternately, a separate ipath parameter.
  1812. ##
  1813. ## The main body of 'makepanda' is a long list of TargetAdd
  1814. ## directives building up a giant list of make targets. Then,
  1815. ## finally, the targets are run and panda is built.
  1816. ##
  1817. ## Makepanda's dependency system does not understand multiple
  1818. ## outputs from a single build step. When a build step generates
  1819. ## a primary output file and a secondary output file, it is
  1820. ## necessary to trick the dependency system. Insert a dummy
  1821. ## build step that "generates" the secondary output file, using
  1822. ## the primary output file as an input. There is a special
  1823. ## compiler option DEPENDENCYONLY that creates such a dummy
  1824. ## build-step. There are two cases where dummy build steps must
  1825. ## be inserted: bison generates an OBJ and a secondary header
  1826. ## file, interrogate generates an IN and a secondary IGATE.OBJ.
  1827. ##
  1828. ########################################################################
  1829. class Target:
  1830. pass
  1831. TARGET_LIST=[]
  1832. TARGET_TABLE={}
  1833. def TargetAdd(target, dummy=0, opts=0, input=0, dep=0, ipath=0, winrc=0):
  1834. if (dummy != 0):
  1835. exit("Syntax error in TargetAdd "+target)
  1836. if (ipath == 0): ipath = opts
  1837. if (ipath == 0): ipath = []
  1838. if (type(input) == str): input = [input]
  1839. if (type(dep) == str): dep = [dep]
  1840. full = FindLocation(target,[OUTPUTDIR+"/include"])
  1841. if (full not in TARGET_TABLE):
  1842. t = Target()
  1843. t.name = full
  1844. t.inputs = []
  1845. t.deps = {}
  1846. t.opts = []
  1847. TARGET_TABLE[full] = t
  1848. TARGET_LIST.append(t)
  1849. else:
  1850. t = TARGET_TABLE[full]
  1851. ipath = [OUTPUTDIR+"/tmp"] + GetListOption(ipath, "DIR:") + [OUTPUTDIR+"/include"]
  1852. if (opts != 0):
  1853. for x in opts:
  1854. if (t.opts.count(x)==0):
  1855. t.opts.append(x)
  1856. if (input != 0):
  1857. for x in input:
  1858. fullinput = FindLocation(x, ipath)
  1859. t.inputs.append(fullinput)
  1860. # Don't re-link a library or binary if just it's dependency dll's have been altered.
  1861. # This should work out fine in most cases, and often reduces recompilation time.
  1862. if (os.path.splitext(x)[-1] not in SUFFIX_DLL):
  1863. t.deps[fullinput] = 1
  1864. (base,suffix) = os.path.splitext(x)
  1865. if (SUFFIX_INC.count(suffix)):
  1866. for d in CxxCalcDependencies(fullinput, ipath, []):
  1867. t.deps[d] = 1
  1868. if (dep != 0):
  1869. for x in dep:
  1870. fulldep = FindLocation(x, ipath)
  1871. t.deps[fulldep] = 1
  1872. if (winrc != 0 and sys.platform.startswith("win")):
  1873. TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc))
  1874. if (target.endswith(".in")):
  1875. t.deps[FindLocation("interrogate.exe",[])] = 1
  1876. t.deps[FindLocation("dtool_have_python.dat",[])] = 1