makepandacore.py 130 KB

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