makepandacore.py 75 KB

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