makepandacore.py 123 KB

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