makepandacore.py 130 KB

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