makepandacore.py 123 KB

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