makepandacore.py 71 KB

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