makepandacore.py 140 KB

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