makepandacore.py 105 KB

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