text
stringlengths
2
104M
meta
dict
module AcLibraryRb end include AcLibraryRb require_relative '../lib_lock/ac-library-rb/core_ext/all.rb' require_relative '../lib_lock/ac-library-rb/convolution' require_relative '../lib_lock/ac-library-rb/crt' require_relative '../lib_lock/ac-library-rb/dequex' require_relative '../lib_lock/ac-library-rb/dsu' require_relative '../lib_lock/ac-library-rb/fenwick_tree' require_relative '../lib_lock/ac-library-rb/floor_sum' require_relative '../lib_lock/ac-library-rb/inv_mod' require_relative '../lib_lock/ac-library-rb/lazy_segtree' require_relative '../lib_lock/ac-library-rb/lcp_array' require_relative '../lib_lock/ac-library-rb/max_flow' require_relative '../lib_lock/ac-library-rb/min_cost_flow' require_relative '../lib_lock/ac-library-rb/modint' require_relative '../lib_lock/ac-library-rb/pow_mod' require_relative '../lib_lock/ac-library-rb/priority_queue' require_relative '../lib_lock/ac-library-rb/scc' require_relative '../lib_lock/ac-library-rb/segtree' require_relative '../lib_lock/ac-library-rb/suffix_array' require_relative '../lib_lock/ac-library-rb/two_sat' require_relative '../lib_lock/ac-library-rb/z_algorithm'
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require_relative "../../lib_lock/ac-library-rb/convolution" require_relative "../../lib_lock/ac-library-rb/crt" require_relative "../../lib_lock/ac-library-rb/deque" require_relative "../../lib_lock/ac-library-rb/dsu" require_relative "../../lib_lock/ac-library-rb/fenwick_tree" require_relative "../../lib_lock/ac-library-rb/floor_sum" require_relative "../../lib_lock/ac-library-rb/inv_mod" require_relative "../../lib_lock/ac-library-rb/lazy_segtree" require_relative "../../lib_lock/ac-library-rb/lcp_array" require_relative "../../lib_lock/ac-library-rb/max_flow" require_relative "../../lib_lock/ac-library-rb/min_cost_flow" require_relative "../../lib_lock/ac-library-rb/modint" require_relative "../../lib_lock/ac-library-rb/pow_mod" require_relative "../../lib_lock/ac-library-rb/priority_queue" require_relative "../../lib_lock/ac-library-rb/scc" require_relative "../../lib_lock/ac-library-rb/segtree" require_relative "../../lib_lock/ac-library-rb/suffix_array" require_relative "../../lib_lock/ac-library-rb/two_sat" require_relative "../../lib_lock/ac-library-rb/z_algorithm" # Usage: # require 'ac-library-rb/all' # include AcLibraryRb
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Awesome Phodal > Awesome articles, tools, OS project, design of Phodal - collections in path of Phodal's way for new geek & nerd to quick growth. ## 文章 ### 练习 - 2016.7 [关于编程,你的练习是不是有效的?](https://github.com/phodal/articles/issues/19) - 2017.6 **[演进:在工作的前三年里快速成长(练习篇)](https://www.phodal.com/blog/evolution-how-to-practise/)** - 2019.2 [练习技术的诀窍](https://www.phodal.com/blog/how-to-make-practise-works/) - 2018.8 [技术的学习与练习](https://www.phodal.com/blog/how-to-learn-skill/) - 2014.5 [写作驱动学习](https://www.phodal.com/blog/write-driven-learning/) - 2016.5 [如何以“正确的姿势”阅读开源软件代码 ](https://github.com/phodal/articles/issues/14) ### 软件工程 - 2018.9 [项目初期的最优技术实践](https://www.phodal.com/blog/short-time-project-best-practise/) - 2018.1 [开源之美:开源软件开发流程](https://www.phodal.com/blog/how-to-build-a-opensource-project/) - 2017.6 [技巧 - 如何好一个 Git 提交信息及几种不同的规范](https://www.phodal.com/blog/how-to-write-a-better-git-commit-message/) - 2017.7 [使用 React Native 重写大型 Ionic 应用后,我们想分享一下这八个经验](https://www.phodal.com/blog/react-native-case-study/) - 2018.1 [从遗留技术栈升级里,我学到的八件事](https://www.phodal.com/blog/learning-from-blogpost-tech-stack-migrate/) ### 职业生涯系列 - 2017.2 [程序员如何写好简历 && 一份优秀的程序员简历是什么样的?](https://www.phodal.com/blog/how-to-write-a-resume/) - 2017.4 [天天写业务代码的那些年,我们是如何成长过来的](https://www.phodal.com/blog/howto-learn-technoloty-from-legacy-system-project/) - 2017.6 [编程热情的维系](https://www.phodal.com/blog/thinking-about-programming-enthusiasm/) - 2017.9 [说说程序员的核心能力:第一个三年:后台、前端、移动应用,第二个三年呢?](https://www.phodal.com/blog/thinking-about-programmer-core-skills/) - 2018.4 [初级到资深:程序员的职业生涯思考与可迁移技能培养](https://www.phodal.com/blog/thinking-in-programmer-career-and-common-skills/) - 2016.7 [两年以来x两年以后](https://github.com/phodal/articles/issues/21) - 2018.7 [编程人生:毕业到迈入工作的第五年,发生了这些变化](https://www.phodal.com/blog/a-programmer-to-five-years/) - 2018.12 [程序员的成长焦虑:构建长期职业生涯](https://www.phodal.com/blog/build-a-long-tem-programmer-life-plan/) - 2016.2 [我的编程之路](https://mp.weixin.qq.com/s/RKHo8oFydYL0KgHbvvOUkA) - 2016.8 [【前端人生】我的前端学习经验和方法技巧](https://mp.weixin.qq.com/s/j-6zHfOvzG4pJzMXji-lVg) ### Tech Lead 系列 - 2019.1 **[迈向 Tech Lead 之路](https://www.phodal.com/blog/path-to-tech-lead/)** - 2019.3 [新项目检查清单](https://www.phodal.com/blog/new-project-check-lists/) - 2019.4 [技术调研的模式](https://www.phodal.com/blog/tech-spike-patterns/) - 2019.3 [如何优化上线流程——Path to Production](https://www.phodal.com/blog/tech-lead-tools-path-to-production/) ### 架构 - 2018.7 [实施微前端的六种方式](https://github.com/phodal/articles/issues/51) - 2015.12 [RePractise:前端演进史](http://repractise.phodal.com/) - ["微" 害架构](https://www.phodal.com/blog/micro-architecture-in-real-world/) - [如何解构单体前端应用——前端应用的微服务式拆分](https://www.phodal.com/blog/how-to-build-a-microfrontend-framework-mooa/) - [无代码编程](https://www.phodal.com/blog/low-code-programming/) - [前后端分离团队的资源浪费](https://www.phodal.com/blog/frontend-backend-seperate-team-is-waste-resources/) - [构建质量可信的软件系统](https://www.phodal.com/blog/build-trusted-software-system/) - [管理依赖的 11 个策略](https://www.phodal.com/blog/dependency-management-strategy/) - [如何创建你的应用脚手架](https://www.phodal.com/blog/how-to-create-application-boilerplate/) - [整洁前端架构](https://github.com/phodal/clean-frontend) **架构拾集**: - [【架构拾集】 微前端:微应用化](https://www.phodal.com/blog/architecutre-in-word-design-micro-application-frontend-architecture/) - [【架构拾集】:移动应用架构设计](https://www.phodal.com/blog/architecture-design-series-design-a-mobile-application-architecture/) - [【架构拾集】前后端分离演进:不能微服务,那就 BFF 隔离](https://www.phodal.com/blog/architecture-101-bff-for-legacy-system-migrate/) - [【架构拾集】简易的 Android 混合应用框架的插件架构设计](https://www.phodal.com/blog/phodal-architecture-books-build-android-hybird-plugins-manage/) - [【架构拾集】移动应用的自动化测试(BDD 方式)](https://www.phodal.com/blog/phodal-architecture-101-mobile-appllication-test-architecture/) - [【架构拾集】基于混合应用架构的跨平台实时聊天应用](https://www.phodal.com/blog/architecture-design-build-instant-message-application/) - [【架构拾集】WebView 的JavaScript Bridge 设计](https://www.phodal.com/blog/architecture-books-build-hybird-framework/) - [跨平台架构模式](https://www.phodal.com/blog/cross-platform-strategy/) ### 编码 - [如何提升 Web 应用的代码质量](https://www.phodal.com/blog/how-to-improve-web-application-quanlity/) - [五个基本原则,让新手写出 “整洁代码”](https://www.phodal.com/blog/how-to-write-clean-code/) - [使用 “IDE 重构” 改善代码质量](https://www.phodal.com/blog/beautify-code-ide-refactor/) ### 业务 - [如何在业务代码中提升:创建领域特定语言](https://www.phodal.com/blog/how-to-design-dsl-in-bau-project/) - [开发一个类似于 xxx 的应用有多难?](https://www.phodal.com/blog/how-to-development-a-xxx-like-application/) ### 算法 - [我是如何为技术博客设计一个推荐系统(上):基于统计与评分](https://www.phodal.com/blog/how-to-design-a-recommend-system-part-1-statistics-rating-up/) - [如何为技术博客设计一个推荐系统(中):基于 Google 搜索的半自动推荐](https://www.phodal.com/blog/how-to-design-a-recommend-system-part-1-google-based-auto-tag-system/) ### 测试 - 2016.11 [UI测试:一个浏览器跑要8分钟,那么8个浏览器呢?](https://www.phodal.com/blog/one-browser-run-test-in-8mins-how-about-eight-browsers/) - 2015.12 [基于Virtual DOM与Diff DOM的测试代码生成](https://www.phodal.com/blog/virtual-dom-diff-dom-generate-test/) - 2017.10 [BDD 框架对比: Cucumber.js vs Robot Framework vs Gauge.js](https://www.phodal.com/blog/how-to-choice-you-bdd-framework-robot-cucumber-gauge/) - [测试代码的坏味道](https://www.phodal.com/blog/test-bad-smell/) ### 系统重构 - [如何做遗留系统的重构评估](https://www.phodal.com/blog/evaluate-legacy-system/) - [分层架构重构](https://www.phodal.com/blog/refactor-mvc-architecture-to-ddd/) - [重构的自动化](https://www.phodal.com/blog/auto-refactor/) ### 写作 - [如何翻译一本计算机书籍?](https://www.phodal.com/blog/how-to-translate-a-technology-book/) - [程序员怎样才能写出一篇好的博客或者技术文章](https://www.phodal.com/blog/programmer-how-to-write-a-good-article/) - [写一篇好的技术文章有多难?](https://www.phodal.com/blog/how-to-write-a-good-tech-artilce/) ### 个人 - 2017.2 [2017 年,你应该这样学习 Web 编程 —— 内置索引 + 外置搜索引擎](https://github.com/phodal/articles/issues/37) - [如何提高影响力](https://www.phodal.com/blog/how-to-improve-impact/) - [程序员如何艺术的提升技术、影响力&赚钱](https://www.phodal.com/blog/how-to-make-money-and-improve-impact/) - [程序员如何提高影响力 2.0](https://www.phodal.com/blog/improve-impact-2/) - [程序员如何提高效率之休息](https://www.phodal.com/blog/how-to-improve-performance-by-better-rest/) ### 年度流水系列 - [2013 节点——技术成长,从比赛到 ThoughtWorks](https://www.phodal.com/blog/my-2013-from-competition-to-thoughtworks/) - [2014 节点——高速发展的一年:目标和代码](https://www.phodal.com/blog/2014-node-quick-grow-year-tasks-code/) - [2015 节点——从翻译到浮现式设计](https://www.phodal.com/blog/recap-2015-simple-the-world/) - [2016 年节点——增长的一年:不只编程](https://www.phodal.com/blog/summary-2016-growth-year-notolny-programming/) - [2017 年节点——T 型成长,持续学习](https://www.phodal.com/blog/summary-2017-t-talents-continues-growth/) - [2018 节点:Think Big & Be Long](https://www.phodal.com/blog/summary-2018-think-big-and-be-long/) - [2019 节点: Love Wife & Change Life](https://www.phodal.com/blog/annual-2019-love-wife-change-life/) ## 书 ### 作者 - 《前端架构:从入门到微前端》 电子工业出版社 - 《全栈应用开发:精益实践》 电子工业出版社(购买:[亚马逊](https://www.amazon.cn/dp/B0722YJR89)、[当当](http://product.dangdang.com/25077858.html)、[京东](http://item.jd.com/12195442.html)) - 《自己动手设计物联网》 电子工业出版社(购买:[亚马逊](https://www.amazon.cn/%E5%9B%BE%E4%B9%A6/dp/B01IBZWTWW?ie=UTF8&creative=2384&creativeASIN=B01IBZWTWW&linkCode=df0&ref_=asc_df_B01IBZWTWW2239914&tag=douban-23)、[当当](http://product.dangdang.com/24000878.html?_ddclickunion=P-306226-0-s26841195|ad_type=0|sys_id=1#dd_refer=https%3A%2F%2Fbook.douban.com%2Flink2%2F%3Flowest%3D4250%26pre%3D0%26vendor%3Ddangdang%26srcpage%3Dsubject%26price%3D5020%26pos%3D1%26url%3Dhttp%253a%252f%252funion.dangdang.com%252ftransfer.php%253ffrom%253dp-306226-0-s26841195%2526backurl%253dhttp%253a%252f%252fproduct.dangdang.com%252fproduct.aspx%253fproduct_id%253d24000878%26cntvendor%3D4%26srcsubj%3D26841195%26type%3Dbkbuy%26subject%3D26841195)、[京东](http://item.jd.com/11946585.html)) ### 翻译 - 《物联网实战指南》机械工业出版社(购买:[京东](https://item.jd.com/12037436.html) 、[当当](http://product.dangdang.com/24035320.html)、[亚马逊](https://www.amazon.cn/dp/B01M06CK6R/)) - 《Arduino 编程:实现梦想的工具和技术([亚马逊](https://www.amazon.cn/dp/B075VVPN79))》 ### 电子书 - 《[Phodal's Idea实战指南](https://github.com/phodal/ideabook)》 - 《[一步步搭建物联网系统](https://github.com/phodal/designiot)》 - 《[GitHub 漫游指南](https://github.com/phodal/github-roam)》 - 《[RePractise](https://github.com/phodal/repractise)》 - 《[Growth: 全栈增长工程师指南](https://github.com/phodal/growth-ebook)》 - 《[Growth: 全栈增长工程师实战](https://github.com/phodal/growth-in-action)》 - 《[我的职业是前端工程师](https://github.com/phodal/fe)》 - 《[Serverless 应用开发指南](https://github.com/phodal/serverless)》 - 《[微前端的那些事儿](https://github.com/phodal/microfrontends)》 - 《[系统重构与迁移指南](https://github.com/phodal/migration)》 - 《[云研发:研发即代码](https://github.com/phodal/cloud-dev)》(草稿) ### 审阅 - 《[Learning Internet of Things》](https://www.packtpub.com/application-development/learning-internet-things)》(英文版, PACKT出版社)》 - 《[Smart Internet of Things ](https://www.packtpub.com/hardware-and-creative/smart-internet-things-projects)》(英文版,PACKT出版社) - 《[Angular Services](https://www.packtpub.com/web-development/angular-services)》(英文版,PACKT出版社) - 《[Getting Started with Angular - Second Edition](https://www.packtpub.com/web-development/getting-started-angular-second-edition)》(英文版,PACKT出版社) - 《[Building Modern Web Applications Using Angular](https://www.packtpub.com/web-development/building-modern-web-applications-using-angular)》(英文版,PACKT出版社) - 《[Expert Angular](https://www.packtpub.com/web-development/expert-angular)》(英文版,PACKT出版社) - 《[Angular 6 by Example - Third Edition](https://www.packtpub.com/web-development/angular-example-third-edition)》(英文版,PACKT出版社) - 《[Mastering Angular Components - Second Edition](https://www.packtpub.com/web-development/mastering-angular-components-second-edition)》(英文版,PACKT出版社) - 《[Building Large-Scale Web Applications with Angular](https://www.packtpub.com/web-development/building-large-scale-web-applications-angular)》(英文版,PACKT出版社) ## 开源项目 详细见:[Ideas](https://github.com/phodal/ideas) ### 语言 - 通用语言元信息转换器 [Chapi](https://github.com/phodal/chapi) ### 工具 - 架构决策记录工具 [ADR](https://github.com/phodal/adr) - DDD 生成工个 [stepping](https://github.com/phodal/stepping) - Markdown 编辑器 [Phodit](https://github.com/phodal/phodit) - Serverless 密码管理工具 [Mopass](https://github.com/phodal/mopass) - 遗留系统重构工具 [Coca](https://github.com/phodal/coca) ### 移动端 - React Native 混合应用框架 [Dore](https://github.com/phodal/dore) - Android 应用模板 [Arche](https://github.com/phodal/arche) ### 前端 - Developer 进阶书单 [Booktree](https://github.com/phodal/booktree) - 技能树 2 [Sherlock](https://github.com/phodal/sherlock) - 技能树 1 [Skilltree](https://github.com/phodal/skilltree) - Slide 框架 [Echoesworks](https://github.com/phodal/echoesworks) - 前端框架 [Lettuce](https://github.com/phodal/lettuce) - 文档代码化框架:[Ledge Framework](https://github.com/ledge-framework/engine/) ### 物联网 - 多协议物联网系统 [Lan](https://github.com/phodal/lan) - 最小物联网系统 [IoT](https://github.com/phodal/iot) - 嵌入式知识总汇 [EKS](https://github.com/phodal/eks) ### 文档化 - DevOps 知识平台[Ledge](https://github.com/phodal/ledge)
{ "repo_name": "phodal/summary", "stars": "51", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
![Awesome Campus Expert](https://cloud.githubusercontent.com/assets/8436717/25505858/a76c6a54-2b9b-11e7-9062-d9f4e664ace0.gif) [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) Resources marked with a :triangular_flag_on_post: have been created by campus experts ## Contents - [Learn](#learn) - [Git](#git) - [Markdown](#markdown) - [Workshops](#workshops) - [Tips](#tips) - [Teaching](#teaching) - [Slide Resources](#slide-resources) - [Writing](#writing) - [Tools](#tools) - [Content Guides](#content-guides) - [Open Source](#open-source) - [Find projects](#find-projects) - [Community](#community) - [Management](#management) ## Learn Resources for learning or teaching languages, techniques, skills etc. ### Git - [tryGit](https://try.github.io/levels/1/challenges/1) - A 15 minute introduction to git in the terminal. - [Learn Git Branching](http://learngitbranching.js.org/) - Interactive lesson which visualises branches and commits - [GitHub Flow](https://guides.github.com/introduction/flow/) - Guide that explains how and why GitHub Flow work - [On Demand Training](https://services.github.com/on-demand/) - On demand training material for various Git and GitHub tools such a command line and GitHub Pages - [GitHub training resources](https://services.github.com/resources/) - Extensive collection of battle tested resources from documentation to training slides and cheat sheets - :triangular_flag_on_post: [Lionex/github-workshop](https://github.com/Lionex/github-workshop) - Originally created for HackFSU '17, this workshop hopes to introduce new hackers to the basics of using git with GitHub. ### Markdown - [Mastering Markdown](https://guides.github.com/features/mastering-markdown/) - GitHub guide to mastering GitHub flavoured markdown ## Workshops Resources for running workshops and workshops that other campus experts have run themselves or that may be useful to others. ### Tips - [Speaking.io](http://speaking.io/) - a cool website with some good tips on giving talks, focused on tech talks mostly - [The Art of Slide Design](https://missgeeky.com/2017/08/04/the-art-of-slide-design/) - Melinda Seckington, talk on the fundamentals of good slide design for pleasant and effective transfer of information. ### Teaching - [github/training-utils](https://github.com/github/training-utils) - A series of Bash and ZShell scripts useful when teaching about git and GitHub (+ bonus [list of useful apps](https://github.com/github/training-utils#other-useful-apps)) - [codesandbox](https://codesandbox.io/) - Online web application editor (react, vue), useful when running a react/vue or other framework type workshop. - [Glitch](https://glitch.com/) - Online HTML/JS/CSS editor and viewer, very useful when doing HTMl / web based workshops. Also hosts the static site at project-name.glitch.me. Bonus, runs node.js so it can also be used to run an api workshop if the backend is written in node.js. ### Slide Resources - [FsReveal](https://github.com/fsprojects/FsReveal) - FsReveal allows you to write beautiful slides in Markdown and brings F# to the reveal.js web presentation framework. - [Remark](https://github.com/gnab/remark) - A simple, in-browser, markdown-driven slideshow tool targeted at people who know their way around HTML and CSS. - [`reveal-md`](https://www.npmjs.com/package/reveal-md) - Write reveal.js slides as a single markdown file, and use markdown's html fallback to add more complicated markup and set reveal-specific configuration (like fragments). ## Writing Resources for writing and maintaining technical documentation ### Visualisation - [Apiary](https://apiary.io/) - Powerful API Design Stack. Built for Developers. - [Swagger](http://swagger.io) - Swagger is a powerful open source framework backed by a large ecosystem of tools that helps design, build, document, and consume RESTful APIs. ### Tools - [nanoc](https://nanoc.ws/) - Nanoc is a static-site generator, fit for building anything from a small personal blog to a large corporate website. (used by GitHub on their own docs) - [Sphinx](http://www.sphinx-doc.org/en/stable/) - Sphinx is a tool that makes it easy to create intelligent and beautiful documentation, originally created for the Python documentation. - [Daux](https://github.com/justinwalsh/daux.io) - Daux is an documentation generator that uses a simple folder structure and Markdown files to create custom documentation on the fly. - :triangular_flag_on_post: [mdpdf](https://github.com/bluehatbrit/mdpdf) - mdpdf is a tool for generating stylable pdfs from markdown. ### Content Guides Communication and writing style - [MailChimp](http://styleguide.mailchimp.com/) - The style guide was created for MailChimp employees - [18f](https://pages.18f.gov/content-guide/) - How to plan, write, and manage content at 18F. - [Digital Ocean](https://www.digitalocean.com/community/tutorials/digitalocean-s-writing-guidelines) - DigitalOcean's Writing Guidelines - [SendGrid](https://sendgrid.com/blog/write-technical-blog-posts/) - How To Write Technical Blog Posts ## Open Source ### Find Projects - [Up For Grabs](http://up-for-grabs.net/) - List of projects which have curated tasks specifically for new contributors. - [issuehub.io](http://issuehub.io/) - Contribute to Open Source. Search issue labels to find the right project for you! - [FIRST TIMERS ONLY](http://www.firsttimersonly.com/) - Friendly Open Source projects should reserve specific issues for newbies. - [Your First PR](http://yourfirstpr.github.io/) - Your First PR helps you get started contributing to Open Source by showcasing great starter issues on GitHub and elsewhere. - [Awesome First PR Opportunities](https://github.com/MunGell/awesome-for-beginners) - A list of awesome beginners-friendly projects. - [Codetriange](https://www.codetriage.com/) - Help out your favorite open source projects and become a better developer while doing it. - [Pull Request Roulette](http://PullRequestRoulette.com) - Pull requests (or PRs) submitted for review - [24 Pull Requests](http://24pullrequests.com) - Contribute to projects for 24 days leading up to christmas - [WebCompat](https://webcompat.com/) - Bug reporting for the internet ## Community ### Management - [Curriculum for the Atom Community Manager Apprenticeship project](https://github.com/lee-dohm/community-manager) ## Contribute Contributions welcome! Read the [contribution guidelines](contributing.md) first. ## License [![CC0](http://mirrors.creativecommons.org/presskit/buttons/88x31/svg/cc-zero.svg)](http://creativecommons.org/publicdomain/zero/1.0) To the extent possible under law, Joe Nash has waived all copyright and related or neighboring rights to this work.
{ "repo_name": "campus-experts/awesome-campus-expert", "stars": "470", "repo_language": "None", "file_name": "contributing.md", "mime_type": "text/plain" }
# Contributor Covenant Code of Conduct Version 2.0 ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations # Getting help with a violation or incident, the TLDR: If for any reason, you feel unsafe, unwelcome or uncomfortable as a result of an interaction within the Campus Experts program, ways to report the incident and get support are listed below - Contact @juanpflores & the Education team at [email protected]
{ "repo_name": "campus-experts/awesome-campus-expert", "stars": "470", "repo_language": "None", "file_name": "contributing.md", "mime_type": "text/plain" }
# Resources from Open Training - [Campus Experts Benefit List](https://github.com/campus-experts/open-training/blob/master/docs/benefits.md) ## Module 0 ~ Start Here - [Video](https://www.youtube.com/watch?v=bKCa9LVacUk&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c&index=1) - does not have transcript? - [Managing Notifications](https://github.com/campus-experts/open-training/blob/master/docs/managing-notifications.md) - [Mastering Markdown](https://guides.github.com/features/mastering-markdown/) - [Intro to GitHub](https://services.github.com/on-demand/intro-to-github/) - [Git-It](https://github.com/jlord/git-it-electron) ## Module 1 ~ Introduction - [Video](https://www.youtube.com/watch?v=kCs0gSlFM1A&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c&index=2) - does not have transcript? ## Module 2 ~ Community Management - [Video](https://www.youtube.com/watch?v=PWbP-lk8rX4&index=3&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/02-community-management/resources/webinar-transcript.html) - still in html, not md - [Conversational Aikido](https://github.com/campus-experts/open-training/blob/master/02-community-management/resources/conversational-aikido.md) - [Contributor Covenant](https://www.contributor-covenant.org/) - [Creating Inclusive Tech Communities](https://medium.com/samsung-internet-dev/creating-inclusive-tech-communities-e08ee73b4fa1) - [Lee's Community Management Repo](https://github.com/lee-dohm/community-manager) - [Lee on Trolls](http://www.lee-dohm.com/2017/02/03/troll-tactics-and-responses/) ## Module 3 ~ Public Speaking - [Video](https://www.youtube.com/watch?v=22IFQLDQvfQ&index=4&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/03-public-speaking/resources/webinar-transcript.md) - [Annotated Transcript](https://github.com/campus-experts/open-training/blob/master/03-public-speaking/resources/annotated-transcript.md) - [Writing Proposals](https://github.com/campus-experts/open-training/blob/master/03-public-speaking/resources/writing-proposals.md) - [Demystifying Public Speaking](https://abookapart.com/products/demystifying-public-speaking) - not link to the actual book. link to buy the book - [What Your Conference Proposal Is Missing](http://www.sarahmei.com/blog/2014/04/07/what-your-conference-proposal-is-missing/) - [We Are All Awesome](http://weareallaweso.me/) - advice for first time speakers [Speaking.io](http://speaking.io/) - advice for speakers - [Papercall](https://www.papercall.io/), [Technically Speaking](https://tinyletter.com/techspeak), and [Eventil](https://eventil.com/) - places to submit talks - [The Importance of Donuts](http://larahogan.me/donuts/) ## Module 4 ~ Workshop Development - [Video](https://www.youtube.com/watch?v=FR2JbCbSDSc&index=5&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/04-workshop-development/resources/webinar-transcript.md) - [How GitHub teaches GitHub](https://github.com/campus-experts/open-training/blob/master/04-workshop-development/resources/how-github-teaches-github.md) - [Live GitHub Workshop](https://www.youtube.com/watch?v=1HTalMpRSgY) - [Advice on Technical Workshops](http://coaching.rubymonstas.org/) - from Rails Girls - [GitHub's open source training](https://github.com/github/training-kit) ## Module 5 ~ Technical Writing - [Video](https://www.youtube.com/watch?v=sxXvfttdzKg&index=6&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/05-technical-writing/resources/webinar-transcript.md) - [Fall 2016 Technical Writing Q&A](https://github.com/campus-experts/fall-2016/blob/master/docs/technical-writing-answers.md) - [Spring 2017 Technical Writing Q&A](https://github.com/campus-experts/spring-2017/issues/25#issuecomment-294971349) - [GitHub Pages from the command line](https://services.github.com/on-demand/github-cli/) - [GitHub Pages from GitHub Desktop](https://services.github.com/on-demand/github-desktop/) - [How GitHub does Docs](https://github.com/campus-experts/open-training/blob/master/05-technical-writing/resources/how-github-does-docs.md) - [Campus Experts Q&A](https://github.com/campus-experts/open-training/blob/master/05-technical-writing/resources/q%26a.md) ## Module 6 ~ Fundraising - [Video](https://www.youtube.com/watch?v=SZDuPf2-vhA&index=7&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/06-fundraising/resources/webinar-transcript.md) -[Tim on Fundraising](https://github.com/campus-experts/open-training/blob/master/06-fundraising/resources/fundraising.md) ## Module 7 ~ Open Source - [Video](https://www.youtube.com/watch?v=VNUiXLN8Q8M&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c&index=8) - [Transcript](https://github.com/campus-experts/open-training/blob/master/07-opensource/resources/webinar-transcript.md) - [Annotated Transcript](https://github.com/campus-experts/open-training/blob/master/07-opensource/resources/annotated-transcript.md) - Places to Find Open Source Projects: - http://up-for-grabs.net/ - http://issuehub.io/ - http://www.firsttimersonly.com/ - http://yourfirstpr.github.io/ - https://github.com/MunGell/awesome-for-beginners - http://docsdoctor.org - http://PullRequestRoulette.com - http://24pullrequests.com - https://webcompat.com/ - https://open-source.now.sh/ ## Module 8 ~ GraphQL - [Video](https://www.youtube.com/watch?v=PPWWPLuN4nU&index=9&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/08-graphql/resources/webinar-transcript.md) - [GraphQL SetUp](https://gist.github.com/wilhelmklopp/96309b04f67d4ac029d1880ca26fc2aa) - [GraphQL Sample App in node.js](https://github-graphql-example-app.glitch.me/) - [Remix the app on Glitch.com](https://glitch.com/edit/#!/puzzled-peony?path=README.md:1:0) - [Intro to GraphQL](https://services.github.com/on-demand/graphql/) ## Module 9 ~ Hubot - [Video](https://www.youtube.com/watch?v=9AuKvqdSS6c&index=10&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/09-hubot/resources/webinar-transcript.md) - Deploying a Hubot to Heroku for Slack: - https://slackapi.github.io/hubot-slack/ - https://hubot.github.com/docs/deploying/heroku/ - [Hubot Documentation](https://hubot.github.com/docs/) ## Module 10 ~ Opensource Clubs - [Video](https://www.youtube.com/watch?v=eLfyXT7tcDE&index=11&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - No Transcript! - [Starting a Club](https://github.com/campus-experts/open-training/blob/master/10-opensource-clubs/resources/starting-a-club.md) ## Module 11 ~ Git Tips & Tricks - Videos: - [GitHooks](https://www.youtube.com/watch?v=ca2Zw3hR5uo&index=11&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Squashing](https://www.youtube.com/watch?v=AmyXHwLKrLA&index=13&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [SSH](https://www.youtube.com/watch?v=PrkrcMfVkHo&index=12&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Rebasing with no conflicts](https://www.youtube.com/watch?v=OBhhd2ozSsw&index=14&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Rebasing with conflicts](https://www.youtube.com/watch?v=lDRTMR5frG4&index=15&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/11-git-tips-and-tricks/resources/webinar-transcript.md) ## Module 12 ~ Electron - [Video](https://www.youtube.com/watch?v=-uBlR1ke1bM&index=12&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/12-electron/resources/webinar-transcript.md) - [Electron Prerequisites](https://gist.github.com/hollenberry/fb784b4a630d274469f09bff18eaa26a) - [Apps Built on Electron](https://electron.atom.io/apps/) - [On Demand Electron Courses](https://services.github.com/on-demand/electron/) ## Module 13 ~ Atom - [Video](https://www.youtube.com/watch?v=ma1PmLRcLKc&index=13&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - No Transcript!! - [Making Plugins in Atom](https://github.com/campus-experts/open-training/blob/master/13-atom/resources/atom-content.md) - [Atom Flight Manual](http://flight-manual.atom.io/) - [Building Your First Atom Plugin](https://github.com/blog/2231-building-your-first-atom-plugin) ## Module 14 ~ GitHub Pages - [Video](https://www.youtube.com/watch?v=8ZbCasdaR6Y&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c&index=13) - [Transcript](https://github.com/campus-experts/open-training/blob/master/14-github-pages/resources/webinar-transcript.md) - [GitHub Pages Overview](https://pages.github.com/) - contains video about GitHub Pages and some quickstart instructions. - [User, Organization, and Project Pages](https://help.github.com/articles/user-organization-and-project-pages/) - helpful in determining the structure of your site's URL. - [Setting up your GitHub Pages site locally with Jekyll](https://help.github.com/articles/setting-up-your-github-pages-site-locally-with-jekyll/#step-2-install-jekyll-using-bundler) - instructions for testing or spinning up a new local site compatible with GitHub Pages. - [GitHub Pages Gem](https://github.com/github/pages-gem) - information about all that's included in the gem. - [Jekyll Documentation](https://jekyllrb.com/docs/home/) - source of truth for all the Jekyll-specific things, including: configuration defaults, installation guides for Mac and Windows, basic usage. - [GitHub's On-Demand Training](https://services.github.com/on-demand/) - site created using GitHub Pages. ## Module 15 ~ Running an Organization - [Video](https://www.youtube.com/watch?v=67ypYKihMiw&index=19&list=PLIRjfNq867bdlTQcgcOGATPrVggvfLv1c) - [Transcript](https://github.com/campus-experts/open-training/blob/master/15-running-an-org/resources/webinar-transcript.md) - [How GitHub uses GitHub: Managing your Teams](https://resources.github.com/webcasts/GitHub-managing-your-teams/) - [How GitHub uses GitHub: Communicating with Remote Teams](https://resources.github.com/webcasts/GitHub-communicating-with-remote-teams/) - [Add-to-org](https://github.com/benbalter/add-to-org) - a tool for automating joining of organizations.
{ "repo_name": "campus-experts/awesome-campus-expert", "stars": "470", "repo_language": "None", "file_name": "contributing.md", "mime_type": "text/plain" }
# Contribution Guidelines Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms. --- Ensure your pull request adheres to the following guidelines: - Make sure you take care of this - And this as well - And don't forget to check this Thank you for your suggestions! ## Updating your PR A lot of times, making a PR adhere to the standards above can be difficult. If the maintainers notice anything that we'd like changed, we'll ask you to edit your PR before we merge it. There's no need to open a new PR, just edit the existing one. If you're not sure how to do that, [here is a guide](https://github.com/RichardLitt/knowledge/blob/master/github/amending-a-commit-guide.md) on the different ways you can update your PR so that we can merge it.
{ "repo_name": "campus-experts/awesome-campus-expert", "stars": "470", "repo_language": "None", "file_name": "contributing.md", "mime_type": "text/plain" }
import Foundation fileprivate let stdOutIsColorTerm: Bool = { if let cliColorForce = ProcessInfo.processInfo.environment["CLICOLOR_FORCE"], ["1", "yes", "true"].contains(cliColorForce) { return true} guard isatty(STDOUT_FILENO) == 1 else { return false } #if os(macOS) if let xpcServiceName = ProcessInfo.processInfo.environment["XPC_SERVICE_NAME"], xpcServiceName.localizedCaseInsensitiveContains("com.apple.dt.xcode") { return false } #endif guard let term = ProcessInfo.processInfo.environment["TERM"], !["", "dumb", "cons25", "emacs"].contains(term) else { return false } return true }() public enum Color: RawRepresentable { case black case red case green case yellow case blue case magenta case cyan case white case extended(UInt8) public init?(rawValue: UInt8) { switch rawValue { case 0: self = .black case 1: self = .red case 2: self = .green case 3: self = .yellow case 4: self = .blue case 5: self = .magenta case 6: self = .cyan case 7: self = .white default: self = .extended(rawValue) } } public var rawValue: UInt8 { switch self { case .black: return 0 case .red: return 1 case .green: return 2 case .yellow: return 3 case .blue: return 4 case .magenta: return 5 case .cyan: return 6 case .white: return 7 case .extended(let number): return number } } } public struct Style: OptionSet { public static let bold = Style(rawValue: 1 << 0) public static let dim = Style(rawValue: 1 << 1) public static let italic = Style(rawValue: 1 << 2) public static let underlined = Style(rawValue: 1 << 3) public static let blink = Style(rawValue: 1 << 4) public static let inverse = Style(rawValue: 1 << 5) public static let hidden = Style(rawValue: 1 << 6) // for eg. passwords public static let strikethrough = Style(rawValue: 1 << 7) // not implemented in Terminal.app public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } private extension String.StringInterpolation { mutating func applyChalk(color: Color?, background: Color?, style: Style?, to any: Any) { guard stdOutIsColorTerm else { return appendInterpolation("\(any)") } appendLiteral("\u{001B}[") var codeStrings: [String] = [] if let color = color?.rawValue { codeStrings.append("38") codeStrings.append("5") codeStrings.append("\(color)") } if let background = background?.rawValue { codeStrings.append("48") codeStrings.append("5") codeStrings.append("\(background)") } if let style = style { let lookups: [(Style, Int)] = [(.bold, 1), (.dim, 2), (.italic, 3), (.underlined, 4), (.blink, 5), (.inverse, 7), (.hidden, 8), (.strikethrough, 9)] for (key, value) in lookups where style.contains(key) { codeStrings.append(String(value)) } } appendInterpolation(codeStrings.joined(separator: ";")) appendLiteral("m") appendInterpolation("\(any)") appendLiteral("\u{001B}[0m") // reset color, background, and style } } public extension String.StringInterpolation { mutating func appendInterpolation(_ any: Any, color: Color) { applyChalk(color: color, background: nil, style: nil, to: any) } mutating func appendInterpolation(_ any: Any, background: Color) { applyChalk(color: nil, background: background, style: nil, to: any) } mutating func appendInterpolation(_ any: Any, style: Style) { applyChalk(color: nil, background: nil, style: style, to: any) } mutating func appendInterpolation(_ any: Any, color: Color, background: Color) { applyChalk(color: color, background: background, style: nil, to: any) } mutating func appendInterpolation(_ any: Any, background: Color, style: Style) { applyChalk(color: nil, background: background, style: style, to: any) } mutating func appendInterpolation(_ any: Any, color: Color, style: Style) { applyChalk(color: color, background: nil, style: style, to: any) } mutating func appendInterpolation(_ any: Any, color: Color, background: Color, style: Style) { applyChalk(color: color, background: background, style: style, to: any) } }
{ "repo_name": "mxcl/Chalk", "stars": "215", "repo_language": "Swift", "file_name": "ci.yml", "mime_type": "text/plain" }
// swift-tools-version:5.0 import PackageDescription let pkg = Package( name: "Chalk", products: [ .library(name: "Chalk", targets: ["Chalk"]), ], targets: [ .target(name: "Chalk", path: ".", sources: ["Chalk.swift"]), ], swiftLanguageVersions: [.v5] )
{ "repo_name": "mxcl/Chalk", "stars": "215", "repo_language": "Swift", "file_name": "ci.yml", "mime_type": "text/plain" }
# Chalk Terminal colors using Swift 5’s string interpolation extensions. <img src="../gh-pages/Screenshot.1.png" width="467"> ```swift import Chalk // @mxcl ~> 0.3 let colorString = "blue" print("Here’s \(colorString, color: .blue)!") ``` # Styles, Backgrounds, Extended Colors etc. ```swift // color, background & style can be specified all together or individually: print("Foo \(string, color: .blue) bar") print("Foo \(string, color: .blue, background: .yellow) bar") print("Foo \(string, color: .blue, background: .yellow, style: .underline) bar") // styles are an `OptionSet`: print("Foo \(string, style: .underline) bar") print("Foo \(string, style: [.underline, .bold]) bar") // 256 color mode is supported: print("Foo \(string, color: .extended(78) bar") ``` # Name [Chalk] by [@sindresorhus] is an extremely famous Node package for the same purpose. Open source is facilitated by naming connections, we picked the same name to enable those mental connections. This package is called Chalk, or `mxcl/Chalk` or Chalk for Swift when disambiguating. [@sindresorhus]: https://github.com/sindresorhus [Chalk]: https://github.com/chalk/chalk # Support mxcl Hey there, I’m Max Howell, a prolific producer of open source and probably you already use some of it (I created [`brew`]). I work full-time on open source and it’s hard; currently *I earn less than minimum wage*. Please help me continue my work, I appreciate it 🙏🏻 <a href="https://www.patreon.com/mxcl"> <img src="https://c5.patreon.com/external/logo/[email protected]" width="160"> </a> [Other ways to say thanks](http://mxcl.dev/#donate). [`brew`]: https://brew.sh # Demo If you have [`swift-sh`]: ``` $ swift sh <<EOF import Foundation import Chalk // @mxcl ~> 0.3 for x in 0..<256 { let cell = " \(x)".padding(toLength: 5, withPad: " ", startingAt: 0) let terminator = (x + 3).isMultiple(of: 6) ? "\n" : "" print("\(cell, color: .extended(15), background: .extended(UInt8(x)))", terminator: terminator) } EOF ``` Will give you: <img src='../gh-pages/Screenshot.2.png' width='572'> [`swift-sh`]: https://github.com/mxcl/swift-sh # Installation SwiftPM: ```swift package.append(.package(url: "https://github.com/mxcl/Chalk.git", from: "0.1.0")) ``` Carthage: > Waiting on: [@Carthage#1945](https://github.com/Carthage/Carthage/pull/1945).
{ "repo_name": "mxcl/Chalk", "stars": "215", "repo_language": "Swift", "file_name": "ci.yml", "mime_type": "text/plain" }
on: pull_request: paths: - '*.swift' - .github/workflows/ci.yml schedule: - cron: '3 3 * * 1' # 3:03 AM, every Monday jobs: build: runs-on: macos-10.15 strategy: matrix: xcode: [^10, ^11, ^12] conf: [release, debug] steps: - uses: actions/checkout@v2 - uses: mxcl/xcodebuild@v1 with: xcode: ${{ matrix.xcode }} configuration: ${{ matrix.conf }} action: build warnings-as-errors: true
{ "repo_name": "mxcl/Chalk", "stars": "215", "repo_language": "Swift", "file_name": "ci.yml", "mime_type": "text/plain" }
# Summary * [Python代码规范](style-guide/README.md) * [简明概述](style-guide/overview.md) * [注释和文档](style-guide/comment_and_docs.md) * [命名规范](style-guide/variables.md) * [程序设计规范](style-guide/code.md) * [单元测试规范](test-pattern/README.md) * [单元测试简介](test-pattern/intro.md) * [单元测试规范](test-pattern/pattern.md) * [单元测试框架种类及样例](test-pattern/example.md) * [项目规范](project-guide/README.md) * [包和依赖](project-guide/package.md) * [静态文件](project-guide/static.md) * [配置文件和数据](project-guide/config-and-data.md) * [项目目录结构示例](project-guide/dir.md) * [优雅之道](pythonic/README.md) * [Python的哲学](pythonic/zen.md) * [DRY--不要重复你自己](pythonic/DRY.md) * [KISS--keep it simple & small](pythonic/KISS.md) * [虚拟环境--virtualenv](pythonic/virtualenv.md) * [Lint工具--pylint](pythonic/lint.md) * [好用的轮子](pythonic/awesome-python.md)
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# Python 代码、单元测试和项目规范 > 代码是写给人看的, 顺带能在计算机上运行 > > -- <cite>《SICP》</cite> ## 目的 关于 python 项目,尤其是 web 项目,并没有一个比较完整(包含代码、测试、项目)的开源规范。所以我决定自己整理一个,作为大家制定python代码规范的参考,也可以直接拿来用。 ## 在线阅读和下载 [在线阅读](https://python-guide.gitbooks.io/python-style-guide/content/) / [PDF](https://www.gitbook.com/download/pdf/book/python-guide/python-style-guide) / [EPUB](https://www.gitbook.com/download/epub/book/python-guide/python-style-guide) / [MOBI](https://www.gitbook.com/download/mobi/book/python-guide/python-style-guide) ## 参与项目 本书还需要不断完善和编辑,欢迎直接评论或者发起issue,也欢迎pull requests。 ## 待完成 - 翻译awesome-python - pylint - virtualenv ## License Creative Commons — CC0 1.0 Universal
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 程序设计规范 ## 避免'裸代码' * 尽量不要直接将代码写在模块的顶层中,在执行主程序前应该总是检查 ``if __name__ == '__main__'`` , 这样当模块被导入时主程序就不会被执行. ```python # 不推荐的写法(裸代码) do_something() # 正确的写法 def main(): do_something() if __name__ == '__main__': main() ``` 所有的顶级代码在模块导入时都会被执行. 要小心不要去调用函数, 创建对象, 或者执行那些不应该在使用pydoc时执行的操作. ## 字符串 * 尽量不要用```+```号拼接字符串, 使用```%s```模板或```join```拼接 ```Python # 不推荐的写法 print("Spam" + " eggs" + " and" + " spam") # 正确写法, 使用 join print(" ".join(["Spam","eggs","and","spam"])) # 正确写法, 使用 %s 模板 print("%s %s %s %s" % ("Spam", "eggs", "and", "spam")) ``` ## 列表和字典 * 在不复杂的情况下, 尽量多用列表生成式, 可以使代码更加清晰 **注意: 复杂情况下不适用, 列表生成式过复杂反而会导致阅读和调试困难** ```Python # 不推荐的写法 items = [] for item in directory: items.append(item) # 正确的写法 items = [item for item in directory] ``` * 尽量使用map和filter等内置函数, 而不是自己去写循环 ```Python numbers = [1, 2, 6, 9, 10 ...] # 不推荐的写法 def even(numbers): evens = [] for number in numbers: if number % 2 == 0: evens.append(number) return even # 正确的写法 def even(numbers): return filter(lambda x: x%2 == 0, numbers) ``` ## 正则表达式 * 正则表达式前一律加r ```Python regex_phone = re.compile(r'(13\d|14[57]|15[^4,\D]))$') ``` * 正则表达式使用前尽量先编译好 ```Python # 不推荐的写法, 不要使用未编译的正则 result = re.match(r'(^(13\d|14[57]|15[^4,\D]))$', my_phone) # 正确的写法,使用前先编译 regex_phone = re.compile(r'(13\d|14[57]|15[^4,\D]))$') if __name__ == '__main__': result = regex_phone.match(my_phone) ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 简明概述 ## 编码 * 如无特殊情况, 文件一律使用UTF-8编码 * 如无特殊情况, 文件头部必须加入`#-*-coding:utf-8-*-`标识 ## 代码格式 ### 缩进 * 统一使用4个空格进行缩进 ### 行宽 每行代码尽量不超过80个字符(在特殊情况下可以略微超过80,但最长不得超过120) 理由: * 这在查看side-by-side的diff时很有帮助 * 方便在控制台下查看代码 * 太长可能是设计有缺陷 ### 引号 简单说,自然语言使用双引号,机器标示使用单引号,因此 __代码里__ 多数应该使用 __单引号__ * ***自然语言*** **使用双引号** `"..."` 例如错误信息;很多情况还是unicode,使用`u"你好世界"` * ***机器标识*** **使用单引号** `'...'` 例如dict里的key * ***正则表达式*** **使用原生的双引号** `r"..."` * ***文档字符串(docstring)*** **使用三个双引号** `"""......"""` ### 空行 * 模块级函数和类定义之间空两行; * 类成员函数之间空一行; ```python class A: def __init__(self): pass def hello(self): pass def main(): pass ``` * 可以使用多个空行分隔多组相关的函数 * 函数中可以使用空行分隔出逻辑相关的代码 ### 编码 * 文件使用UTF-8编码 * 文件头部加入`#-*-conding:utf-8-*-`标识 ## import语句 * import语句应该分行书写 ```python # 正确的写法 import os import sys # 不推荐的写法 import sys,os # 正确的写法 from subprocess import Popen, PIPE ``` * import语句应该使用 __absolute__ import ```python # 正确的写法 from foo.bar import Bar # 不推荐的写法 from ..bar import Bar ``` * import语句应该放在文件头部,置于模块说明及docstring之后,于全局变量之前; * import语句应该按照顺序排列,每组之间用一个空行分隔 ```python import os import sys import msgpack import zmq import foo ``` * 导入其他模块的类定义时,可以使用相对导入 ```python from myclass import MyClass ``` * 如果发生命名冲突,则可使用命名空间 ```python import bar import foo.bar bar.Bar() foo.bar.Bar() ``` ## 空格 * 在二元运算符两边各空一格`[=,-,+=,==,>,in,is not, and]`: ```python # 正确的写法 i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # 不推荐的写法 i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) ``` * 函数的参数列表中,`,`之后要有空格 ```python # 正确的写法 def complex(real, imag): pass # 不推荐的写法 def complex(real,imag): pass ``` * 函数的参数列表中,默认值等号两边不要添加空格 ```python # 正确的写法 def complex(real, imag=0.0): pass # 不推荐的写法 def complex(real, imag = 0.0): pass ``` * 左括号之后,右括号之前不要加多余的空格 ```python # 正确的写法 spam(ham[1], {eggs: 2}) # 不推荐的写法 spam( ham[1], { eggs : 2 } ) ``` * 字典对象的左括号之前不要多余的空格 ```python # 正确的写法 dict['key'] = list[index] # 不推荐的写法 dict ['key'] = list [index] ``` * 不要为对齐赋值语句而使用的额外空格 ```python # 正确的写法 x = 1 y = 2 long_variable = 3 # 不推荐的写法 x = 1 y = 2 long_variable = 3 ``` ### 换行 Python支持括号内的换行。这时有两种情况。 1) 第二行缩进到括号的起始处 ```python foo = long_function_name(var_one, var_two, var_three, var_four) ``` 2) 第二行缩进4个空格,适用于起始括号就换行的情形 ```python def long_function_name( var_one, var_two, var_three, var_four): print(var_one) ``` 使用反斜杠`\`换行,二元运算符`+` `.`等应出现在行末;长字符串也可以用此法换行 ```python session.query(MyTable).\ filter_by(id=1).\ one() print 'Hello, '\ '%s %s!' %\ ('Harry', 'Potter') ``` 禁止复合语句,即一行中包含多个语句: ```python # 正确的写法 do_first() do_second() do_third() # 不推荐的写法 do_first();do_second();do_third(); ``` `if/for/while`一定要换行: ```python # 正确的写法 if foo == 'blah': do_blah_thing() # 不推荐的写法 if foo == 'blah': do_blash_thing() ``` ## 注释 ###块注释 “#”号后空一格,段落件用空行分开(同样需要“#”号) ```python # 块注释 # 块注释 # # 块注释 # 块注释 ``` ### 行注释 至少使用两个空格和语句分开,注意不要使用无意义的注释 ```python # 正确的写法 x = x + 1 # 边框加粗一个像素 # 不推荐的写法(无意义的注释) x = x + 1 # x加1 ``` ## docstring docstring的规范在 [PEP 257](http://www.python.org/dev/peps/pep-0257/) 中有详细描述,其中最其本的两点: 1. 所有的公共模块、函数、类、方法,都应该写docstring。私有方法不一定需要,但应该在def后提供一个块注释来说明。 2. docstring的结束"""应该独占一行,除非此docstring只有一行。 ```python """Return a foobar Optional plotz says to frobnicate the bizbaz first. """ """Oneline docstring""" ``` ## 命名规范 * 应避免使用小写字母l(L),大写字母O(o)或I(i)单独作为一个变量的名称,以区分数字1和0 * 包和模块使用全小写命名,尽量不要使用下划线 * 类名使用CamelCase命名风格,内部类可用一个下划线开头 * 函数使用下划线分隔的小写命名 * 当参数名称和Python保留字冲突,可在最后添加一个下划线,而不是使用缩写或自造的词 * 常量使用以下划线分隔的大写命名 ```python MAX_OVERFLOW = 100 Class FooBar: def foo_bar(self, print_): print(print_) ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 命名 ## 应该避免的名称 以下命名应该尽量避免 * 单字符名称, 除了计数器和迭代器. ```python if __name__ == '__main__': # 不推荐的写法 # 尽量避免单字符变量名 s = "hello world!" ``` * 包/模块名中的连字符(-) ```python # 错误的包名 # 引用文件 html-parser.py import html-parser # 正确的写法 # 文件名应为 html_parser.py import html_parser ``` * 双下划线开头并结尾的名称(Python保留, 例如\_\_init\_\_) * 应避免使用小写字母l(L),大写字母O(o)或I(i)单独作为一个变量的名称,以区分数字1和0 ```python if __name__ == '__main__': # 不推荐的写法 # 尽量避免l、O 等容易混淆的字母 l = 1 O = 0 l = (O + 1)*l ``` * 当参数名称和Python保留字冲突,可在最后添加一个下划线,而不是使用缩写或自造的词 ```python # 如果变量名和python保留字冲突,则在末尾添加下划线 # 切记不要自己造词,或者使用缩写 def print_(): ... ... if __name__ == '__main__': str_ = "hello world!" print_(str_) ``` ## 命名约定 ### 模块 * 模块尽量使用小写命名,首字母保持小写,尽量不要用下划线(除非多个单词,且数量不多的情况) ```python # 正确的模块名 import decoder import html_parser # 不推荐的模块名 import Decoder ``` ### 类名 * 类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头 ```Python class Farm(): pass class AnimalFarm(Farm): pass class _PrivateFarm(Farm): pass ``` * 将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块. ### 函数 * 函数名一律小写,如有多个单词,用下划线隔开 ```python def run(): pass def run_with_env(): pass ``` * 私有函数在函数前加一个下划线_ ```python class Person(): def _private_func(): pass ``` ### 变量名 * 变量名尽量小写, 如有多个单词,用下划线隔开 ```python if __name__ == '__main__': count = 0 school_name = '' ``` * 常量采用全大写,如有多个单词,使用下划线隔开 ```python MAX_CLIENT = 100 MAX_CONNECTION = 1000 CONNECTION_TIMEOUT = 600 ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 注释和文档 代码注释和文档(docstring)的规范, 参考并综合了[PEP257](https://www.python.org/dev/peps/pep-0257/)、 [Google Python Style Guide](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/example_google.html) 和 [Numpy](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt)的文档标准. ## 注释 * 单行注释和多行注释, 请参考本章第一小节 * 在代码的关键部分(或比较复杂的地方), 能写注释的要尽量写注释 * 比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性 ```python app = create_app(name, options) # ===================================== # 请勿在此处添加 get post等app路由行为 !!! # ===================================== if __name__ == '__main__': app.run() ``` ## 文档注释(Docstring) 作为文档的Docstring一般出现在模块头部、函数和类的头部,这样在python中可以通过对象的\_\_doc\_\_对象获取文档. 编辑器和IDE也可以根据Docstring给出自动提示. * 文档注释以 """ 开头和结尾, 首行不换行, 如有多行, 末行必需换行, 以下是Google的docstring风格示例 ```python # -*- coding: utf-8 -*- """Example docstrings. This module demonstrates documentation as specified by the `Google Python Style Guide`_. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text. Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. """ ``` * 不要在文档注释复制函数定义原型, 而是具体描述其具体内容, 解释具体参数和返回值等 ```python # 不推荐的写法(不要写函数原型等废话) def function(a, b): """function(a, b) -> list""" ... ... # 正确的写法 def function(a, b): """计算并返回a到b范围内数据的平均值""" ... ... ``` * 对函数参数、返回值等的说明采用numpy标准, 如下所示 ```python def func(arg1, arg2): """在这里写函数的一句话总结(如: 计算平均值). 这里是具体描述. 参数 ---------- arg1 : int arg1的具体描述 arg2 : int arg2的具体描述 返回值 ------- int 返回值的具体描述 参看 -------- otherfunc : 其它关联函数等... 示例 -------- 示例使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行 >>> a=[1,2,3] >>> print [x + 3 for x in a] [4, 5, 6] """ ``` * 文档注释不限于中英文, 但不要中英文混用 * 文档注释不是越长越好, 通常一两句话能把情况说清楚即可 * 模块、公有类、公有方法, 能写文档注释的, 应该尽量写文档注释
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# python代码规范 本代码规范基于[PEP8](https://www.python.org/dev/peps/pep-0008/), 在PEP8的基础上做了一些改动。
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 单元测试的书写规范 ## 一个单元测试样例的规则 - 完全自动运行,而不需要人工干预。单元测试几乎是全自动的。 - 自主判断被测试的方法是通过还是失败,而不需要人工解释结果。 - 独立运行,而不依赖其它测试用例(即使测试的是同样的方法)。即,每一个测试用例都是一个孤岛。 - 每一个独立的测试都有它自己的不含参数及没有返回值的方法。如果方法不抛出异常而正常退出则认为测试通过;否则,测试失败。 ## 测试文件的位置及命名规则 1. 为了编写测试用例,首先使该测试用例类成为unittest 模块的TestCase 类的子类。TestCase 提供了很多你可以用于测试特定条件的测试用例的有用的方法。 2. 所有测试样例放在项目根目录下的 test 文件夹中,如果你的所有测试都在一个文件中,也可以省略文件夹,直接把这个文件放在根目录下,命名为`test_your_project.py` (例如`test_requests.py`)。 3. 如前一个测试用例,创建一个继承于 unittest.TestCase 的类。你可以在每个类中实现多个测试(正如你在本节中将会看到的一样),但是我却选择了创建一个新类,因为该测试与上一个有点不同。这样,我们可以把正常输入的测试跟非法输入的测试分别放入不同的两个类中。 4. 测试本身是类一个方法,并且该方法以 test 开头命名。 5. 当你改变条件的时候,要确保同步更新那些提示错误信息的可读字符串。unittest 框架并不关心这些,但是如果你的代码抛出描述不正确的异常信息的话会使得手工调试代码变得困难。 6. 出现频率较多和不明朗的方法,需要加注释,比如`test_string`如果不加注释很难让人读懂测试的是哪一个 string。 我们以bottle的测试为例: ```python import unittest from tools import warn from bottle import MakoTemplate, mako_template, mako_view, touni class TestMakoTemplate(unittest.TestCase): def test_string(self): """ Templates: Mako string""" t = MakoTemplate('start ${var} end').render(var='var') self.assertEqual('start var end', t) def test_file(self): """ Templates: Mako file""" t = MakoTemplate(name='./views/mako_simple.tpl').render(var='var') self.assertEqual('start var end\n', t) # ... ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
> 本文参考了 _Div Into Python3_ 以及 stackoverflow 上的一些答案 # 什么是单元测试 单元测试是对软件的基本组成单位进行的测试,目的是检验软件基本组成单位的正确性。 单元测试是整个以测试为中心的开发策略中的一个重要部分。编写单元测试应该安排在项目的早期,同时要让它随同代码及需求变更一起更新。 当然,任何时间编写单元测试都是有好处的。 # 单元测试的优点 - 在编写代码之前,通过编写单元测试来强迫你使用有用的方式细化你的需求。 - 在编写代码时,单元测试可以使你避免过度编码。当所有测试用例通过时,实现的方法就完成了。 - 重构代码时,单元测试用例有助于证明新版本的代码跟老版本功能是一致的。 - 在维护代码期间,如果有人对你大喊:你最新的代码修改破坏了原有代码的状态,那么此时单元测试可以帮助你反驳(“先生,所有单元测试用例通过了我才提交代码的...”)。 - 在团队编码中,缜密的测试套件可以降低你的代码影响别人代码的机会,这是因为你需要优先执行别人的单元测试用例。(我曾经在代码冲刺见过这种实践。一个团队把任务分解,每个人领取其中一小部分任务,同时为其编写单元测试;然后,团队相互分享他们的单元测试用例。这样,所有人都可以在编码过程中提前发现谁的代码与其他人的不可以良好工作。) # Python 中的单元测试 这是一张很知名的玩笑式的Python学习曲线: ![python_learning_curves](https://raw.githubusercontent.com/Dobiasd/articles/master/programming_language_learning_curves/python.png) 它确实说明了一些问题,总体上Python程序员的自我评估一直高于实际的产出,但是写了测试之后会提高生产力,掌握了装饰(bi)器之后,以为自己更牛×了,实际上并没有,因为装饰器不过是一个卡新手的语法糖。 Python 在Web方向上被国内很多中小型公司大规模使用,但是由于追求所谓的产品快速上线和"敏捷开发",很多创业公司盲目学习 Facebook 之类的公司不配备测试职位,却没有一个优秀的团队来把测试工作顺带完成,导致很多项目不重视测试,甚至不写单元测试也是常有的事。
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 单元测试框架的选择 选择框架之前首先要确认一下我们的选项概念和她们之间的区别。 ### PyUnit PyUnit(The Python unit testing framework) 是 Kent Beck 和 Erich Gamma 所设计的 JUnit 的 Python 版本。从 Python 2.1 版本后,PyUnit 成为 Python 标准库的一部分。 这就是我们日常使用的 unittest 。它太过优秀了,以至于我们几乎没有必要再用别的测试框架了。 下面这个例子,是bottle框架下测试首页的简单例子,首先是bottle的代码: ```python #!/usr/bin/env python # encoding: utf-8 import bottle @bottle.route('/') def index(): return 'Hi!' if __name__ == '__main__': bottle.run() ``` 这是单元测试的代码: ```python #!/usr/bin/env python # encoding: utf-8 import mywebapp import unittest class TestBottle(unittest.TestCase): def test_webapp_index(self): assert mywebapp.index() == 'Hi!' if __name__ == '__main__': unittest.main() ``` 直接运行这个文件就可以了,可以看到在普通模式,和verbosity模式下的返回结果: 普通模式: ``` . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ``` verbosity模式: ``` test_webapp_index (__main__.TestBottle) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ``` 表示我们的测试都通过了。 ### doctest doctest 也是 Python 标准库的一部分。 doctest 可以用来写一些比较简单的测试,也可以用来检查文档和注释能否解释当前版本的代码。 ### pytest pytest 也是一个很流行的测试框架,是很多公司的首选。 看一份邮件流吧,一些工程师阐述了他们为什么会选择使用pytest: [我是邮件链接](http://thread.gmane.org/gmane.comp.python.testing.general/3748) ### nose nose 并不是一个真正的测试框架,它只是一个很优秀的测试执行器,是unittest的拓展。 它的官方也是这样介绍自己的:nose extends unittest to make testing easier. nose 可以运行由PyUnit(unittest), doctest,[pytest](https://github.com/pytest-dev/pytest)创建的测试。
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 单元测试规范 关于单元测试的规范
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 静态文件 > 如无特殊说明,本文中的静态文件是指web项目中的图片、css、js等静态资源而言(有cdn的需求) 1. 为了便于部署时使用cdn加速,静态文件应该统一存放于项目根目录下的```static```文件夹中 2. 为了便于统一管理,favicon.ico文件也应该放置于static文件夹中, 在html中使用link方式引用 ```html <!DOCTYPE html> <html> <head> <title>标题</title> <link rel="shortcut icon" href="http://www.xxx.com/图标的地址.../favicon.ico"> </head> ... ... ``` 3. 引用静态文件时,**不要用绝对路径**,可以使用django的static模板标签,或flask的url_for自动生成 * django 静态文件引用示例 ```html {% raw %} {% load staticfiles %} <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> {% endraw %} ``` * flask 静态文件引用示例 ```html {% raw %} <img src="{% url_for "my_app/myexample.jpg" %}" alt="My image"/> {% endraw %} ``` * 不恰当的静态文件引用方式 ```html <img src="/static/img/pic1.jpg" alt="My image"/> ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 配置文件和数据 1. 如框架无特殊规定,配置文件应放置于**项目根目录下的```config```文件夹中** 2. 配置文件在部署、预发布、生产环境、开发环境等环境中会有很大差异,因此请**不要将配置文件在上传到git、svn等版本库中**, 而是建议在版本库中上传一个配置的**示例文件**(如:config.example) 3. 上传到版本库中配置示例文件**不允许出现密码、证书、token等敏感信息** 4. 数据和程序应该尽量分离,不要将数据写在代码中,需要持久化存储数据必须使用数据库
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 项目目录结构示例 以下是一个web项目的目录结构示例 ``` .project_root/ 项目根目录 | ├── app/ app代码等(不限定,可根据实际情况命名和确定结构) │   ├── .../ │   ├── .../ │   └── ... ├── config/ 配置文件夹 │   ├── config.ini 配置文件(应该被版本库ignore掉) │   └── config.ini.example 配置文件示例 ├── static/ 静态文件夹 │   ├── css/ │   ├── img/ │   ├── js/ │   └── favicon.ico 网站图标 ├── README.md 项目说明文件 ├── requrements.txt 项目依赖文件 ├── TODO.md 待完成项目 └── .gitignore 版本库ignore文件 ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 包和依赖 1. 如无特殊情况,项目的包管理器**一律使用pip** 2. 项目**根目录下必须包含requirements.txt文件**,作为项目依赖的显示声明文件 3. 所有依赖都必须显示声明,禁止隐式依赖,例如: ```python # 错误,依赖的wget在别的系统环境下很可能不存在 def download(url): os.system('wget %s' % url) ``` 以上代码隐式依赖了wget,但很有可能开发环境中有wget,而在部署环境下根本不存在, 这样部署app时就很可能出错! 4. 依赖声明文件中不应该包含项目中没有用到的依赖 5. 建议在开发项目时使用virtualenv做依赖隔离,便于使用pip freeze自动生成 ```sh # 自动生成requirement.txt示例 $ pip freeze > requirements.txt ```
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 项目规范 关于python项目(尤其是web项目)的规范
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# Python的轮子 -- 常用的包、库、软件 一些比较好用的 Python 框架、库、软件等的合集, 基于[awesome-python](https://github.com/vinta/awesome-python). - [目录](#常用的包、库、软件) - [Python环境管理](#Python环境管理) - [包管理工具](#包管理工具) - [打包发布工具](#打包发布工具) - [交互式工具(REPL)](#交互式工具(REPL)) - [文件](#文件) - [时间和日期](#时间和日期) - [文本处理](#文本处理) - [特定文本格式处理(word、excel、pdf、markdown等)](#特定文本格式处理(word、excel、pdf、markdown等)) - [自然语言处理](#自然语言处理) - [文档工具](#文档工具) - [配置](#配置) - [图片](#图片) - [文字识别(OCR)](#文字识别(OCR)) - [音频](#音频) - [视频](#视频) - [地理位置](#地理位置) - [HTTP](#http) - [数据库](#数据库) - [数据库驱动(连接件)](#数据库驱动(连接件)) - [数据库对象关系模型映射(orm)](#数据库对象关系模型映射(orm)) - [Web框架](#Web框架) - [内容管理系统(CMS)](#内容管理系统(CMS)) - [电子商务](#电子商务) - [RESTful API 框架](#restful-api-框架) - [授权(Authentication)](#授权(Authentication)) - [模版引擎](#模版引擎) - [任务队列](#任务队列) - [搜索工具](#搜索工具) - [Feed工具](#Feed工具) - [网站资源管理(压缩、最小化等)](#网站资源管理) - [缓存](#caching) - [电子邮件(email)](#电子邮件(email)) - [国际化(多语言)](#国际化(多语言)) - [URL处理](#URL处理) - [HTML处理](#HTML处理) - [Web爬虫](#Web爬虫) - [Web内容解析](#Web内容解析) - [数据验证](#数据验证) - [管理界面](#管理界面) - [静态网站生成](#静态网站生成) - [进程管理](#进程管理) - [并发和并行](#并发和并行) - [网络](#网络) - [WebSocket处理](#WebSocket处理) - [WSGI服务器](#WSGI服务器) - [远程调用服务](#远程调用服务) - [加解密](#加解密) - [图形界面(GUI)](#图形界面(GUI)) - [游戏开发](#游戏开发) - [日志工具](#日志工具) - [测试](#测试) - [代码分析和优化](#代码分析和优化) - [调试工具](#调试工具) - [科学算和数据分析](#科学计算和数据分析) - [数据可视化](#数据可视化) - [计算机图形学](#计算机图形学) - [机器学习](#机器学习) - [函数式编程](#函数式编程) - [MapReduce](#mapreduce) - [运维开发工具](#运维开发工具) - [任务调度](#任务调度) - [使用其它语言扩展Python](#使用其它语言扩展Python) - [高性能](#高性能) - [Windows工具](#Windows工具) - [网络虚拟化和SDN](#网络虚拟化和SDN) - [硬件](#硬件) - [兼容性](#兼容性) - [开发者插件](#开发者插件) - [IDEs](#ides) - [Python资源](#Python资源) - [网站](#网站) - [网站](#网站) - [Twitter](#twitter) - - - ## Python环境管理 *Python版本和虚拟环境管理.* * [virtualenv](https://pypi.python.org/pypi/virtualenv) - 最常用的Python虚拟环境管理工具. * [p](https://github.com/qw3rtman/p) - 非常简单的Python版本管理工具. * [pyenv](https://github.com/yyuu/pyenv) - 简单的Python版本管理工具. * [PyRun](https://www.egenix.com/products/python/PyRun/) - 一个单文件、免安装的Python运行环境. * [Vex](https://github.com/sashahart/vex) - 在virtualenv中运行命令的工具. * [virtualenvwrapper](https://pypi.python.org/pypi/virtualenvwrapper) - virtualenv的插件合集. ## 包管理工具 *包和依赖管理工具.* * [pip](https://pip.pypa.io/) - 即Python Package Index, 最常用的Python包管理工具. * 官方网站 [Python Package Index](https://pypi.python.org/pypi) * [pip-tools](https://github.com/nvie/pip-tools) - 保持pip的包最新的同步工具. * [conda](https://github.com/conda/conda/) - 跨平台的二进制包管理工具. * [Curdling](http://clarete.li/curdling/) - 命令行包管理工具. * [wheel](http://pythonwheels.com/) - 标准Python打包工具(用来替代eggs). ## 打包发布工具 *打包发布和安装包制作工具.* * [PyInstaller](https://github.com/pyinstaller/pyinstaller) - 将Python程序转换为跨平台的可执行程序(客户无需安装python即可运行). * [dh-virtualenv](http://dh-virtualenv.readthedocs.org/) - 将virtualenv环境打包成可发布的Debian软件包. * [Nuitka](http://nuitka.net/) - 将python脚本、模块、包编译成可执行或可扩展模块. * [py2app](http://pythonhosted.org/py2app/) - Python代码打包成 Mac OS X App 的工具. * [py2exe](http://www.py2exe.org/) - Python转exe(Windows). * [pynsist](http://pynsist.readthedocs.org/) - Windows安装包制作工具,会将Python一起打包. ## 交互式工具(REPL) *交互式Python执行工具 (REPL).* * [IPython](https://github.com/ipython/ipython) - 强大,比较常用的Python交互shell. * [bpython](http://bpython-interpreter.org) – 一个便捷的Python交互工具. * [ptpython](https://github.com/jonathanslenders/ptpython) - 先进的Python交互工具. ## 文件 *文件操作和MIME类型描述等.* * [imghdr](https://docs.python.org/2/library/imghdr.html) - (Python内置标准库) 判断图片类型的库. * [mimetypes](https://docs.python.org/2/library/mimetypes.html) - (Python内置标准库) 获取文件的MIME类型描述. * [path.py](https://github.com/jaraco/path.py) - [os.path](https://docs.python.org/2/library/os.path.html)的便捷版本. * [pathlib](https://pathlib.readthedocs.org/en/pep428/) - (Python3.4+ 内置标准库) 跨平台的文件路径库. * [python-magic](https://github.com/ahupp/python-magic) - libmagic 的便捷版本. * [Unipath](https://github.com/mikeorr/Unipath) - 一个面向对象的文件和目录操作库. * [watchdog](https://github.com/gorakhargosh/watchdog) - 监视文件系统改动的库. ## 时间和日期 *关于时间和日期的库.* * [arrow](https://github.com/crsmithdev/arrow) - 更好用的时间日期库. * [Chronyk](https://github.com/KoffeinFlummi/Chronyk) - Python3 时间日期解析库. * [dateutil](https://pypi.python.org/pypi/python-dateutil) - Python标准模块 [datetime](https://docs.python.org/2/library/datetime.html) 的扩展. * [delorean](https://github.com/myusuf3/delorean/) - 处理跨时区、时间和日期的库. * [moment](https://github.com/zachwill/moment) - 时间日期处理库,[Moment.js](http://momentjs.com/)的Python 版. * [PyTime](https://github.com/shnode/PyTime) - 易用的的时间处理库,把date/time/datetime当成string来处理. * [pytz](https://launchpad.net/pytz) - 世界时区的库. 使用 [tz database](http://en.wikipedia.org/wiki/Tz_database). * [when.py](https://github.com/dirn/When.py) - 用户友好的时间日期操作库. ## 文本处理 *解析和操作普通文本的库.* * 通用 * [chardet](https://github.com/chardet/chardet) - 兼容 Python 2/3 的字符编码检测. * [difflib](https://docs.python.org/2/library/difflib.html) - (Python内置标准库) 差异计算工具. * [esmre](https://code.google.com/p/esmre/) - 正则表达式加速器. * [ftfy](https://github.com/LuminosoInsight/python-ftfy) - Unicode文本乱码自动修复. * [fuzzywuzzy](https://github.com/seatgeek/fuzzywuzzy) - 文本模糊匹配(包含相似度计算). * [Levenshtein](https://github.com/ztane/python-Levenshtein/) - 字符串莱文斯坦距离和相似度计算. * [pangu.py](https://github.com/vinta/pangu.py) - 中日韩文分词库. * [pyfiglet](https://github.com/pwaller/pyfiglet) - figlet的Python实现. * [shortuuid](https://github.com/stochastic-technologies/shortuuid) - 简洁,唯一,URL安全的UUID生成器. * [unidecode](https://pypi.python.org/pypi/Unidecode) - Unicode转ASCII. * [uniout](https://github.com/moskytw/uniout) - 打印可读的字符串(自动消除转义). * [xpinyin](https://github.com/lxneng/xpinyin) - 将中文汉字转化为拼音. * 字符串转义(Slugify) * [awesome-slugify](https://github.com/dimka665/awesome-slugify) - 不转换unicode的slugify库. * [python-slugify](https://github.com/un33k/python-slugify) - slugify库,将会把unicode转成ASCII. * [unicode-slugify](https://github.com/mozilla/unicode-slugify) - slugify库, 支持unicode. * 解析器(Parser) * [phonenumbers](https://github.com/daviddrysdale/python-phonenumbers) - 解析、格式化、存储和验证电话号码. * [PLY](http://www.dabeaz.com/ply/) - lex 和 yacc 解析工具的python实现. * [Pygments](http://pygments.org/) - (编程语言)文本语法高亮工具. * [pyparsing](http://pyparsing.wikispaces.com/) - 通用parser生成框架. * [python-nameparser](https://github.com/derek73/python-nameparser) - 人名解析器(英文). * [python-user-agents](https://github.com/selwin/python-user-agents) - 浏览器user-agent解析器. * [sqlparse](https://sqlparse.readthedocs.org/) - SQL语句解析器. ## 特定文本格式处理(word、excel、pdf、markdown等) *解析和处理特定文本格式的库.* * 通用 * [tablib](https://github.com/kennethreitz/tablib) - XLS, CSV, JSON, YAML处理. * Office * [Marmir](https://github.com/brianray/mm) - 把Python数据结构转化成表格. * [openpyxl](https://openpyxl.readthedocs.org/en/latest/) - 读写微软Excel 2010 xlsx/xlsm/xltx/xltm 文件. * [python-docx](https://github.com/python-openxml/python-docx) - 读写微软Word 2007/2008 docx文件. * [unoconv](https://github.com/dagwieers/unoconv) - LibreOffice/OpenOffice 文档格式转化. * [XlsxWriter](https://xlsxwriter.readthedocs.org/) - 创建 .xlsx 文件的库. * [xlwings](http://xlwings.org/) - 读写 Excel. * [xlwt](https://github.com/python-excel/xlwt) / [xlrd](https://github.com/python-excel/xlrd) - 读写 Excel 文件. * [relatorio](http://relatorio.tryton.org/) - OpenDocument文件模版库. * PDF * [PDFMiner](https://github.com/euske/pdfminer) - 读取PDF文档. * [PyPDF2](https://github.com/mstamy2/PyPDF2) - 切分、合并、转换PDF文档 * [ReportLab](http://www.reportlab.com/opensource/) - 快速创建PDF文档. * Markdown * [Mistune](https://github.com/lepture/mistune) - 快速,功能齐全的Markdown解析器. * [Python-Markdown](https://github.com/waylan/Python-Markdown) - John Gruber的Markdown的Python实现. * YAML * [PyYAML](http://pyyaml.org/) - YAML的Python实现. * CSV * [csvkit](https://github.com/onyxfish/csvkit) - CSV转化和操作库. * 压缩文件 * [unp](https://github.com/mitsuhiko/unp) - 压缩文件处理库(.tar, .gz, .zip, .7z, .bz, .rar 等). ## 自然语言处理 *自然语言处理库.* * [NLTK](http://www.nltk.org/) - 最常用的Python自然语言处理平台. * [jieba](https://github.com/fxsjy/jieba) - 中文分词. * [langid.py](https://github.com/saffsd/langid.py) - 自动判断语言类型(可判别英文、中文等97种语言). * [Pattern](http://www.clips.ua.ac.be/pattern) - 网络文本挖掘和分析. * [SnowNLP](https://github.com/isnowfy/snownlp) - 中文文本处理库(分词、词性、情感分析等). * [TextBlob](http://textblob.readthedocs.org/) - 便捷的NLP通用库. ## 文档工具 *生成项目文档的工具.* * [Sphinx](http://sphinx-doc.org/) - 功能强大的文档生成器,广泛用于Python社区的各种文档. * [MkDocs](http://www.mkdocs.org/) - 使用Markdown的文档生成器. * [pdoc](https://github.com/BurntSushi/pdoc) - 自动为Python库生成文档. * [Pycco](http://fitzgen.github.io/pycco/) - "文艺编程"风格的文档生成器. ## 配置 *存储和解析配置的库.* * [config](http://www.red-dove.com/config-doc/) * [ConfigObj](http://www.voidspace.org.uk/python/configobj.html) - INI配置文件处理. * [ConfigParser](https://docs.python.org/2/library/configparser.html) - (Python内置标准库) 解析INI文件. * [profig](http://profig.readthedocs.org/) - 可解析多种配置文件格式. * [python-decouple](https://github.com/henriquebastos/python-decouple) - Strict separation of settings from code. ## 图片 *Libraries for manipulating images.* * [pillow](http://pillow.readthedocs.org/) - Pillow is the friendly [PIL](http://www.pythonware.com/products/pil/) fork. * [hmap](https://github.com/rossgoodwin/hmap) - Image histogram remapping. * [imgSeek](http://www.imgseek.net/) - A project for searching a collection of images using visual similarity. * [nude.py](https://github.com/hhatto/nude.py) - Nudity detection. * [pyBarcode](https://pythonhosted.org/pyBarcode/) - Create barcodes in Python without needing PIL. * [pygram](https://github.com/ajkumar25/pygram) - Instagram-like image filters. * [python-qrcode](https://github.com/lincolnloop/python-qrcode) - A pure Python QR Code generator. * [Quads](https://github.com/fogleman/Quads) - Computer art based on quadtrees. * [scikit-image](http://scikit-image.org/) - A Python library for (scientific) image processing. * [thumbor](https://github.com/thumbor/thumbor) - A smart imaging service. It enables on-demand crop, re-sizing and flipping of images. * [wand](https://github.com/dahlia/wand) - Python bindings for [MagickWand](http://www.imagemagick.org/script/magick-wand.php), C API for ImageMagick. ## 文字识别(OCR) *文字识别库, OCR(Optical Character Recognition).* * [pyocr](https://github.com/jflesch/pyocr) - A wrapper for Tesseract and Cuneiform. * [pytesseract](https://github.com/madmaze/pytesseract) - Another wrapper for Google Tesseract OCR. * [python-tesseract](https://code.google.com/p/python-tesseract) - A wrapper class for [Google Tesseract OCR](https://code.google.com/p/tesseract-ocr/). ## 音频 *Libraries for manipulating audio.* * [audiolazy](https://github.com/danilobellini/audiolazy) - Expressive Digital Signal Processing (DSP) package for Python. * [audioread](https://github.com/sampsyo/audioread) - Cross-library (GStreamer + Core Audio + MAD + FFmpeg) audio decoding. * [beets](http://beets.radbox.org/) - A music library manager and [MusicBrainz](https://musicbrainz.org/) tagger. * [dejavu](https://github.com/worldveil/dejavu) - Audio fingerprinting and recognition. * [django-elastic-transcoder](https://github.com/StreetVoice/django-elastic-transcoder) - Django + [Amazon Elastic Transcoder](http://aws.amazon.com/elastictranscoder/). * [eyeD3](http://eyed3.nicfit.net/) - A tool for working with audio files, specifically MP3 files containing ID3 metadata. * [id3reader](http://nedbatchelder.com/code/modules/id3reader.py) - A Python module for reading MP3 meta data. * [m3u8](https://github.com/globocom/m3u8) - A module for parsing m3u8 file. * [mutagen](https://bitbucket.org/lazka/mutagen) - A Python module to handle audio metadata. * [pydub](https://github.com/jiaaro/pydub) - Manipulate audio with a simple and easy high level interface. * [pyechonest](https://github.com/echonest/pyechonest) - Python client for the [Echo Nest](http://developer.echonest.com/docs/) API. * [talkbox](http://scikits.appspot.com/talkbox) - A Python library for speech/signal processing. * [TimeSide](https://github.com/yomguy/TimeSide) - Open web audio processing framework. * [tinytag](https://github.com/devsnd/tinytag) - A library for reading music meta data of MP3, OGG, FLAC and Wave files. * [mingus](http://bspaans.github.io/python-mingus/) - An advanced music theory and notation package with MIDI file and playback support. ## 视频 *Libraries for manipulating video and GIFs.* * [moviepy](http://zulko.github.io/moviepy/) - A module for script-based movie editing with many formats, including animated GIFs. * [scikit-video](https://github.com/aizvorski/scikit-video) - Video processing routines for SciPy. ## 地理位置 *Libraries for geocoding addresses and working with latitudes and longitudes.* * [GeoDjango](https://docs.djangoproject.com/en/dev/ref/contrib/gis/) - A world-class geographic web framework. * [GeoIP](https://github.com/maxmind/geoip-api-python) - Python API for MaxMind GeoIP Legacy Database. * [geojson](https://github.com/frewsxcv/python-geojson) - Python bindings and utilities for GeoJSON. * [geopy](https://github.com/geopy/geopy) - Python Geocoding Toolbox. * [pygeoip](https://github.com/appliedsec/pygeoip) - Pure Python GeoIP API. * [django-countries](https://github.com/SmileyChris/django-countries) - A Django app that provides country choices for use with forms, flag icons static files, and a country field for models. ## HTTP *Libraries for working with HTTP.* * [requests](http://docs.python-requests.org/) - HTTP Requests for Humans™. * [grequests](https://github.com/kennethreitz/grequests) - requests + gevent for asynchronous HTTP requests. * [httplib2](https://github.com/jcgregorio/httplib2) - Comprehensive HTTP client library. * [treq](https://github.com/dreid/treq) - Python requests like API built on top of Twisted's HTTP client. * [urllib3](https://github.com/shazow/urllib3) - A HTTP library with thread-safe connection pooling, file post support, sanity friendly. ## 数据库 *用Python写的数据库.* * [pickleDB](https://pythonhosted.org/pickleDB/) - A simple and lightweight key-value store for Python. * [PipelineDB](http://www.pipelinedb.com/) - The Streaming SQL Database. * [TinyDB](https://github.com/msiemens/tinydb) - A tiny, document-oriented database. * [ZODB](http://www.zodb.org/) - A native object database for Python. A key-value and object graph database. ## 数据库驱动(连接件) *连接和操作数据库.* * MySQL * [mysql-python](http://sourceforge.net/projects/mysql-python/) - Python默认的MySQL连接件. * [mysqlclient](https://github.com/PyMySQL/mysqlclient-python) - 支持Python 3,是mysql-python的一个分支. * [PyMySQL](https://github.com/PyMySQL/PyMySQL) - 纯Python MySQL连接件,兼容mysql-python. * [oursql](https://pythonhosted.org/oursql/) - 一个更好用的MySQL连接件. * PostgreSQL * [psycopg2](http://initd.org/psycopg/) - 最常用的PostgreSQL连接件. * [queries](https://github.com/gmr/queries) - A wrapper of the psycopg2 library for interacting with PostgreSQL. * [txpostgres](http://txpostgres.readthedocs.org/) - Twisted based asynchronous driver for PostgreSQL. * 其它关系型数据库 * [apsw](http://rogerbinns.github.io/apsw/) - Another Python SQLite wrapper. * [dataset](https://github.com/pudo/dataset) - Store Python dicts in a database - works with SQLite, MySQL, and PostgreSQL. * [pymssql](http://www.pymssql.org/) - A simple database interface to Microsoft SQL Server. * NoSQL数据库 * [cassandra-python-driver](https://github.com/datastax/python-driver) - Python driver for Cassandra. * [HappyBase](http://happybase.readthedocs.org/) - A developer-friendly library for Apache HBase. * [Plyvel](https://plyvel.readthedocs.org/) - A fast and feature-rich Python interface to LevelDB. * [py2neo](http://book.py2neo.org/) - Python wrapper client for Neo4j's restful interface. * [pycassa](https://github.com/pycassa/pycassa) - Python Thrift driver for Cassandra. * [PyMongo](http://docs.mongodb.org/ecosystem/drivers/python/) - The official Python client for MongoDB. * [redis-py](https://github.com/andymccurdy/redis-py) - The Redis Python Client. * [telephus](https://github.com/driftx/Telephus) - Twisted based client for Cassandra. * [txRedis](https://github.com/deldotdr/txRedis) - Twisted based client for Redis. ## 数据库对象关系模型映射(ORM) *Libraries that implement Object-Relational Mapping or data mapping techniques.* * 关系型数据库 * [Django Models](https://docs.djangoproject.com/en/dev/topics/db/models/) - A part of Django. * [SQLAlchemy](http://www.sqlalchemy.org/) - The Python SQL Toolkit and Object Relational Mapper. * [awesome-sqlalchemy](https://github.com/dahlia/awesome-sqlalchemy) * [Peewee](https://github.com/coleifer/peewee) - A small, expressive ORM. * [PonyORM](http://ponyorm.com) - ORM that provides a generator-oriented interface to SQL. * [python-sql](https://pypi.python.org/pypi/python-sql) - Write SQL queries pythonically. * NoSQL数据库 * [django-mongodb-engine](https://github.com/django-nonrel/mongodb-engine) - Django MongoDB Backend. * [PynamoDB](https://github.com/jlafon/PynamoDB) - A Pythonic interface for [Amazon DynamoDB](https://aws.amazon.com/dynamodb/). * [flywheel](https://github.com/mathcamp/flywheel) - Object mapper for Amazon DynamoDB. * [MongoEngine](http://mongoengine.org/) - A Python Object-Document-Mapper for working with MongoDB. * [hot-redis](https://github.com/stephenmcd/hot-redis) - Rich Python data types for Redis. * [redisco](https://github.com/kiddouk/redisco) - A Python Library for Simple Models and Containers Persisted in Redis. * 其它 * [butterdb](https://github.com/Widdershin/butterdb) - A Python ORM for Google Drive Spreadsheets. ## Web框架 *Full stack web frameworks.* * [Django](https://www.djangoproject.com/) - The most popular web framework in Python. * [awesome-django](https://github.com/rosarior/awesome-django) * [Flask](http://flask.pocoo.org/) - A microframework for Python. * [awesome-flask](https://github.com/humiaozuzu/awesome-flask) * [Pyramid](http://www.pylonsproject.org/) - A small, fast, down-to-earth, open source Python web framework. * [awesome-pyramid](https://github.com/ITCase/awesome-pyramid) * [Bottle](http://bottlepy.org/) - A fast, simple and lightweight WSGI micro web-framework. * [CherryPy](http://www.cherrypy.org/) - A minimalist Python web framework, HTTP/1.1-compliant and WSGI thread-pooled. * [TurboGears](http://www.turbogears.org/) - A microframework that can scale up to a full stack solution. * [web.py](http://webpy.org/) - A web framework for Python that is as simple as it is powerful. * [web2py](http://www.web2py.com) - A full stack web framework and platform focused in the ease of use. ## 内容管理系统(CMS) *Content Management Systems.* * [django-cms](https://www.django-cms.org/en/) - An Open source enterprise CMS based on the Django. * [djedi-cms](http://djedi-cms.org/) - A lightweight but yet powerful Django CMS with plugins, inline editing and performance in mind. * [FeinCMS](http://www.feincms.org/) - One of the most advanced Content Management Systems built on Django. * [Kotte](http://kotti.pylonsproject.org/) - A high-level, Pythonic web application framework built on Pyramid. * [Mezzanine](http://mezzanine.jupo.org/) - A powerful, consistent, and flexible content management platform. * [Opps](http://oppsproject.org/) - A Django-based CMS for magazines, newspapers websites and portals with high-traffic. * [Plone](http://plone.org/) - A CMS built on top of the open source application server Zope. * [Quokka](http://quokkaproject.org/) - Flexible, extensible, small CMS powered by Flask and MongoDB. * [Wagtail](http://wagtail.io/) - A Django content management system. * [Widgy](http://wid.gy/) - Last CMS framework, based on Django. ## 电子商务 *Frameworks and libraries for e-commerce and payments.* * [django-oscar](http://oscarcommerce.com/) - An open-source e-commerce framework for Django. * [django-shop](https://www.django-cms.org/) - A Django based shop system. * [Cartridge](https://github.com/stephenmcd/cartridge) - A shopping cart app built using the Mezzanine. * [shoop](https://www.shoop.io/) - An open source E-Commerce platform based on Django. * [alipay](https://github.com/lxneng/alipay) - Unofficial Alipay API for Python. * [merchant](https://github.com/agiliq/merchant) - A Django app to accept payments from various payment processors. * [money](https://github.com/carlospalol/money) - Money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution. * [python-currencies](https://github.com/Alir3z4/python-currencies) - Display money format and its filthy currencies. ## RESTful API 框架 *Libraries for developing RESTful APIs.* * Django * [django-rest-framework](http://www.django-rest-framework.org/) - A powerful and flexible toolkit to build web APIs. * [django-tastypie](http://tastypieapi.org/) - Creating delicious APIs for Django apps. * [django-formapi](https://github.com/5monkeys/django-formapi) - Create JSON APIs with Django's form validation. * Flask * [flask-api](http://www.flaskapi.org/) - Browsable Web APIs for Flask. * [flask-restful](http://flask-restful.readthedocs.org/) - Quickly building REST APIs for Flask. * [flask-restless](https://flask-restless.readthedocs.org/en/latest/) - Generating RESTful APIs for database models defined with SQLAlchemy. * [flask-api-utils](https://github.com/marselester/flask-api-utils) - Taking care of API representation and authentication for Flask. * [eve](https://github.com/nicolaiarocci/eve) - REST API framework powered by Flask, MongoDB and good intentions. * Pyramid * [cornice](https://cornice.readthedocs.org/) - A REST framework for Pyramid. * 其它 * [falcon](http://falconframework.org/) - A high-performance framework for building cloud APIs and web app backends. * [sandman](https://github.com/jeffknupp/sandman) - Automated REST APIs for existing database-driven systems. * [restless](http://restless.readthedocs.org/en/latest/) - Framework agnostic REST framework based on lessons learned from Tastypie. * [ripozo](https://github.com/vertical-knowledge/ripozo) - Quickly creating REST/HATEOAS/Hypermedia APIs. ## 授权(Authentication) *Libraries for implementing authentications schemes.* * OAuth * [Authomatic](http://peterhudec.github.io/authomatic/) - Simple but powerful framework agnostic authentication/authorization client. * [django-allauth](https://github.com/pennersr/django-allauth) - Authentication app for Django that "just works." * [django-oauth-toolkit](https://github.com/evonove/django-oauth-toolkit) - OAuth2 goodies for the Djangonauts. * [django-oauth2-provider](https://github.com/caffeinehit/django-oauth2-provider) - Providing OAuth2 access to Django app. * [Flask-OAuthlib](https://github.com/lepture/flask-oauthlib) - OAuth 1.0/a, 2.0 implementation of client and provider for Flask. * [OAuthLib](https://github.com/idan/oauthlib) - A generic and thorough implementation of the OAuth request-signing logic. * [python-oauth2](https://github.com/simplegeo/python-oauth2) - A fully tested, abstract interface to creating OAuth clients and servers. * [python-social-auth](https://github.com/omab/python-social-auth) - An easy-to-setup social authentication mechanism. * [rauth](https://github.com/litl/rauth) - A Python library for OAuth 1.0/a, 2.0, and Ofly. * [sanction](https://github.com/demianbrecht/sanction) - A dead simple OAuth2 client implementation. * 其它 * [jose](https://github.com/demonware/jose) - JavaScript Object Signing and Encryption draft implementation. * [PyJWT](https://github.com/progrium/pyjwt) - Implementation of the JSON Web Token draft 01. * [python-jws](https://github.com/brianloveswords/python-jws) - Implementation of JSON Web Signatures draft 02. * [python-jwt](https://github.com/davedoesdev/python-jwt) - Module for generating and verifying JSON Web Tokens. ## 模板引擎 *Libraries and tools for templating and lexing.* * [Jinja2](https://github.com/mitsuhiko/jinja2) - A modern and designer friendly templating language. * [Chameleon](https://chameleon.readthedocs.org/) - An HTML/XML template engine. Modeled after ZPT, optimized for speed. * [Genshi](http://genshi.edgewall.org/) - Python templating toolkit for generation of web-aware output. * [Mako](http://www.makotemplates.org/) - Hyperfast and lightweight templating for the Python platform. * [Spitfire](https://code.google.com/p/spitfire/) - A very fast Python template compiler. ## 任务队列 *Libraries for working with event and task queues.* * [celery](http://www.celeryproject.org/) - An asynchronous task queue/job queue based on distributed message passing. * [huey](https://github.com/coleifer/huey) - Little multi-threaded task queue. * [mrq](https://github.com/pricingassistant/mrq) - Mr. Queue - A distributed worker task queue in Python using Redis & gevent. * [rq](http://python-rq.org/) - Simple job queues for Python. * [simpleq](https://github.com/rdegges/simpleq) - A simple, infinitely scalable, Amazon SQS based queue. ## 搜索工具 *Libraries and software for indexing and performing search queries on data.* * [django-haystack](https://github.com/toastdriven/django-haystack) - Modular search for Django. * [elasticsearch-py](http://www.elasticsearch.org/guide/en/elasticsearch/client/python-api/current/) - The official low-level Python client for [Elasticsearch](https://www.elastic.co/products/elasticsearch). * [elasticsearch-dsl-py](https://github.com/elastic/elasticsearch-dsl-py) - The official high-level Python client for Elasticsearch. * [solrpy](https://code.google.com/p/solrpy/) - A Python client for [solr](http://lucene.apache.org/solr/). * [Whoosh](http://whoosh.readthedocs.org/) - A fast, pure Python search engine library. ## Feed工具 *Libraries for building user's activities.* * [django-activity-stream](https://github.com/justquick/django-activity-stream) - Generating generic activity streams from the actions on your site. * [Stream-Framework](https://github.com/tschellenbach/Stream-Framework) - Building newsfeed and notification systems using Cassandra and Redis. ## 网站资源管理(压缩、最小化等) *Tools for managing, compressing and minifying website assets.* * [django-compressor](https://github.com/django-compressor/django-compressor) - Compresses linked and inline JavaScript or CSS into a single cached file. * [django-storages](http://code.larlet.fr/django-storages/) - A collection of custom storage back ends for Django. * [fanstatic](http://www.fanstatic.org/) - Packages, optimizes, and serves static file dependencies as Python packages. * [File Conveyor](http://fileconveyor.org/) - A daemon to detect and sync files to CDNs, S3 and FTP. * [Flask-Assets](http://flask-assets.readthedocs.org/) - Helps you integrate webassets into your Flask app. * [glue](http://gluecss.com) - Glue is a simple command line tool to generate CSS sprites. * [jinja-assets-compressor](https://github.com/jaysonsantos/jinja-assets-compressor) - A Jinja extension to compile and compress your assets. * [webassets](http://webassets.readthedocs.org/) - Bundles, optimizes, and manages unique cache-busting URLs for static resources. ## 缓存 *Libraries for caching data.* * [Beaker](http://beaker.readthedocs.org/) - A library for caching and sessions for use with web applications and stand-alone Python scripts and applications. * [django-cache-machine](https://github.com/jbalogh/django-cache-machine) - Automatic caching and invalidation for Django models. * [django-cacheops](https://github.com/Suor/django-cacheops) - A slick ORM cache with automatic granular event-driven invalidation. * [django-viewlet](https://github.com/5monkeys/django-viewlet) - Render template parts with extended cache control. * [dogpile.cache](http://dogpilecache.readthedocs.org/) - dogpile.cache is next generation replacement for Beaker made by same authors. * [HermesCache](https://pypi.python.org/pypi/HermesCache) - Python caching library with tag-based invalidation and dogpile effect prevention. * [johnny-cache](https://github.com/jmoiron/johnny-cache) - A caching framework for django applications. * [pylibmc](https://github.com/lericson/pylibmc) - A Python wrapper around the [libmemcached](http://libmemcached.org/libMemcached.html) interface. ## 电子邮件(email) *Libraries for sending and parsing email.* * [django-celery-ses](https://github.com/StreetVoice/django-celery-ses) - Django email back end with AWS SES and Celery. * [envelopes](http://tomekwojcik.github.io/envelopes/) - Mailing for human beings. * [flanker](https://github.com/mailgun/flanker) - A email address and Mime parsing library. * [imbox](https://github.com/martinrusev/imbox) - Python IMAP for Humans. * [inbox.py](https://github.com/kennethreitz/inbox.py) - Python SMTP Server for Humans. * [inbox](https://github.com/inboxapp/inbox) - The open source email toolkit. * [lamson](https://github.com/zedshaw/lamson) - Pythonic SMTP Application Server. * [mailjet](https://github.com/WoLpH/mailjet) - Mailjet API implementation for batch mailing, statistics and more. * [marrow.mailer](https://github.com/marrow/marrow.mailer) - High-performance extensible mail delivery framework. * [modoboa](https://github.com/tonioo/modoboa) - A mail hosting and management platform including a modern and simplified Web UI. * [pyzmail](http://www.magiksys.net/pyzmail/) - Compose, send and parse emails. * [Talon](https://github.com/mailgun/talon) - Mailgun library to extract message quotations and signatures. ## 国际化(多语言) *Libraries for working with i18n.* * [Babel](http://babel.pocoo.org/) - An internationalization library for Python. * [Korean](https://korean.readthedocs.org/) - A library for [Korean](http://en.wikipedia.org/wiki/Korean_language) morphology. ## URL处理 *Libraries for parsing URLs.* * [furl](https://github.com/gruns/furl) - A small Python library that makes manipulating URLs simple. * [purl](https://github.com/codeinthehole/purl) - A simple, immutable URL class with a clean API for interrogation and manipulation. * [pyshorteners](https://github.com/ellisonleao/pyshorteners) - A pure Python URL shortening lib. * [short_url](https://github.com/Alir3z4/python-short_url) - Python implementation for generating Tiny URL and bit.ly-like URLs. * [webargs](https://github.com/sloria/webargs) - A friendly library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, and Pyramid. ## HTML处理 *Libraries for working with HTML and XML.* * [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) - Providing Pythonic idioms for iterating, searching, and modifying HTML or XML. * [bleach](http://bleach.readthedocs.org/) - A whitelist-based HTML sanitization and text linkification library. * [cssutils](https://pypi.python.org/pypi/cssutils/) - A CSS library for Python. * [html5lib](https://github.com/html5lib/html5lib-python) - A standards-compliant library for parsing and serializing HTML documents and fragments. * [lxml](http://lxml.de/) - A very fast, easy-to-use and versatile library for handling HTML and XML. * [MarkupSafe](https://github.com/mitsuhiko/markupsafe) - Implements a XML/HTML/XHTML Markup safe string for Python. * [pyquery](https://github.com/gawel/pyquery) - A jQuery-like library for parsing HTML. * [untangle](https://github.com/stchris/untangle) - Converts XML documents to Python objects for easy access. * [xhtml2pdf](https://github.com/chrisglass/xhtml2pdf) - HTML/CSS to PDF converter. * [xmltodict](https://github.com/martinblech/xmltodict) - Working with XML feel like you are working with JSON. ## Web爬虫 *Libraries for scraping websites.* * [Scrapy](http://scrapy.org/) - A fast high-level screen scraping and web crawling framework. * [cola](https://github.com/chineking/cola) - A distributed crawling framework. * [Demiurge](https://github.com/matiasb/demiurge) - PyQuery-based scraping micro-framework. * [feedparser](http://pythonhosted.org/feedparser/) - Universal feed parser. * [Grab](http://grablib.org/) - Site scraping framework. * [MechanicalSoup](https://github.com/hickford/MechanicalSoup) - A Python library for automating interaction with websites. * [portia](https://github.com/scrapinghub/portia) - Visual scraping for Scrapy. * [pyspider](https://github.com/binux/pyspider) - A powerful spider system. * [RoboBrowser](https://github.com/jmcarp/robobrowser) - A simple, Pythonic library for browsing the web without a standalone web browser. ## Web内容解析 *Libraries for extracting web contents.* * [Haul](https://github.com/vinta/Haul) - An Extensible Image Crawler. * [html2text](https://github.com/Alir3z4/html2text) - Convert HTML to Markdown-formatted text. * [lassie](https://github.com/michaelhelmick/lassie) - Web Content Retrieval for Humans. * [micawber](https://github.com/coleifer/micawber) - A small library for extracting rich content from URLs. * [newspaper](https://github.com/codelucas/newspaper) - News extraction, article extraction and content curation in Python. * [opengraph](https://github.com/erikriver/opengraph) - A Python module to parse the Open Graph Protocol * [python-goose](https://github.com/grangier/python-goose) - HTML Content/Article Extractor. * [python-readability](https://github.com/buriy/python-readability) - Fast Python port of arc90's readability tool. * [sanitize](https://github.com/Alir3z4/sanitize) - Bringing sanity to world of messed-up data. * [sumy](https://github.com/miso-belica/sumy) - A module for automatic summarization of text documents and HTML pages. * [textract](https://github.com/deanmalmgren/textract) - Extract text from any document, Word, PowerPoint, PDFs, etc. ## 数据验证 *Libraries for validating data. Used for forms in many cases.* * [Cerberus](http://python-cerberus.org) - A mappings-validator with a variety of rules, normalization-features and simple customization that uses a pythonic schema-definition. * [colander](http://docs.pylonsproject.org/projects/colander/) - A system for validating and deserializing data obtained via XML, JSON, an HTML form post or any other equally simple data serialization. * [kmatch](https://github.com/ambitioninc/kmatch) - A language for matching/validating/filtering Python dictionaries. * [schema](https://github.com/halst/schema) - A library for validating Python data structures. * [Schematics](https://github.com/schematics/schematics) - Data Structure Validation. * [valideer](https://github.com/podio/valideer) - Lightweight extensible data validation and adaptation library. * [voluptuous](https://github.com/alecthomas/voluptuous) - A Python data validation library. It is primarily intended for validating data coming into Python as JSON, YAML, etc. ## 管理界面 *Libraries for administrative interfaces.* * [Ajenti](https://github.com/Eugeny/ajenti) - The admin panel your servers deserve. * [django-suit](http://djangosuit.com/) - Alternative Django Admin-Interface (free only for Non-commercial use). * [django-xadmin](https://github.com/sshwsfc/django-xadmin) - Drop-in replacement of Django admin comes with lots of goodies. * [flask-admin](https://github.com/mrjoes/flask-admin) - Simple and extensible administrative interface framework for Flask. * [flower](https://github.com/mher/flower) - Real-time monitor and web admin for Celery. * [Grappelli](http://grappelliproject.com) – A jazzy skin for the Django Admin-Interface. * [Wooey](https://github.com/wooey/wooey) - A Django app which creates automatic web UIs for Python scripts. ## 静态网站生成 *Static site generator is a software that takes some text + templates as input and produces HTML files on the output.* * [Pelican](http://blog.getpelican.com/) - Uses Markdown or ReST for content and Jinja 2 for themes. Supports DVCS, Disqus. AGPL. * [Cactus](http://github.com/koenbok/Cactus/) – Static site generator for designers. * [Hyde](https://hyde.github.com/) - Jinja2-based static web site generator. * [Nikola](http://www.getnikola.com/) - A static website and blog generator. * [Tinkerer](http://tinkerer.me/) - Tinkerer is a blogging engine/.static website generator powered by Sphinx. ## 进程管理 *Libraries for starting and communicating with OS processes.* * [envoy](https://github.com/kennethreitz/envoy) - Python [subprocess](https://docs.python.org/2/library/subprocess.html) for Humans™. * [sarge](http://sarge.readthedocs.org/) - Yet another wrapper for subprocess. * [sh](https://github.com/amoffat/sh) - A full-fledged subprocess replacement for Python. ## 并发和并行 *Libraries for concurrent and parallel execution.* * [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) - (Python standard library) Process-based "threading" interface. * [threading](https://docs.python.org/2/library/threading.html) - (Python standard library) Higher-level threading interface. * [eventlet](http://eventlet.net/) - Asynchronous framework with WSGI support. * [gevent](http://www.gevent.org/) - A coroutine-based Python networking library that uses [greenlet](https://github.com/python-greenlet/greenlet). * [Tomorrow](https://github.com/madisonmay/Tomorrow) - Magic decorator syntax for asynchronous code. ## 网络 *Libraries for networking programming.* * [asyncio](https://docs.python.org/3/library/asyncio.html) - (Python standard library) Asynchronous I/O, event loop, coroutines and tasks. * [Tornado](http://www.tornadoweb.org/) - A Web framework and asynchronous networking library. * [Twisted](https://twistedmatrix.com/trac/) - An event-driven networking engine. * [pulsar](https://github.com/quantmind/pulsar) - Event-driven concurrent framework for Python. * [diesel](https://github.com/jamwt/diesel) - Greenlet-based event I/O Framework for Python. * [pyzmq](http://zeromq.github.io/pyzmq/) - A Python wrapper for the ZeroMQ message library. * [txZMQ](https://github.com/smira/txZMQ) - Twisted based wrapper for the ZeroMQ message library. ## WebSocket处理 *Libraries for working with WebSocket.* * [AutobahnPython](https://github.com/tavendo/AutobahnPython) - WebSocket & WAMP for Python on Twisted and [asyncio](https://docs.python.org/3/library/asyncio.html). * [Crossbar](https://github.com/crossbario/crossbar/) - Open-source Unified Application Router (Websocket & WAMP for Python on Autobahn). * [django-socketio](https://github.com/stephenmcd/django-socketio) - WebSockets for Django. * [WebSocket-for-Python](https://github.com/Lawouach/WebSocket-for-Python) - WebSocket client and server library for Python 2 and 3 as well as PyPy. ## WSGI服务器 *兼容WSGI的web服务器.* * [gunicorn](http://pypi.python.org/pypi/gunicorn) - Pre-forked, partly written in C. * [uwsgi](https://uwsgi-docs.readthedocs.org/en/latest/) - A project aims at developing a full stack for building hosting services, written in C. * [bjoern](http://pypi.python.org/pypi/bjoern) - Asynchronous, very fast and written in C. * [fapws3](http://www.fapws.org/) - Asynchronous (network side only), written in C. * [meinheld](http://pypi.python.org/pypi/meinheld) - Asynchronous, partly written in C. * [netius](https://github.com/hivesolutions/netius) - Asynchronous, very fast. * [paste](http://pythonpaste.org/) - Multi-threaded, stable, tried and tested. * [rocket](http://pypi.python.org/pypi/rocket) - Multi-threaded. * [waitress](https://waitress.readthedocs.org/) - Multi-threaded, poweres Pyramid. * [Werkzeug](http://werkzeug.pocoo.org/) - A WSGI utility library for Python that powers Flask and can easily be embedded into your own projects. ## 远程调用 *RPC-compatible servers.* * [SimpleJSONRPCServer](https://github.com/joshmarshall/jsonrpclib/) - This library is an implementation of the JSON-RPC specification. * [SimpleXMLRPCServer](https://docs.python.org/2/library/simplexmlrpcserver.html) - (Python standard library) Simple XML-RPC server implementation, single-threaded. * [zeroRPC](https://github.com/dotcloud/zerorpc-python) - zerorpc is a flexible RPC implementation based on [ZeroMQ](http://zeromq.org/) and [MessagePack](http://msgpack.org/). ## 加解密 * [cryptography](https://cryptography.io/) - A package designed to expose cryptographic primitives and recipes to Python developers. * [hashids](https://github.com/davidaurelio/hashids-python) - Implementation of [hashids](http://hashids.org) in Python. * [Paramiko](http://www.paramiko.org/) - A Python (2.6+, 3.3+) implementation of the SSHv2 protocol, providing both client and server functionality. * [Passlib](https://pythonhosted.org/passlib/) - Secure password storage/hashing library, very high level. * [PyCrypto](https://www.dlitz.net/software/pycrypto/) - The Python Cryptography Toolkit. * [PyNacl](https://github.com/pyca/pynacl) - Python binding to the Networking and Cryptography (NaCl) library. ## 图形界面(GUI) *Libraries for working with graphical user interface applications.* * [curses](https://docs.python.org/2/library/curses.html#module-curses) - Built-in wrapper for [ncurses](http://www.gnu.org/software/ncurses/) used to create terminal GUI applications. * [enaml](https://github.com/nucleic/enaml) - Creating beautiful user-interfaces with Declaratic Syntax like QML. * [kivy](http://kivy.org/) - A library for creating NUI applications, running on Windows, Linux, Mac OS X, Android and iOS. * [pyglet](http://www.pyglet.org/) - A cross-platform windowing and multimedia library for Python. * [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) - Python bindings for the [Qt](http://qt-project.org/) cross-platform application and UI framework, with support for both Qt v4 and Qt v5 frameworks. * [PySide](http://qt-project.org/wiki/pyside) - Python bindings for the [Qt](http://qt-project.org/) cross-platform application and UI framework, supporting the Qt v4 framework. * [Tkinter](https://wiki.python.org/moin/TkInter) - Tkinter is Python's de-facto standard GUI package. * [Toga](https://github.com/pybee/toga) - A Python native, OS native GUI toolkit. * [urwid](http://urwid.org/) - A library for creating terminal GUI applications with strong support for widgets, events, rich colors, etc. * [wxPython](http://wxpython.org/) - A blending of the wxWidgets C++ class library with the Python. * [PyGObject](https://wiki.gnome.org/Projects/PyGObject) - Python Bindings for GLib/GObject/GIO/GTK+ (GTK+3) * [Flexx](https://github.com/zoofIO/flexx) - Flexx is a pure Python toolkit for creating GUI's, that uses web technology for its rendering. ## 游戏开发 *Awesome game development libraries.* * [Cocos2d](http://cocos2d.org/) - cocos2d is a framework for building 2D games, demos, and other graphical/interactive applications. It is based on pyglet. * [Panda3D](https://www.panda3d.org/) - 3D game engine developed by Disney and maintained by Carnegie Mellon's Entertainment Technology Center. Written in C++, completely wrapped in Python. * [Pygame](http://www.pygame.org/news.html) - Pygame is a set of Python modules designed for writing games. * [PyOgre](http://www.ogre3d.org/tikiwiki/PyOgre) - Python bindings for the Ogre 3D render engine, can be used for games, simulations, anything 3D. * [PyOpenGL](http://pyopengl.sourceforge.net/) - Python ctypes bindings for OpenGL and it's related APIs. * [PySDL2](http://pysdl2.readthedocs.org/) - A ctypes based wrapper for the SDL2 library. * [PySFML](http://www.python-sfml.org/) - Python bindings for [SFML](http://www.sfml-dev.org/) * [RenPy](http://www.renpy.org/) - A Visual Novel engine. ## 日志工具 *Libraries for generating and working with logs.* * [logging](https://docs.python.org/2/library/logging.html) - (Python standard library) Logging facility for Python. * [logbook](http://pythonhosted.org/Logbook/) - Logging replacement for Python. * [Eliot](https://eliot.readthedocs.org/) - Logging for complex & distributed systems. * [Raven](http://raven.readthedocs.org/) - The Python client for Sentry. * [Sentry](https://pypi.python.org/pypi/sentry) - A realtime logging and aggregation server. ## 测试 *Libraries for testing codebases and generating test data.* * 测试框架 * [unittest](https://docs.python.org/2/library/unittest.html) - (Python standard library) Unit testing framework. * [nose](https://nose.readthedocs.org/) - nose extends unittest. * [contexts](https://github.com/benjamin-hodgson/Contexts) - A BDD framework for Python 3.3+. Inspired by C#'s `Machine.Specifications`. * [hypothesis](https://github.com/DRMacIver/hypothesis) - Hypothesis is an advanced Quickcheck style property based testing library. * [mamba](https://nestorsalceda.github.io/mamba) - The definitive testing tool for Python. Born under the banner of BDD. * [PyAutoGUI](https://github.com/asweigart/pyautogui) - PyAutoGUI is a cross-platform GUI automation Python module for human beings. * [pyshould](https://github.com/drslump/pyshould) - Should style asserts based on [PyHamcrest](https://github.com/hamcrest/PyHamcrest). * [pytest](http://pytest.org/) - A mature full-featured Python testing tool. * [pyvows](http://heynemann.github.io/pyvows/) - BDD style testing for Python. Inspired by [Vows.js](http://vowsjs.org/). * [Robot Framework](https://github.com/robotframework/robotframework) - A generic test automation framework. * Web测试 * [Selenium](https://pypi.python.org/pypi/selenium) - Python bindings for [Selenium](http://www.seleniumhq.org/) WebDriver. * [locust](https://github.com/locustio/locust) - Scalable user load testing tool written in Python. * [sixpack](https://github.com/seatgeek/sixpack) - A language-agnostic A/B Testing framework. * [splinter](https://splinter.readthedocs.org/en/latest/) - Open source tool for testing web applications. * Mock * [mock](https://docs.python.org/3/library/unittest.mock.html) - (Python standard library) A mocking and patching library. * [doublex](https://pypi.python.org/pypi/doublex) - Powerful test doubles framework for Python. * [freezegun](https://github.com/spulec/freezegun) - Travel through time by mocking the datetime module. * [httmock](https://github.com/patrys/httmock) - A mocking library for requests for Python 2.6+ and 3.2+. * [httpretty](http://falcao.it/HTTPretty/) - HTTP request mock tool for Python. * [responses](https://github.com/dropbox/responses) - A utility library for mocking out the requests Python library. * [VCR.py](https://github.com/kevin1024/vcrpy) - Record and replay HTTP interactions on your tests. * 对象工厂 * [factory_boy](https://github.com/rbarrois/factory_boy) - A test fixtures replacement for Python. * [mixer](https://github.com/klen/mixer) - Another fixtures replacement. Supported Django, Flask, SQLAlchemy, Peewee and etc. * [model_mommy](https://github.com/vandersonmota/model_mommy) - Creating random fixtures for testing in Django. * 代码覆盖率 * [coverage](https://pypi.python.org/pypi/coverage) - Code coverage measurement. * 伪数据(生成) * [faker](http://www.joke2k.net/faker/) - A Python package that generates fake data. * [fake2db](https://github.com/emirozer/fake2db) - Fake database generator. * [radar](https://pypi.python.org/pypi/radar) - Generate random datetime / time. * 错误处理 * [FuckIt.py](https://github.com/ajalt/fuckitpy) - FuckIt.py uses state-of-the-art technology to make sure your Python code runs whether it has any right to or not. ## 代码分析和优化 *Libraries and tools for analysing, parsing and manipulation codebases.* * 代码分析 * [code2flow](https://github.com/scottrogowski/code2flow) - Turn your Python and JavaScript code into DOT flowcharts. * [pycallgraph](https://github.com/gak/pycallgraph) - A library that visualises the flow (call graph) of your Python application. * [pysonar2](https://github.com/yinwang0/pysonar2) - A type inferencer and indexer for Python. * 代码检查和优化 * [Flake8](https://pypi.python.org/pypi/flake8) - The modular source code checker: pep8, pyflakes and co. * [Pylint](http://www.pylint.org/) - A source code analyzer. * [pylama](https://pylama.readthedocs.org/) - Code audit tool for Python and JavaScript. ## 调试工具 *Libraries for debugging code.* * 调试器 * [ipdb](https://pypi.python.org/pypi/ipdb) - IPython-enabled [pdb](https://docs.python.org/2/library/pdb.html). * [pudb](https://pypi.python.org/pypi/pudb) – A full-screen, console-based Python debugger. * [pyringe](https://github.com/google/pyringe) - Debugger capable of attaching to and injecting code into Python processes. * [wdb](https://github.com/Kozea/wdb) - An improbable web debugger through WebSockets. * [winpdb](http://winpdb.org/) - A Python Debugger with GUI, capable of remote debugging based on `rpdb2`. * [django-debug-toolbar](https://github.com/django-debug-toolbar/django-debug-toolbar) - Display various debug information for Django. * [django-devserver](https://github.com/dcramer/django-devserver) - A drop-in replacement for Django's runserver. * [flask-debugtoolbar](https://github.com/mgood/flask-debugtoolbar) - A port of the django-debug-toolbar to flask. * 性能分析 * [line_profiler](https://github.com/rkern/line_profiler) - Line-by-line profiling. * [memory_profiler](https://github.com/fabianp/memory_profiler) - Monitor Memory usage of Python code. * [profiling](https://github.com/what-studio/profiling) - An interactive Python profiler. * 其它 * [pyelftools](https://github.com/eliben/pyelftools) - Parsing and analyzing ELF files and DWARF debugging information. * [python-statsd](https://github.com/WoLpH/python-statsd) - Python Client for the [statsd](https://github.com/etsy/statsd/) server. ## 科学计算和数据分析 *Libraries for scientific computing and data analyzing.* * [astropy](http://www.astropy.org/) - A community Python library for Astronomy. * [bcbio-nextgen](https://github.com/chapmanb/bcbio-nextgen) - A toolkit providing best-practice pipelines for fully automated high throughput sequencing analysis. * [bccb](https://github.com/chapmanb/bcbb) - Collection of useful code related to biological analysis. * [Biopython](http://biopython.org/wiki/Main_Page) - Biopython is a set of freely available tools for biological computation. * [blaze](http://blaze.pydata.org/en/latest/) - NumPy and Pandas interface to Big Data. * [cclib](http://cclib.github.io/) - A library for parsing and interpreting the results of computational chemistry packages. * [NetworkX](https://networkx.github.io/) - A high-productivity software for complex networks. * [Neupy](http://neupy.com/pages/home.html) - Running and testing different Artificial Neural Networks algorithms. * [Numba](http://numba.pydata.org/) - Python JIT (just in time) complier to LLVM aimed at scientific Python by the developers of Cython and NumPy. * [NumPy](http://www.numpy.org/) - A fundamental package for scientific computing with Python. * [Open Babel](http://openbabel.org/wiki/Main_Page) - A chemical toolbox designed to speak the many languages of chemical data. * [Open Mining](https://github.com/avelino/mining) - Business Intelligence (BI) in Python (Pandas web interface) * [orange](http://orange.biolab.si/) - Data mining, data visualization, analysis and machine learning through visual programming or Python scripting. * [Pandas](http://pandas.pydata.org/) - A library providing high-performance, easy-to-use data structures and data analysis tools. * [PyDy](https://pydy.org/) - Short for Python Dynamics, used to assist with workflow in the modeling of dynamic motion based around NumPy, SciPy, IPython, and matplotlib. * [PyMC](https://github.com/pymc-devs/pymc3) - Markov Chain Monte Carlo sampling toolkit. * [RDKit](http://www.rdkit.org/) - Cheminformatics and Machine Learning Software. * [SciPy](http://www.scipy.org/) - A Python-based ecosystem of open-source software for mathematics, science, and engineering. * [statsmodels](https://github.com/statsmodels/statsmodels) - Statistical modeling and econometrics in Python. * [SymPy](https://github.com/sympy/sympy) - A Python library for symbolic mathematics. * [zipline](https://github.com/quantopian/zipline) - A Pythonic algorithmic trading library. ## 数据可视化 *Libraries for visualizing data. See: [awesome-javascript](https://github.com/sorrycc/awesome-javascript#data-visualization).* * [matplotlib](http://matplotlib.org/) - A Python 2D plotting library. * [bokeh](https://github.com/ContinuumIO/bokeh) - Interactive Web Plotting for Python. * [ggplot](https://github.com/yhat/ggplot) - Same API as ggplot2 for R. * [plotly](https://plot.ly/python) - Collaborative web plotting for Python and matplotlib. * [pygal](http://pygal.org/) - A Python SVG Charts Creator. * [pygraphviz](https://pypi.python.org/pypi/pygraphviz) - Python interface to [Graphviz](http://www.graphviz.org/). * [PyQtGraph](http://www.pyqtgraph.org/) - Interactive and realtime 2D/3D/Image plotting and science/engineering widgets. * [SnakeViz](https://jiffyclub.github.io/snakeviz) - A browser based graphical viewer for the output of Python's cProfile module. * [vincent](https://github.com/wrobstory/vincent) - A Python to Vega translator. * [VisPy](http://vispy.org/) - High-performance scientific visualization based on OpenGL. ## 视觉计算 *Libraries for computer vision.* * [OpenCV](http://opencv.org/) - Open Source Computer Vision Library. * [SimpleCV](http://simplecv.org/) - An open source framework for building computer vision applications. ## 机器学习 *Libraries for Machine Learning. See: [awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning#python).* * [Crab](https://github.com/muricoca/crab) - A flexible, fast recommender engine. * [gensim](https://github.com/piskvorky/gensim) - Topic Modelling for Humans. * [hebel](https://github.com/hannes-brt/hebel) - GPU-Accelerated Deep Learning Library in Python. * [NuPIC](https://github.com/numenta/nupic) - Numenta Platform for Intelligent Computing. * [pattern](https://github.com/clips/pattern) - Web mining module for Python. * [PyBrain](https://github.com/pybrain/pybrain) - Another Python Machine Learning Library. * [Pylearn2](https://github.com/lisa-lab/pylearn2) - A Machine Learning library based on [Theano](https://github.com/Theano/Theano). * [python-recsys](https://github.com/ocelma/python-recsys) - A Python library for implementing a Recommender System. * [scikit-learn](http://scikit-learn.org/) - A Python module for machine learning built on top of SciPy. * [vowpal_porpoise](https://github.com/josephreisinger/vowpal_porpoise) - A lightweight Python wrapper for [Vowpal Wabbit](https://github.com/JohnLangford/vowpal_wabbit/). ## MapReduce *Framworks and libraries for MapReduce.* * [dpark](https://github.com/douban/dpark) - Python clone of Spark, a MapReduce alike framework in Python. * [dumbo](https://github.com/klbostee/dumbo) - Python module that allows one to easily write and run Hadoop programs. * [luigi](https://github.com/spotify/luigi) - A module that helps you build complex pipelines of batch jobs. * [mrjob](https://github.com/Yelp/mrjob) - Run MapReduce jobs on Hadoop or Amazon Web Services. * [PySpark](http://spark.apache.org/docs/latest/programming-guide.html) - The Spark Python API. * [streamparse](https://github.com/Parsely/streamparse) - Run Python code against real-time streams of data. Integrates with [Apache Storm](https://storm.incubator.apache.org/). ## 函数式编程 *Functional Programming with Python.* * [CyToolz](https://github.com/pytoolz/cytoolz/) - Cython implementation of Toolz: High performance functional utilities. * [fn.py](https://github.com/kachayev/fn.py) - Functional programming in Python: implementation of missing features to enjoy FP. * [funcy](https://github.com/Suor/funcy) - A fancy and practical functional tools. * [Toolz](https://github.com/pytoolz/toolz) - A collection of functional utilities for iterators, functions, and dictionaries. ## 运维开发工具 *Software and libraries for DevOps.* * [Ansible](https://github.com/ansible/ansible) - A radically simple IT automation platform. * [SaltStack](https://github.com/saltstack/salt) - Infrastructure automation and management system. * [OpenStack](http://www.openstack.org/) - Open source software for building private and public clouds. * [Docker Compose](https://docs.docker.com/compose/) - Fast, isolated development environments using [Docker](https://www.docker.com/). * [Fabric](http://www.fabfile.org/) - A simple, Pythonic tool for remote execution and deployment. * [cuisine](https://github.com/sebastien/cuisine) - Chef-like functionality for Fabric. * [Fabtools](https://github.com/ronnix/fabtools) - Tools for writing awesome Fabric files. * [gitapi](http://bitbucket.org/haard/gitapi) - Pure-Python API for Git. * [hgapi](http://bitbucket.org/haard/hgapi) - Pure-Python API for Mercurial. * [honcho](https://github.com/nickstenning/honcho) - A Python clone of [Foreman](https://github.com/ddollar/foreman), for managing Procfile-based applications. * [pexpect](https://github.com/pexpect/pexpect) - Controlling interactive programs in a pseudo-terminal like GNU expect. * [psutil](https://github.com/giampaolo/psutil) - A cross-platform process and system utilities module. * [supervisor](https://github.com/Supervisor/supervisor) - Supervisor process control system for UNIX. ## 任务调度 *Libraries for scheduling jobs.* * [APScheduler](http://apscheduler.readthedocs.org/) - A light but powerful in-process task scheduler that lets you schedule functions. * [django-schedule](https://github.com/thauber/django-schedule) - A calendaring app for Django. * [doit](http://pydoit.org/) - A task runner and build tool. * [gunnery](https://github.com/gunnery/gunnery) - Multipurpose task execution tool for distributed systems with web-based interface. * [Joblib](http://pythonhosted.org/joblib/index.html) - A set of tools to provide lightweight pipelining in Python. * [Plan](https://github.com/fengsp/plan) - Writing crontab file in Python like a charm. * [schedule](https://github.com/dbader/schedule) - Python job scheduling for humans. * [Spiff](https://github.com/knipknap/SpiffWorkflow) - A powerful workflow engine implemented in pure Python. * [TaskFlow](http://docs.openstack.org/developer/taskflow/) - A Python library that helps to make task execution easy, consistent and reliable. ## 使用其它语言扩展Python *Libraries for providing foreign function interface.* * [cffi](https://pypi.python.org/pypi/cffi) - Foreign Function Interface for Python calling C code. * [ctypes](https://docs.python.org/2/library/ctypes.html) - (Python standard library) Foreign Function Interface for Python calling C code. * [PyCUDA](http://mathema.tician.de/software/pycuda/) - A Python wrapper for Nvidia's CUDA API. * [SWIG](http://www.swig.org/Doc1.3/Python.html) - Simplified Wrapper and Interface Generator. ## 高性能 *Libraries for making Python faster.* * [Cython](http://cython.org/) - Optimizing Static Compiler for Python. Uses type mixins to compile Python into C or C++ modules resulting in large performance gains. * [PeachPy](https://github.com/Maratyszcza/PeachPy) - x86-64 assembler embedded in Python. Can be used as inline assembler for Python or as a stand-alone assembler for Windows, Linux, OS X, Native Client and Go. * [PyPy](http://pypy.org/) - An implementation of Python in Python. The interpreter uses black magic to make Python very fast without having to add in additional type information. * [Pyston](https://github.com/dropbox/pyston) - A Python implementation built using LLVM and modern JIT techniques with the goal of achieving good performance. * [Stackless Python](http://www.stackless.com/) - An enhanced version of the Python. ## Windows工具 *Python programming on Microsoft Windows.* * [Python(x,y)](https://code.google.com/p/pythonxy/) - Scientific-applications-oriented Python Distribution based on Qt and Spyder. * [pythonlibs](http://www.lfd.uci.edu/~gohlke/pythonlibs/) - Unofficial Windows binaries for Python extension packages. * [PythonNet](https://github.com/pythonnet/pythonnet) - Python Integration with the .NET Common Language Runtime (CLR). * [PyWin32](http://sourceforge.net/projects/pywin32/) - Python Extensions for Windows. * [WinPython](https://winpython.github.io/) - Portable development environment for Windows 7/8. ## 网络虚拟化和SDN *网络虚拟化和SDN(Software Defined Networking).* * [Mininet](http://mininet.org/) - A popular network emulator and API written in Python. * [POX](http://www.noxrepo.org/pox/about-pox/) - An open source development platform for Python-based Software Defined Networking (SDN) control applications, such as OpenFlow SDN controllers. * [Pyretic](http://frenetic-lang.org/pyretic/) - A member of the Frenetic family of SDN programming languages that provides powerful abstractions over network switches or emulators. * [SDX Platform](https://github.com/sdn-ixp/internet2award) - SDN based IXP implementation that leverages Mininet, POX and Pyretic. ## 硬件 *Libraries for programming with hardware.* * [ino](http://inotool.org/) - Command line toolkit for working with [Arduino](http://www.arduino.cc/). * [Pyro](http://pyrorobotics.com/) - Python Robotics. * [PyUserInput](https://github.com/SavinaRoja/PyUserInput) - A module for cross-platform control of the mouse and keyboard. * [scapy](http://www.secdev.org/projects/scapy/) - A brilliant packet manipulation library. * [wifi](https://wifi.readthedocs.org/) - A Python library and command line tool for working with WiFi on Linux. * [Pingo](http://pingo.io) - Pingo provides a uniform API to program devices like the Raspberry Pi, pcDuino, Intel Galileo, etc. ## 兼容性 *Python 2 和 3兼容性和转换工具.* * [Python-Future](http://python-future.org/index.html) - The missing compatibility layer between Python 2 and Python 3. * [Python-Modernize](https://github.com/mitsuhiko/python-modernize) - Modernizes Python code for eventual Python 3 migration. * [Six](https://pypi.python.org/pypi/six) - Python 2 and 3 compatibility utilities. ## 开发者插件 *各种编辑器和IDE的插件.* * Emacs * [Elpy](https://github.com/jorgenschaefer/elpy) - Emacs Python Development Environment. * Sublime Text * [SublimeJEDI](https://github.com/srusskih/SublimeJEDI) - A Sublime Text plugin to the awesome auto-complete library Jedi. * [Anaconda](https://github.com/DamnWidget/anaconda) - Anaconda turns your Sublime Text 3 in a full featured Python development IDE. * Vim * [YouCompleteMe](https://github.com/Valloric/YouCompleteMe) - Includes [Jedi](https://github.com/davidhalter/jedi)-based completion engine for Python. * [Jedi-vim](https://github.com/davidhalter/jedi-vim) - Vim bindings for the Jedi auto-completion library for Python. * [Python-mode](https://github.com/klen/python-mode) - An all in one plugin for turning Vim into a Python IDE. * Visual Studio * [PTVS](https://github.com/Microsoft/PTVS) - Python Tools for Visual Studio. ## IDEs *Popular Python IDEs.* * [PyCharm](https://www.jetbrains.com/pycharm/) - Commercial Python IDE by JetBrains. Has free community edition available. * [LiClipse](http://www.liclipse.com/) - Free polyglot IDE based on Eclipse. Uses PyDev for Python support. * [Spyder](https://github.com/spyder-ide/spyder) - Open Source Python IDE. # Python资源 Where to discover new Python libraries. ## 网站 * [r/Python](http://www.reddit.com/r/python) * [CoolGithubProjects](http://coolgithubprojects.com/) * [Django Packages](https://www.djangopackages.com/) * [Full Stack Python](http://www.fullstackpython.com/) * [Python 3 Wall of Superpowers](http://python3wos.appspot.com/) * [Python Hackers](http://pythonhackers.com/open-source/) * [Python ZEEF](https://python.zeef.com/alan.richmond) * [Trending Python repositories on GitHub today](https://github.com/trending?l=python) ## 周报 * [Import Python Newsletter](http://importpython.com/newsletter/) * [Pycoder's Weekly](http://pycoders.com/) * [Python Weekly](http://www.pythonweekly.com/) ## Twitter * [@codetengu](https://twitter.com/codetengu) * [@getpy](https://twitter.com/getpy) * [@planetpython](https://twitter.com/planetpython) * [@pycoders](https://twitter.com/pycoders) * [@pypi](https://twitter.com/pypi) * [@pythontrending](https://twitter.com/pythontrending) * [@PythonWeekly](https://twitter.com/PythonWeekly)
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# KISS -- keep it simple & small KISS原则是英语keep it simple & small, 或Keep It Simple, Stupid 的首字母缩略字。KISS原则是指在设计当中应当注重简约的原则。 KISS原则在设计上可能最被推崇的,在家装设计,界面设计,操作设计上,复杂的东西越来越被众人所BS了,而简单的东西越来越被人所认可,比如这些UI的设计和我们中国网页(尤其是新浪的网页)者是负面的例子。 “宜家”(IKEA)简约、效率的家居设计、生产思路;“微软”(Microsoft)“所见即所得”的理念;“谷歌”(Google)简约、直接的商业风格,无一例外的遵循了“kiss”原则,也正是“kiss”原则,成就了这些看似神奇的商业经典。而苹果公司的iPhone/iPad将这个原则实践到了极至。 把一个事情搞复杂是一件简单的事,但要把一个复杂的事变简单,这是一件复杂的事。 简单的东西往往更容易维护,更加稳定,也更加容易做好,这也是Unix的设计哲学(Less is more):各模块只做好自己该做的事情. 在软件设计的时候,我们也需要想清楚,某些东西是否真的需要, 也许[You aren't gonna need it](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it).
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# Lint工具--pylint
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# Python的哲学 在python命令行中输入import this, 就会打印出一段‘The Zen of Python’的描述: > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! 这就是python的设计哲学,即’python之禅‘,其中文翻译如下: > python之禅, by Tim Peters > > 优美胜于丑陋 > Beautiful is better than ugly. > 明了胜于晦涩 > Explicit is better than implicit. > 简单胜过复杂 > Simple is better than complex. > 复杂胜过凌乱 > Complex is better than complicated. > 扁平胜于嵌套 > Flat is better than nested. > 间隔胜于紧凑 > parse is better than dense. > 可读性很重要 > Readability counts. > 即使假借特例的实用性之名,也不可违背这些规则 > Special cases aren't special enough to break the rules. > 虽然实用性比纯粹性重要 > Although practicality beats purity. > 不要包容所有错误(精准地捕获异常) > Errors should never pass silently. > 除非你确定需要这样做 > Unless explicitly silenced. > 当存在多种可能时,不要尝试去猜测 > In the face of ambiguity, refuse the temptation to guess. > 而是尽量找一种,最好是唯一种明显的解决方案 > There should be one-- and preferably only one --obvious way to do it. > 虽然这并不容易,因为你不是 Python 之父 > Although that way may not be obvious at first unless you're Dutch. > 做也许好过不做 > Now is better than never. > 但不假思索就动手还不如不做 > Although never is often better than *right* now. > 如果你无法向人描述你的实现,那肯定不是一个好方案 > If the implementation is hard to explain, it's a bad idea. > 如果你很容易向人解释你的实现,那么它很可能是个好方案 > If the implementation is easy to explain, it may be a good idea. > 命名空间是一种绝妙的理念,应当多加利用 > Namespaces are one honking great idea -- let's do more of those! 如果说语言是一种工具,那么毫无疑问,不同工具会对思维方式产生不同影响, 也许python程序员大部分有极简主义倾向,讨厌复杂的东西,他们更加关注如何更快地get things done. python作为一种优雅的工具,有一些独到的优点: - 简洁 更少的代码, 更多的事情 - 库比较多 大量现成的轮子,更快的get things done - 语法清晰,可读性高 做一种事情通常只有一种最好的方法 我们应该充分运用这些优点,发挥更高的生产力,接下来的几节将描述致力于简洁性的DRY和KISS原则,以及介绍一些python好用的工具和轮子.
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# DRY原则 -- 不要重复你自己 Don't repeat yourself(不要重复你自己,简称DRY)是面向对象编程中的基本原则,程序员的行事准则。 旨在软件开发中,减少重复的信息。 DRY的原则是──系统中的每一部分,都必须有一个单一的、明确的、权威的代表──指的是(由人编写而非机器生成的)代码和测试所构成的系统,必须能够表达所应表达的内容,但是不能含有任何重复代码。 当DRY原则被成功应用时,一个系统中任何单个元素的修改都不需要与其逻辑无关的其他元素发生改变。此外,与之逻辑上相关的其他元素的变化均为可预见的、均匀的,并如此保持同步。 但过度的强调DRY,以及过早优化都是不对的,我们应该尽量避免过度抽象.有时候一定程度的冗余反而是好事. 关于抽象的原则,可以参看阮一峰的[这篇文章](http://www.ruanyifeng.com/blog/2013/01/abstraction_principles.html)
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 虚拟环境--virtualenv
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
# 优雅之道 > 关于工具,一个最重要的,也是最不易察觉的方面是,工具对使用此工具的人的习惯的潜移默化的影响。 > 如果这个工具是一门程序语言,不管我们是否喜欢它,它都会影响我们的思维惯式。 > > -- <cite>Edsger Dijkstra</cite> Python是一门优雅的语言,使用Python就意味着要用Python的思维方式。 实际上,很多人还用c语言的思维写Python, 这样写出来的代码读起来很费劲,而且效率也不高。 为了提高效率,本章介绍了一些python的设计哲学、设计原则、高效率的工具和轮子等。
{ "repo_name": "ee0703/python-style-guide", "stars": "113", "repo_language": "None", "file_name": "README.md", "mime_type": "text/plain" }
[egg_info] tag_date = 0 tag_svn_revision = 0 tag_build =
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
Metadata-Version: 1.1 Name: py-applescript Version: 1.0.1 Summary: An easy-to-use Python wrapper for NSAppleScript, allowing Python scripts to communicate with AppleScripts and AppleScriptable applications. Home-page: https://github.com/rdhyee/py-applescript Author: UNKNOWN Author-email: UNKNOWN License: Public Domain Description: UNKNOWN Platform: Mac OS X Classifier: License :: Public Domain Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: MacOS :: MacOS X Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Requires: pyobjc
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
py-applescript -- An easy-to-use Python wrapper for NSAppleScript, allowing Python scripts to communicate with AppleScripts and AppleScriptable applications. Features ======== - scripts may be compiled from source or loaded from disk - standard 'run' handler and user-defined handlers can be invoked with or without arguments - argument and result values are automatically converted between common Python types and their AppleScript equivalents - compiled scripts are persistent: handlers can be called multiple times and top-level properties retain their state - avoids any dependency on the legacy appscript library, flawed Scripting Bridge framework, or limited osascript executable Requirements ============ - Python 2.7.x or Python 3.x - PyObjC Installation ============ To install the applescript package, cd to the py-applescript-x.x.x directory and run: python setup.py install or: python3 setup.py install Interface ========= The applescript package exports four classes - AppleScript, ScriptError, AEType and AEEnum - plus one constant, kMissingValue, and one module, kae. AppleScript ----------- Represents a compiled AppleScript. The script object is persistent; its handlers may be called multiple times and its top-level properties will retain current state until the script object's disposal. Properties: source : str -- the script's source code Methods: __init__(self, source=None, path=None) source : str | None -- AppleScript source code path : str | None -- full path to .scpt/.applescript file Notes: - Either the path or the source argument must be provided. - If the script cannot be read/compiled, a ScriptError is raised. run(self, *args) -- Run the script, optionally passing arguments to its run handler. args : anything -- arguments to pass to script, if any; see also supported type mappings documentation Result : anything | None -- the script's return value, if any Notes: - The run handler must be explicitly declared in order to pass arguments. - AppleScript will ignore excess arguments. Passing insufficient arguments will result in an error. - If execution fails, a ScriptError is raised. call(self, name, *args) -- Call the specified user-defined handler. name : str -- the handler's name (case-sensitive) args : anything -- arguments to pass to script, if any; see documentation for supported types Result : anything | None -- the script's return value, if any Notes: - The handler's name must be a user-defined identifier, not an AppleScript keyword; e.g. 'myCount' is acceptable; 'count' is not. - AppleScript will ignore excess arguments. Passing insufficient arguments will result in an error. - If execution fails, a ScriptError is raised. ScriptError ----------- Indicates an AppleScript compilation/execution error. Properties: message : str -- the error message number : int | None -- the error number, if given appname : str | None -- the name of the application that reported the error, where relevant range : (int, int) -- the start and end points (1-indexed) within the source code where the error occurred AEType ------ An AE type. Maps to an AppleScript type class, e.g. AEType(b'utxt') <=> 'unicode text'. Hashable and comparable, so may be used as keys in dictionaries that map to AE records. Properties: code : bytes -- four-char code, e.g. b'utxt' Methods: __init__(self, code) code : bytes -- four-char code, e.g. b'utxt' AEEnum ------ An AE enumeration. Maps to an AppleScript constant, e.g. AEEnum(b'yes ') <=> 'yes' Properties and methods are same as for AEType. kMissingValue ------------- Convenience constant. Contains AEType(b'msng'), i.e. AppleScript's 'missing value' constant. kae --- This module contains common AE constants auto-generated from OS X header files. For example: from applescript import kae; kae.typeUnicodeText. Usage ===== import applescript # 1. Run script: applescript.AppleScript('say "Hello AppleScript"').run() # 2. Call run handler and user-defined handlers with/without arguments: scpt = applescript.AppleScript(''' on run {arg1, arg2} say arg1 & " " & arg2 end run on foo() return "foobar" end foo on Bar(x, y) return x * y end bar ''') print(scpt.run('Python', 'Calling')) #-> None print(scpt.call('foo')) #-> "foobar" print(scpt.call('Bar', 3, 5)) #-> 15 # 3. A compiled script's state persists until the AppleScript instance is disposed: scpt = applescript.AppleScript(''' property _count : 0 on run set _count to _count + 1 end run ''') print(scpt.run()) #-> 1 print(scpt.run()) #-> 2 print(scpt.run()) #-> 3 # 4. Errors will be reported: applescript.AppleScript('this is not a valid script') # applescript.ScriptError: A identifier can't go after this identifier. (-2740) range=12-19 Supported type mappings ======================= The following Python <=> AppleScript mappings are supported: None <=> [no value; see Limitations] bool <=> boolean int <=> integer [or 'real' in some cases; see Limitations] float <=> real str <=> text [a.k.a. string, Unicode text] bytes <=> data list <=> list tuple => list [one-way mapping only] dict <=> record [with restrictions on keys; see Limitations] str <= alias/POSIX file [one-way mapping only; see Limitations] pyapplescript.AEType <=> type class [keyword] pyapplescript.AEEnum <=> constant [keyword] datetime.datetime <=> date [no timezone support; see Limitations] Limitations: - Returned values may be PyObjC versions of standard Python types, e.g. objc.pyobjc_unicode rather than str. - AppleScript's integer type is limited to representing 32-bit signed integers. Python ints outside that range are packed as 64-bit floats instead. - File-related AppleScript types (e.g. alias, POSIX file) are unpacked as POSIX path strings as they have no direct Python equivalent. AppleScripts which receive path strings from Python should use the POSIX file specifier to convert these to file objects as necessary, e.g. 'set theFile to POSIX file thePath'. - AppleScript type and constant names do not have a direct Python equivalent, so are represented as AEType and AEEnum instances containing their four-char codes. There is no automatic mapping between human-readable keywords and their equivalent four-char codes. See kae.py for standard type and enum codes recognized by AppleScript. - AppleScript's 'missing value' constant is mapped to AEType(b'msng'). A kMissingValue constant is provided for convenience. - AppleScript's date class and the equivalent AE descriptor (typeLongDateTime) do not support time zones. Times are assumed to be in the current time zone. - Python's None type is mapped to typeNull, which AppleScript treats as literally 'no value'. To pass a 'missing value' constant, use kMissingValue instead. - Python dicts are packed as AE records, which are roughly equivalent to C structs or Python's namedtuple type, so should not be used as general-purpose key-value collections. Keys must be Python strings or AEType instances; AppleScript will map these to user-defined identifiers or AppleScript/scripting addition/application-defined keywords respectively. - Record-like AE descriptors such as object specifiers (AppleScript 'references') will be unpacked as nested dicts containing an AEType(b'pcls') key whose value is an AEType instance specifying the descriptor type, and one or more other key-value pairs, e.g.: {AEType(b'pcls'): AEType(b'obj '), AEType(b'want'):..., AEType(b'form'):..., AEType(b'seld'):..., AEType(b'from'): ...} - Dicts containing an AEType(b'pcls') key with an AEType value will be coerced to a record-like descriptor of that type when packed, e.g. {AEType(b'pcls'): AEType(b'obj '),…} would be packed as typeObjectSpecifier. - If the AEType(b'pcls') key's value is not an AEType, it will be packed into a normal AE record as an ordinary key-value pair, e.g. {AEType(b'pcls'): "foo",…} -> {class: "foo",…} (note, however, that NSAppleScript will report a coercion error if it tries to return a similar object). - Dicts not containing an AEType(b'pcls') key will be packed as a normal AE record. - Trying to pack unsupported Python types will result in a TypeError. - Unsupported AppleScript types are not unpacked; the NSAppleEventDescriptor instance is returned as-is. Known issues ============ - While the applescript package was developed for Python 3.x, it also works on Python 2.7 thanks to its back-porting of various 3.x features. However, earlier versions of Python are not supported. - AppleScript return values and error messages can often contain non-ASCII characters, which Python 2.7 and some editors/environments may have trouble consuming/displaying. This is not AppleScript's problem. Deal, or use Python 3.x (recommended). - NSAppleScript provides only limited functionality. For example, script object cannot be saved back to disk (so any changes to the script's state will be lost when the AppleScript instance is disposed of); styled source code cannot be obtained; return values cannot be formatted for display as AppleScript-style strings; restrictions apply to multi-threaded use. The OSAKit framework does provide such features (and the legacy Carbon OSA API provides even more). However, the OSAKit framework, while public, is undocumented and the OSA's future in general is uncertain given the deprecation of the underlying Carbon Component Manager API upon which it is built, so has not been used here. - Object specifiers (AppleScript 'references') returned by NSAppleScript are not fully qualified - i.e. they do not contain the address of the application at which they were targeted - so cannot usefully be passed back to AppleScript in a subsequent call as AppleScript would then treat them as targeting the current process, which is almost probably incorrect. (FWIW, AppleScripts may themselves work around this limitation by wrapping a reference value in a script object and returning that, though this is clumsy as the next AppleScript to which the script object is passed must know how to unwrap it again.) - NSAppleScript may sometimes write a "NSMapInsert(): attempt to insert notAKeyMarker " warning to stderr when returning error information. This is a bug in NSAppleScript, but should not affect operation. See Also ======== - https://developer.apple.com/library/mac/#documentation/AppleScript/Conceptual/AppleScriptX - https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsappleeventdescriptor_Class - https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsapplescript_Class - http://pythonhosted.org/pyobjc Copyright ========= py-applescript is released into the public domain. No warranty, E&OE; use at own risk, etc.
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name = "py-applescript", version = "1.0.3", description = "An easy-to-use Python wrapper for NSAppleScript, allowing Python scripts to communicate with AppleScripts and AppleScriptable applications.", url = "https://github.com/rdhyee/py-applescript", platforms = ['Mac OS X'], license = 'Public Domain', packages = ['applescript'], install_requires = ['pyobjc-core', 'pyobjc-framework-AppleScriptKit', 'pyobjc-framework-AppleScriptObjC'], classifiers = [ 'License :: Public Domain', 'Development Status :: 5 - Production/Stable', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], )
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
# kae.py # # Generated on Sun Dec 30 17:39:53 +0000 2007 # AEDataModel.h typeBoolean = b'bool' typeChar = b'TEXT' typeStyledUnicodeText = b'sutx' typeEncodedString = b'encs' typeUnicodeText = b'utxt' typeCString = b'cstr' typePString = b'pstr' typeUTF16ExternalRepresentation = b'ut16' typeUTF8Text = b'utf8' typeSInt16 = b'shor' typeUInt16 = b'ushr' typeSInt32 = b'long' typeUInt32 = b'magn' typeSInt64 = b'comp' typeUInt64 = b'ucom' typeIEEE32BitFloatingPoint = b'sing' typeIEEE64BitFloatingPoint = b'doub' type128BitFloatingPoint = b'ldbl' typeDecimalStruct = b'decm' typeSMInt = typeSInt16 typeShortInteger = typeSInt16 typeInteger = typeSInt32 typeLongInteger = typeSInt32 typeMagnitude = typeUInt32 typeComp = typeSInt64 typeSMFloat = typeIEEE32BitFloatingPoint typeShortFloat = typeIEEE32BitFloatingPoint typeFloat = typeIEEE64BitFloatingPoint typeLongFloat = typeIEEE64BitFloatingPoint typeExtended = b'exte' typeAEList = b'list' typeAERecord = b'reco' typeAppleEvent = b'aevt' typeEventRecord = b'evrc' typeTrue = b'true' typeFalse = b'fals' typeAlias = b'alis' typeEnumerated = b'enum' typeType = b'type' typeAppParameters = b'appa' typeProperty = b'prop' typeFSRef = b'fsrf' typeFileURL = b'furl' typeKeyword = b'keyw' typeSectionH = b'sect' typeWildCard = b'****' typeApplSignature = b'sign' typeQDRectangle = b'qdrt' typeFixed = b'fixd' typeProcessSerialNumber = b'psn ' typeApplicationURL = b'aprl' typeNull = b'null' typeFSS = b'fss ' typeCFAttributedStringRef = b'cfas' typeCFMutableAttributedStringRef = b'cfaa' typeCFStringRef = b'cfst' typeCFMutableStringRef = b'cfms' typeCFArrayRef = b'cfar' typeCFMutableArrayRef = b'cfma' typeCFDictionaryRef = b'cfdc' typeCFMutableDictionaryRef = b'cfmd' typeCFNumberRef = b'cfnb' typeCFBooleanRef = b'cftf' typeCFTypeRef = b'cfty' typeKernelProcessID = b'kpid' typeMachPort = b'port' typeApplicationBundleID = b'bund' keyTransactionIDAttr = b'tran' keyReturnIDAttr = b'rtid' keyEventClassAttr = b'evcl' keyEventIDAttr = b'evid' keyAddressAttr = b'addr' keyOptionalKeywordAttr = b'optk' keyTimeoutAttr = b'timo' keyInteractLevelAttr = b'inte' keyEventSourceAttr = b'esrc' keyMissedKeywordAttr = b'miss' keyOriginalAddressAttr = b'from' keyAcceptTimeoutAttr = b'actm' keyReplyRequestedAttr = b'repq' kAEDebugPOSTHeader = (1 << 0) kAEDebugReplyHeader = (1 << 1) kAEDebugXMLRequest = (1 << 2) kAEDebugXMLResponse = (1 << 3) kAEDebugXMLDebugAll = 0xFFFFFFFF kSOAP1999Schema = b'ss99' kSOAP2001Schema = b'ss01' keyUserNameAttr = b'unam' keyUserPasswordAttr = b'pass' keyDisableAuthenticationAttr = b'auth' keyXMLDebuggingAttr = b'xdbg' kAERPCClass = b'rpc ' kAEXMLRPCScheme = b'RPC2' kAESOAPScheme = b'SOAP' kAESharedScriptHandler = b'wscp' keyRPCMethodName = b'meth' keyRPCMethodParam = b'parm' keyRPCMethodParamOrder = b'/ord' keyAEPOSTHeaderData = b'phed' keyAEReplyHeaderData = b'rhed' keyAEXMLRequestData = b'xreq' keyAEXMLReplyData = b'xrep' keyAdditionalHTTPHeaders = b'ahed' keySOAPAction = b'sact' keySOAPMethodNameSpace = b'mspc' keySOAPMethodNameSpaceURI = b'mspu' keySOAPSchemaVersion = b'ssch' keySOAPStructureMetaData = b'/smd' keySOAPSMDNamespace = b'ssns' keySOAPSMDNamespaceURI = b'ssnu' keySOAPSMDType = b'sstp' kAEUseHTTPProxyAttr = b'xupr' kAEHTTPProxyPortAttr = b'xhtp' kAEHTTPProxyHostAttr = b'xhth' kAESocks4Protocol = 4 kAESocks5Protocol = 5 kAEUseSocksAttr = b'xscs' kAESocksProxyAttr = b'xsok' kAESocksHostAttr = b'xshs' kAESocksPortAttr = b'xshp' kAESocksUserAttr = b'xshu' kAESocksPasswordAttr = b'xshw' kAEDescListFactorNone = 0 kAEDescListFactorType = 4 kAEDescListFactorTypeAndSize = 8 kAutoGenerateReturnID = -1 kAnyTransactionID = 0 kAEDataArray = 0 kAEPackedArray = 1 kAEDescArray = 3 kAEKeyDescArray = 4 kAEHandleArray = 2 kAENormalPriority = 0x00000000 kAEHighPriority = 0x00000001 kAENoReply = 0x00000001 kAEQueueReply = 0x00000002 kAEWaitReply = 0x00000003 kAEDontReconnect = 0x00000080 kAEWantReceipt = 0x00000200 kAENeverInteract = 0x00000010 kAECanInteract = 0x00000020 kAEAlwaysInteract = 0x00000030 kAECanSwitchLayer = 0x00000040 kAEDontRecord = 0x00001000 kAEDontExecute = 0x00002000 kAEProcessNonReplyEvents = 0x00008000 kAEDefaultTimeout = -1 kNoTimeOut = -2 # AEHelpers.h aeBuildSyntaxNoErr = 0 aeBuildSyntaxBadToken = 1 aeBuildSyntaxBadEOF = 2 aeBuildSyntaxNoEOF = 3 aeBuildSyntaxBadNegative = 4 aeBuildSyntaxMissingQuote = 5 aeBuildSyntaxBadHex = 6 aeBuildSyntaxOddHex = 7 aeBuildSyntaxNoCloseHex = 8 aeBuildSyntaxUncoercedHex = 9 aeBuildSyntaxNoCloseString = 10 aeBuildSyntaxBadDesc = 11 aeBuildSyntaxBadData = 12 aeBuildSyntaxNoCloseParen = 13 aeBuildSyntaxNoCloseBracket = 14 aeBuildSyntaxNoCloseBrace = 15 aeBuildSyntaxNoKey = 16 aeBuildSyntaxNoColon = 17 aeBuildSyntaxCoercedList = 18 aeBuildSyntaxUncoercedDoubleAt = 19 # AEMach.h keyReplyPortAttr = b'repp' typeReplyPortAttr = keyReplyPortAttr # AEObjects.h kAEAND = b'AND ' kAEOR = b'OR ' kAENOT = b'NOT ' kAEFirst = b'firs' kAELast = b'last' kAEMiddle = b'midd' kAEAny = b'any ' kAEAll = b'all ' kAENext = b'next' kAEPrevious = b'prev' keyAECompOperator = b'relo' keyAELogicalTerms = b'term' keyAELogicalOperator = b'logc' keyAEObject1 = b'obj1' keyAEObject2 = b'obj2' keyAEDesiredClass = b'want' keyAEContainer = b'from' keyAEKeyForm = b'form' keyAEKeyData = b'seld' keyAERangeStart = b'star' keyAERangeStop = b'stop' keyDisposeTokenProc = b'xtok' keyAECompareProc = b'cmpr' keyAECountProc = b'cont' keyAEMarkTokenProc = b'mkid' keyAEMarkProc = b'mark' keyAEAdjustMarksProc = b'adjm' keyAEGetErrDescProc = b'indc' formAbsolutePosition = b'indx' formRelativePosition = b'rele' formTest = b'test' formRange = b'rang' formPropertyID = b'prop' formName = b'name' formUniqueID = b'ID ' typeObjectSpecifier = b'obj ' typeObjectBeingExamined = b'exmn' typeCurrentContainer = b'ccnt' typeToken = b'toke' typeRelativeDescriptor = b'rel ' typeAbsoluteOrdinal = b'abso' typeIndexDescriptor = b'inde' typeRangeDescriptor = b'rang' typeLogicalDescriptor = b'logi' typeCompDescriptor = b'cmpd' typeOSLTokenList = b'ostl' kAEIDoMinimum = 0x0000 kAEIDoWhose = 0x0001 kAEIDoMarking = 0x0004 kAEPassSubDescs = 0x0008 kAEResolveNestedLists = 0x0010 kAEHandleSimpleRanges = 0x0020 kAEUseRelativeIterators = 0x0040 typeWhoseDescriptor = b'whos' formWhose = b'whos' typeWhoseRange = b'wrng' keyAEWhoseRangeStart = b'wstr' keyAEWhoseRangeStop = b'wstp' keyAEIndex = b'kidx' keyAETest = b'ktst' # AEPackObject.h # AERegistry.h cAEList = b'list' cApplication = b'capp' cArc = b'carc' cBoolean = b'bool' cCell = b'ccel' cChar = b'cha ' cColorTable = b'clrt' cColumn = b'ccol' cDocument = b'docu' cDrawingArea = b'cdrw' cEnumeration = b'enum' cFile = b'file' cFixed = b'fixd' cFixedPoint = b'fpnt' cFixedRectangle = b'frct' cGraphicLine = b'glin' cGraphicObject = b'cgob' cGraphicShape = b'cgsh' cGraphicText = b'cgtx' cGroupedGraphic = b'cpic' cInsertionLoc = b'insl' cInsertionPoint = b'cins' cIntlText = b'itxt' cIntlWritingCode = b'intl' cItem = b'citm' cLine = b'clin' cLongDateTime = b'ldt ' cLongFixed = b'lfxd' cLongFixedPoint = b'lfpt' cLongFixedRectangle = b'lfrc' cLongInteger = b'long' cLongPoint = b'lpnt' cLongRectangle = b'lrct' cMachineLoc = b'mLoc' cMenu = b'cmnu' cMenuItem = b'cmen' cObject = b'cobj' cObjectSpecifier = b'obj ' cOpenableObject = b'coob' cOval = b'covl' cParagraph = b'cpar' cPICT = b'PICT' cPixel = b'cpxl' cPixelMap = b'cpix' cPolygon = b'cpgn' cProperty = b'prop' cQDPoint = b'QDpt' cQDRectangle = b'qdrt' cRectangle = b'crec' cRGBColor = b'cRGB' cRotation = b'trot' cRoundedRectangle = b'crrc' cRow = b'crow' cSelection = b'csel' cShortInteger = b'shor' cTable = b'ctbl' cText = b'ctxt' cTextFlow = b'cflo' cTextStyles = b'tsty' cType = b'type' cVersion = b'vers' cWindow = b'cwin' cWord = b'cwor' enumArrows = b'arro' enumJustification = b'just' enumKeyForm = b'kfrm' enumPosition = b'posi' enumProtection = b'prtn' enumQuality = b'qual' enumSaveOptions = b'savo' enumStyle = b'styl' enumTransferMode = b'tran' kAEAbout = b'abou' kAEAfter = b'afte' kAEAliasSelection = b'sali' kAEAllCaps = b'alcp' kAEArrowAtEnd = b'aren' kAEArrowAtStart = b'arst' kAEArrowBothEnds = b'arbo' kAEAsk = b'ask ' kAEBefore = b'befo' kAEBeginning = b'bgng' kAEBeginsWith = b'bgwt' kAEBeginTransaction = b'begi' kAEBold = b'bold' kAECaseSensEquals = b'cseq' kAECentered = b'cent' kAEChangeView = b'view' kAEClone = b'clon' kAEClose = b'clos' kAECondensed = b'cond' kAEContains = b'cont' kAECopy = b'copy' kAECoreSuite = b'core' kAECountElements = b'cnte' kAECreateElement = b'crel' kAECreatePublisher = b'cpub' kAECut = b'cut ' kAEDelete = b'delo' kAEDoObjectsExist = b'doex' kAEDoScript = b'dosc' kAEDrag = b'drag' kAEDuplicateSelection = b'sdup' kAEEditGraphic = b'edit' kAEEmptyTrash = b'empt' kAEEnd = b'end ' kAEEndsWith = b'ends' kAEEndTransaction = b'endt' kAEEquals = b'= ' kAEExpanded = b'pexp' kAEFast = b'fast' kAEFinderEvents = b'FNDR' kAEFormulaProtect = b'fpro' kAEFullyJustified = b'full' kAEGetClassInfo = b'qobj' kAEGetData = b'getd' kAEGetDataSize = b'dsiz' kAEGetEventInfo = b'gtei' kAEGetInfoSelection = b'sinf' kAEGetPrivilegeSelection = b'sprv' kAEGetSuiteInfo = b'gtsi' kAEGreaterThan = b'> ' kAEGreaterThanEquals = b'>= ' kAEGrow = b'grow' kAEHidden = b'hidn' kAEHiQuality = b'hiqu' kAEImageGraphic = b'imgr' kAEIsUniform = b'isun' kAEItalic = b'ital' kAELeftJustified = b'left' kAELessThan = b'< ' kAELessThanEquals = b'<= ' kAELowercase = b'lowc' kAEMakeObjectsVisible = b'mvis' kAEMiscStandards = b'misc' kAEModifiable = b'modf' kAEMove = b'move' kAENo = b'no ' kAENoArrow = b'arno' kAENonmodifiable = b'nmod' kAEOpen = b'odoc' kAEOpenSelection = b'sope' kAEOutline = b'outl' kAEPageSetup = b'pgsu' kAEPaste = b'past' kAEPlain = b'plan' kAEPrint = b'pdoc' kAEPrintSelection = b'spri' kAEPrintWindow = b'pwin' kAEPutAwaySelection = b'sput' kAEQDAddOver = b'addo' kAEQDAddPin = b'addp' kAEQDAdMax = b'admx' kAEQDAdMin = b'admn' kAEQDBic = b'bic ' kAEQDBlend = b'blnd' kAEQDCopy = b'cpy ' kAEQDNotBic = b'nbic' kAEQDNotCopy = b'ncpy' kAEQDNotOr = b'ntor' kAEQDNotXor = b'nxor' kAEQDOr = b'or ' kAEQDSubOver = b'subo' kAEQDSubPin = b'subp' kAEQDSupplementalSuite = b'qdsp' kAEQDXor = b'xor ' kAEQuickdrawSuite = b'qdrw' kAEQuitAll = b'quia' kAERedo = b'redo' kAERegular = b'regl' kAEReopenApplication = b'rapp' kAEReplace = b'rplc' kAERequiredSuite = b'reqd' kAERestart = b'rest' kAERevealSelection = b'srev' kAERevert = b'rvrt' kAERightJustified = b'rght' kAESave = b'save' kAESelect = b'slct' kAESetData = b'setd' kAESetPosition = b'posn' kAEShadow = b'shad' kAEShowClipboard = b'shcl' kAEShutDown = b'shut' kAESleep = b'slep' kAESmallCaps = b'smcp' kAESpecialClassProperties = b'c@#!' kAEStrikethrough = b'strk' kAESubscript = b'sbsc' kAESuperscript = b'spsc' kAETableSuite = b'tbls' kAETextSuite = b'TEXT' kAETransactionTerminated = b'ttrm' kAEUnderline = b'undl' kAEUndo = b'undo' kAEWholeWordEquals = b'wweq' kAEYes = b'yes ' kAEZoom = b'zoom' kAELogOut = b'logo' kAEReallyLogOut = b'rlgo' kAEShowRestartDialog = b'rrst' kAEShowShutdownDialog = b'rsdn' kAEMouseClass = b'mous' kAEDown = b'down' kAEUp = b'up ' kAEMoved = b'move' kAEStoppedMoving = b'stop' kAEWindowClass = b'wind' kAEUpdate = b'updt' kAEActivate = b'actv' kAEDeactivate = b'dact' kAECommandClass = b'cmnd' kAEKeyClass = b'keyc' kAERawKey = b'rkey' kAEVirtualKey = b'keyc' kAENavigationKey = b'nave' kAEAutoDown = b'auto' kAEApplicationClass = b'appl' kAESuspend = b'susp' kAEResume = b'rsme' kAEDiskEvent = b'disk' kAENullEvent = b'null' kAEWakeUpEvent = b'wake' kAEScrapEvent = b'scrp' kAEHighLevel = b'high' keyAEAngle = b'kang' keyAEArcAngle = b'parc' keyAEBaseAddr = b'badd' keyAEBestType = b'pbst' keyAEBgndColor = b'kbcl' keyAEBgndPattern = b'kbpt' keyAEBounds = b'pbnd' keyAECellList = b'kclt' keyAEClassID = b'clID' keyAEColor = b'colr' keyAEColorTable = b'cltb' keyAECurveHeight = b'kchd' keyAECurveWidth = b'kcwd' keyAEDashStyle = b'pdst' keyAEData = b'data' keyAEDefaultType = b'deft' keyAEDefinitionRect = b'pdrt' keyAEDescType = b'dstp' keyAEDestination = b'dest' keyAEDoAntiAlias = b'anta' keyAEDoDithered = b'gdit' keyAEDoRotate = b'kdrt' keyAEDoScale = b'ksca' keyAEDoTranslate = b'ktra' keyAEEditionFileLoc = b'eloc' keyAEElements = b'elms' keyAEEndPoint = b'pend' keyAEEventClass = b'evcl' keyAEEventID = b'evti' keyAEFile = b'kfil' keyAEFileType = b'fltp' keyAEFillColor = b'flcl' keyAEFillPattern = b'flpt' keyAEFlipHorizontal = b'kfho' keyAEFlipVertical = b'kfvt' keyAEFont = b'font' keyAEFormula = b'pfor' keyAEGraphicObjects = b'gobs' keyAEID = b'ID ' keyAEImageQuality = b'gqua' keyAEInsertHere = b'insh' keyAEKeyForms = b'keyf' keyAEKeyword = b'kywd' keyAELevel = b'levl' keyAELineArrow = b'arro' keyAEName = b'pnam' keyAENewElementLoc = b'pnel' keyAEObject = b'kobj' keyAEObjectClass = b'kocl' keyAEOffStyles = b'ofst' keyAEOnStyles = b'onst' keyAEParameters = b'prms' keyAEParamFlags = b'pmfg' keyAEPenColor = b'ppcl' keyAEPenPattern = b'pppa' keyAEPenWidth = b'ppwd' keyAEPixelDepth = b'pdpt' keyAEPixMapMinus = b'kpmm' keyAEPMTable = b'kpmt' keyAEPointList = b'ptlt' keyAEPointSize = b'ptsz' keyAEPosition = b'kpos' keyAEPropData = b'prdt' keyAEProperties = b'qpro' keyAEProperty = b'kprp' keyAEPropFlags = b'prfg' keyAEPropID = b'prop' keyAEProtection = b'ppro' keyAERenderAs = b'kren' keyAERequestedType = b'rtyp' keyAEResult = b'----' keyAEResultInfo = b'rsin' keyAERotation = b'prot' keyAERotPoint = b'krtp' keyAERowList = b'krls' keyAESaveOptions = b'savo' keyAEScale = b'pscl' keyAEScriptTag = b'psct' keyAESearchText = b'stxt' keyAEShowWhere = b'show' keyAEStartAngle = b'pang' keyAEStartPoint = b'pstp' keyAEStyles = b'ksty' keyAESuiteID = b'suit' keyAEText = b'ktxt' keyAETextColor = b'ptxc' keyAETextFont = b'ptxf' keyAETextPointSize = b'ptps' keyAETextStyles = b'txst' keyAETextLineHeight = b'ktlh' keyAETextLineAscent = b'ktas' keyAETheText = b'thtx' keyAETransferMode = b'pptm' keyAETranslation = b'ptrs' keyAETryAsStructGraf = b'toog' keyAEUniformStyles = b'ustl' keyAEUpdateOn = b'pupd' keyAEUserTerm = b'utrm' keyAEWindow = b'wndw' keyAEWritingCode = b'wrcd' keyMiscellaneous = b'fmsc' keySelection = b'fsel' keyWindow = b'kwnd' keyWhen = b'when' keyWhere = b'wher' keyModifiers = b'mods' keyKey = b'key ' keyKeyCode = b'code' keyKeyboard = b'keyb' keyDriveNumber = b'drv#' keyErrorCode = b'err#' keyHighLevelClass = b'hcls' keyHighLevelID = b'hid ' pArcAngle = b'parc' pBackgroundColor = b'pbcl' pBackgroundPattern = b'pbpt' pBestType = b'pbst' pBounds = b'pbnd' pClass = b'pcls' pClipboard = b'pcli' pColor = b'colr' pColorTable = b'cltb' pContents = b'pcnt' pCornerCurveHeight = b'pchd' pCornerCurveWidth = b'pcwd' pDashStyle = b'pdst' pDefaultType = b'deft' pDefinitionRect = b'pdrt' pEnabled = b'enbl' pEndPoint = b'pend' pFillColor = b'flcl' pFillPattern = b'flpt' pFont = b'font' pFormula = b'pfor' pGraphicObjects = b'gobs' pHasCloseBox = b'hclb' pHasTitleBar = b'ptit' pID = b'ID ' pIndex = b'pidx' pInsertionLoc = b'pins' pIsFloating = b'isfl' pIsFrontProcess = b'pisf' pIsModal = b'pmod' pIsModified = b'imod' pIsResizable = b'prsz' pIsStationeryPad = b'pspd' pIsZoomable = b'iszm' pIsZoomed = b'pzum' pItemNumber = b'itmn' pJustification = b'pjst' pLineArrow = b'arro' pMenuID = b'mnid' pName = b'pnam' pNewElementLoc = b'pnel' pPenColor = b'ppcl' pPenPattern = b'pppa' pPenWidth = b'ppwd' pPixelDepth = b'pdpt' pPointList = b'ptlt' pPointSize = b'ptsz' pProtection = b'ppro' pRotation = b'prot' pScale = b'pscl' pScript = b'scpt' pScriptTag = b'psct' pSelected = b'selc' pSelection = b'sele' pStartAngle = b'pang' pStartPoint = b'pstp' pTextColor = b'ptxc' pTextFont = b'ptxf' pTextItemDelimiters = b'txdl' pTextPointSize = b'ptps' pTextStyles = b'txst' pTransferMode = b'pptm' pTranslation = b'ptrs' pUniformStyles = b'ustl' pUpdateOn = b'pupd' pUserSelection = b'pusl' pVersion = b'vers' pVisible = b'pvis' typeAEText = b'tTXT' typeArc = b'carc' typeBest = b'best' typeCell = b'ccel' typeClassInfo = b'gcli' typeColorTable = b'clrt' typeColumn = b'ccol' typeDashStyle = b'tdas' typeData = b'tdta' typeDrawingArea = b'cdrw' typeElemInfo = b'elin' typeEnumeration = b'enum' typeEPS = b'EPS ' typeEventInfo = b'evin' typeFinderWindow = b'fwin' typeFixedPoint = b'fpnt' typeFixedRectangle = b'frct' typeGraphicLine = b'glin' typeGraphicText = b'cgtx' typeGroupedGraphic = b'cpic' typeInsertionLoc = b'insl' typeIntlText = b'itxt' typeIntlWritingCode = b'intl' typeLongDateTime = b'ldt ' typeCFAbsoluteTime = b'cfat' typeISO8601DateTime = b'isot' typeLongFixed = b'lfxd' typeLongFixedPoint = b'lfpt' typeLongFixedRectangle = b'lfrc' typeLongPoint = b'lpnt' typeLongRectangle = b'lrct' typeMachineLoc = b'mLoc' typeOval = b'covl' typeParamInfo = b'pmin' typePict = b'PICT' typePixelMap = b'cpix' typePixMapMinus = b'tpmm' typePolygon = b'cpgn' typePropInfo = b'pinf' typePtr = b'ptr ' typeQDPoint = b'QDpt' typeQDRegion = b'Qrgn' typeRectangle = b'crec' typeRGB16 = b'tr16' typeRGB96 = b'tr96' typeRGBColor = b'cRGB' typeRotation = b'trot' typeRoundedRectangle = b'crrc' typeRow = b'crow' typeScrapStyles = b'styl' typeScript = b'scpt' typeStyledText = b'STXT' typeSuiteInfo = b'suin' typeTable = b'ctbl' typeTextStyles = b'tsty' typeTIFF = b'TIFF' typeJPEG = b'JPEG' typeGIF = b'GIFf' typeVersion = b'vers' kAEMenuClass = b'menu' kAEMenuSelect = b'mhit' kAEMouseDown = b'mdwn' kAEMouseDownInBack = b'mdbk' kAEKeyDown = b'kdwn' kAEResized = b'rsiz' kAEPromise = b'prom' keyMenuID = b'mid ' keyMenuItem = b'mitm' keyCloseAllWindows = b'caw ' keyOriginalBounds = b'obnd' keyNewBounds = b'nbnd' keyLocalWhere = b'lwhr' typeHIMenu = b'mobj' typeHIWindow = b'wobj' kBySmallIcon = 0 kByIconView = 1 kByNameView = 2 kByDateView = 3 kBySizeView = 4 kByKindView = 5 kByCommentView = 6 kByLabelView = 7 kByVersionView = 8 kAEInfo = 11 kAEMain = 0 kAESharing = 13 kAEZoomIn = 7 kAEZoomOut = 8 kTextServiceClass = b'tsvc' kUpdateActiveInputArea = b'updt' kShowHideInputWindow = b'shiw' kPos2Offset = b'p2st' kOffset2Pos = b'st2p' kUnicodeNotFromInputMethod = b'unim' kGetSelectedText = b'gtxt' keyAETSMDocumentRefcon = b'refc' keyAEServerInstance = b'srvi' keyAETheData = b'kdat' keyAEFixLength = b'fixl' keyAEUpdateRange = b'udng' keyAECurrentPoint = b'cpos' keyAEBufferSize = b'buff' keyAEMoveView = b'mvvw' keyAENextBody = b'nxbd' keyAETSMScriptTag = b'sclg' keyAETSMTextFont = b'ktxf' keyAETSMTextFMFont = b'ktxm' keyAETSMTextPointSize = b'ktps' keyAETSMEventRecord = b'tevt' keyAETSMEventRef = b'tevr' keyAETextServiceEncoding = b'tsen' keyAETextServiceMacEncoding = b'tmen' keyAETSMGlyphInfoArray = b'tgia' typeTextRange = b'txrn' typeComponentInstance = b'cmpi' typeOffsetArray = b'ofay' typeTextRangeArray = b'tray' typeLowLevelEventRecord = b'evtr' typeGlyphInfoArray = b'glia' typeEventRef = b'evrf' typeText = typeChar kTSMOutsideOfBody = 1 kTSMInsideOfBody = 2 kTSMInsideOfActiveInputArea = 3 kNextBody = 1 kPreviousBody = 2 kTSMHiliteCaretPosition = 1 kTSMHiliteRawText = 2 kTSMHiliteSelectedRawText = 3 kTSMHiliteConvertedText = 4 kTSMHiliteSelectedConvertedText = 5 kTSMHiliteBlockFillText = 6 kTSMHiliteOutlineText = 7 kTSMHiliteSelectedText = 8 kTSMHiliteNoHilite = 9 kCaretPosition = kTSMHiliteCaretPosition kRawText = kTSMHiliteRawText kSelectedRawText = kTSMHiliteSelectedRawText kConvertedText = kTSMHiliteConvertedText kSelectedConvertedText = kTSMHiliteSelectedConvertedText kBlockFillText = kTSMHiliteBlockFillText kOutlineText = kTSMHiliteOutlineText kSelectedText = kTSMHiliteSelectedText keyAEHiliteRange = b'hrng' keyAEPinRange = b'pnrg' keyAEClauseOffsets = b'clau' keyAEOffset = b'ofst' keyAEPoint = b'gpos' keyAELeftSide = b'klef' keyAERegionClass = b'rgnc' keyAEDragging = b'bool' keyAELeadingEdge = keyAELeftSide typeMeters = b'metr' typeInches = b'inch' typeFeet = b'feet' typeYards = b'yard' typeMiles = b'mile' typeKilometers = b'kmtr' typeCentimeters = b'cmtr' typeSquareMeters = b'sqrm' typeSquareFeet = b'sqft' typeSquareYards = b'sqyd' typeSquareMiles = b'sqmi' typeSquareKilometers = b'sqkm' typeLiters = b'litr' typeQuarts = b'qrts' typeGallons = b'galn' typeCubicMeters = b'cmet' typeCubicFeet = b'cfet' typeCubicInches = b'cuin' typeCubicCentimeter = b'ccmt' typeCubicYards = b'cyrd' typeKilograms = b'kgrm' typeGrams = b'gram' typeOunces = b'ozs ' typePounds = b'lbs ' typeDegreesC = b'degc' typeDegreesF = b'degf' typeDegreesK = b'degk' kFAServerApp = b'ssrv' kDoFolderActionEvent = b'fola' kFolderActionCode = b'actn' kFolderOpenedEvent = b'fopn' kFolderClosedEvent = b'fclo' kFolderWindowMovedEvent = b'fsiz' kFolderItemsAddedEvent = b'fget' kFolderItemsRemovedEvent = b'flos' kItemList = b'flst' kNewSizeParameter = b'fnsz' kFASuiteCode = b'faco' kFAAttachCommand = b'atfa' kFARemoveCommand = b'rmfa' kFAEditCommand = b'edfa' kFAFileParam = b'faal' kFAIndexParam = b'indx' kAEInternetSuite = b'gurl' kAEISWebStarSuite = b'WWW\xBD' kAEISGetURL = b'gurl' KAEISHandleCGI = b'sdoc' cURL = b'url ' cInternetAddress = b'IPAD' cHTML = b'html' cFTPItem = b'ftp ' kAEISHTTPSearchArgs = b'kfor' kAEISPostArgs = b'post' kAEISMethod = b'meth' kAEISClientAddress = b'addr' kAEISUserName = b'user' kAEISPassword = b'pass' kAEISFromUser = b'frmu' kAEISServerName = b'svnm' kAEISServerPort = b'svpt' kAEISScriptName = b'scnm' kAEISContentType = b'ctyp' kAEISReferrer = b'refr' kAEISUserAgent = b'Agnt' kAEISAction = b'Kact' kAEISActionPath = b'Kapt' kAEISClientIP = b'Kcip' kAEISFullRequest = b'Kfrq' pScheme = b'pusc' pHost = b'HOST' pPath = b'FTPc' pUserName = b'RAun' pUserPassword = b'RApw' pDNSForm = b'pDNS' pURL = b'pURL' pTextEncoding = b'ptxe' pFTPKind = b'kind' eScheme = b'esch' eurlHTTP = b'http' eurlHTTPS = b'htps' eurlFTP = b'ftp ' eurlMail = b'mail' eurlFile = b'file' eurlGopher = b'gphr' eurlTelnet = b'tlnt' eurlNews = b'news' eurlSNews = b'snws' eurlNNTP = b'nntp' eurlMessage = b'mess' eurlMailbox = b'mbox' eurlMulti = b'mult' eurlLaunch = b'laun' eurlAFP = b'afp ' eurlAT = b'at ' eurlEPPC = b'eppc' eurlRTSP = b'rtsp' eurlIMAP = b'imap' eurlNFS = b'unfs' eurlPOP = b'upop' eurlLDAP = b'uldp' eurlUnknown = b'url?' kConnSuite = b'macc' cDevSpec = b'cdev' cAddressSpec = b'cadr' cADBAddress = b'cadb' cAppleTalkAddress = b'cat ' cBusAddress = b'cbus' cEthernetAddress = b'cen ' cFireWireAddress = b'cfw ' cIPAddress = b'cip ' cLocalTalkAddress = b'clt ' cSCSIAddress = b'cscs' cTokenRingAddress = b'ctok' cUSBAddress = b'cusb' pDeviceType = b'pdvt' pDeviceAddress = b'pdva' pConduit = b'pcon' pProtocol = b'pprt' pATMachine = b'patm' pATZone = b'patz' pATType = b'patt' pDottedDecimal = b'pipd' pDNS = b'pdns' pPort = b'ppor' pNetwork = b'pnet' pNode = b'pnod' pSocket = b'psoc' pSCSIBus = b'pscb' pSCSILUN = b'pslu' eDeviceType = b'edvt' eAddressSpec = b'eads' eConduit = b'econ' eProtocol = b'epro' eADB = b'eadb' eAnalogAudio = b'epau' eAppleTalk = b'epat' eAudioLineIn = b'ecai' eAudioLineOut = b'ecal' eAudioOut = b'ecao' eBus = b'ebus' eCDROM = b'ecd ' eCommSlot = b'eccm' eDigitalAudio = b'epda' eDisplay = b'edds' eDVD = b'edvd' eEthernet = b'ecen' eFireWire = b'ecfw' eFloppy = b'efd ' eHD = b'ehd ' eInfrared = b'ecir' eIP = b'epip' eIrDA = b'epir' eIRTalk = b'epit' eKeyboard = b'ekbd' eLCD = b'edlc' eLocalTalk = b'eclt' eMacIP = b'epmi' eMacVideo = b'epmv' eMicrophone = b'ecmi' eModemPort = b'ecmp' eModemPrinterPort = b'empp' eModem = b'edmm' eMonitorOut = b'ecmn' eMouse = b'emou' eNuBusCard = b'ednb' eNuBus = b'enub' ePCcard = b'ecpc' ePCIbus = b'ecpi' ePCIcard = b'edpi' ePDSslot = b'ecpd' ePDScard = b'epds' ePointingDevice = b'edpd' ePostScript = b'epps' ePPP = b'eppp' ePrinterPort = b'ecpp' ePrinter = b'edpr' eSvideo = b'epsv' eSCSI = b'ecsc' eSerial = b'epsr' eSpeakers = b'edsp' eStorageDevice = b'edst' eSVGA = b'epsg' eTokenRing = b'etok' eTrackball = b'etrk' eTrackpad = b'edtp' eUSB = b'ecus' eVideoIn = b'ecvi' eVideoMonitor = b'edvm' eVideoOut = b'ecvo' cKeystroke = b'kprs' pKeystrokeKey = b'kMsg' pModifiers = b'kMod' pKeyKind = b'kknd' eModifiers = b'eMds' eOptionDown = b'Kopt' eCommandDown = b'Kcmd' eControlDown = b'Kctl' eShiftDown = b'Ksft' eCapsLockDown = b'Kclk' eKeyKind = b'ekst' eEscapeKey = b'ks5\x00' eDeleteKey = b'ks3\x00' eTabKey = b'ks0\x00' eReturnKey = b'ks\x24\x00' eClearKey = b'ksG\x00' eEnterKey = b'ksL\x00' eUpArrowKey = b'ks\x7E\x00' eDownArrowKey = b'ks\x7D\x00' eLeftArrowKey = b'ks\x7B\x00' eRightArrowKey = b'ks\x7C\x00' eHelpKey = b'ksr\x00' eHomeKey = b'kss\x00' ePageUpKey = b'kst\x00' ePageDownKey = b'ksy\x00' eForwardDelKey = b'ksu\x00' eEndKey = b'ksw\x00' eF1Key = b'ksz\x00' eF2Key = b'ksx\x00' eF3Key = b'ksc\x00' eF4Key = b'ksv\x00' eF5Key = b'ks\x60\x00' eF6Key = b'ksa\x00' eF7Key = b'ksb\x00' eF8Key = b'ksd\x00' eF9Key = b'kse\x00' eF10Key = b'ksm\x00' eF11Key = b'ksg\x00' eF12Key = b'kso\x00' eF13Key = b'ksi\x00' eF14Key = b'ksk\x00' eF15Key = b'ksq\x00' keyAELaunchedAsLogInItem = b'lgit' keyAELaunchedAsServiceItem = b'svit' # AEUserTermTypes.h kAEUserTerminology = b'aeut' kAETerminologyExtension = b'aete' kAEScriptingSizeResource = b'scsz' kAEOSAXSizeResource = b'osiz' kAEUTHasReturningParam = 31 kAEUTOptional = 15 kAEUTlistOfItems = 14 kAEUTEnumerated = 13 kAEUTReadWrite = 12 kAEUTChangesState = 12 kAEUTTightBindingFunction = 12 kAEUTEnumsAreTypes = 11 kAEUTEnumListIsExclusive = 10 kAEUTReplyIsReference = 9 kAEUTDirectParamIsReference = 9 kAEUTParamIsReference = 9 kAEUTPropertyIsReference = 9 kAEUTNotDirectParamIsTarget = 8 kAEUTParamIsTarget = 8 kAEUTApostrophe = 3 kAEUTFeminine = 2 kAEUTMasculine = 1 kAEUTPlural = 0 kLaunchToGetTerminology = (1 << 15) kDontFindAppBySignature = (1 << 14) kAlwaysSendSubject = (1 << 13) kReadExtensionTermsMask = (1 << 15) kOSIZDontOpenResourceFile = 15 kOSIZdontAcceptRemoteEvents = 14 kOSIZOpenWithReadPermission = 13 kOSIZCodeInSharedLibraries = 11 # AppleEvents.h keyDirectObject = b'----' keyErrorNumber = b'errn' keyErrorString = b'errs' keyProcessSerialNumber = b'psn ' keyPreDispatch = b'phac' keySelectProc = b'selh' keyAERecorderCount = b'recr' keyAEVersion = b'vers' kCoreEventClass = b'aevt' kAEOpenApplication = b'oapp' kAEOpenDocuments = b'odoc' kAEPrintDocuments = b'pdoc' kAEOpenContents = b'ocon' kAEQuitApplication = b'quit' kAEAnswer = b'ansr' kAEApplicationDied = b'obit' kAEShowPreferences = b'pref' kAEStartRecording = b'reca' kAEStopRecording = b'recc' kAENotifyStartRecording = b'rec1' kAENotifyStopRecording = b'rec0' kAENotifyRecording = b'recr' kAEUnknownSource = 0 kAEDirectCall = 1 kAESameProcess = 2 kAELocalProcess = 3 kAERemoteProcess = 4 # AEInteraction.h kAEInteractWithSelf = 0 kAEInteractWithLocal = 1 kAEInteractWithAll = 2 kAEDoNotIgnoreHandler = 0x00000000 kAEIgnoreAppPhacHandler = 0x00000001 kAEIgnoreAppEventHandler = 0x00000002 kAEIgnoreSysPhacHandler = 0x00000004 kAEIgnoreSysEventHandler = 0x00000008 kAEIngoreBuiltInEventHandler = 0x00000010 kAEDontDisposeOnResume = 0x80000000 kAENoDispatch = 0 kAEUseStandardDispatch = 0xFFFFFFFF # AppleScript.h typeAppleScript = b'ascr' kAppleScriptSubtype = typeAppleScript typeASStorage = typeAppleScript kASSelectInit = 0x1001 kASSelectSetSourceStyles = 0x1002 kASSelectGetSourceStyles = 0x1003 kASSelectGetSourceStyleNames = 0x1004 kASSelectCopySourceAttributes = 0x1005 kASSelectSetSourceAttributes = 0x1006 kASHasOpenHandler = b'hsod' kASDefaultMinStackSize = 4 kASDefaultPreferredStackSize = 16 kASDefaultMaxStackSize = 16 kASDefaultMinHeapSize = 4 kASDefaultPreferredHeapSize = 16 kASDefaultMaxHeapSize = 32 kASSourceStyleUncompiledText = 0 kASSourceStyleNormalText = 1 kASSourceStyleLanguageKeyword = 2 kASSourceStyleApplicationKeyword = 3 kASSourceStyleComment = 4 kASSourceStyleLiteral = 5 kASSourceStyleUserSymbol = 6 kASSourceStyleObjectSpecifier = 7 kASNumberOfSourceStyles = 8 # ASDebugging.h kOSAModeDontDefine = 0x0001 kASSelectSetPropertyObsolete = 0x1101 kASSelectGetPropertyObsolete = 0x1102 kASSelectSetHandlerObsolete = 0x1103 kASSelectGetHandlerObsolete = 0x1104 kASSelectGetAppTerminologyObsolete = 0x1105 kASSelectSetProperty = 0x1106 kASSelectGetProperty = 0x1107 kASSelectSetHandler = 0x1108 kASSelectGetHandler = 0x1109 kASSelectGetAppTerminology = 0x110A kASSelectGetSysTerminology = 0x110B kASSelectGetPropertyNames = 0x110C kASSelectGetHandlerNames = 0x110D # ASRegistry.h keyAETarget = b'targ' keySubjectAttr = b'subj' keyASReturning = b'Krtn' kASAppleScriptSuite = b'ascr' kASScriptEditorSuite = b'ToyS' kASTypeNamesSuite = b'tpnm' typeAETE = b'aete' typeAEUT = b'aeut' kGetAETE = b'gdte' kGetAEUT = b'gdut' kUpdateAEUT = b'udut' kUpdateAETE = b'udte' kCleanUpAEUT = b'cdut' kASComment = b'cmnt' kASLaunchEvent = b'noop' keyScszResource = b'scsz' typeScszResource = b'scsz' kASSubroutineEvent = b'psbr' keyASSubroutineName = b'snam' kASPrepositionalSubroutine = b'psbr' keyASPositionalArgs = b'parg' keyAppHandledCoercion = b'idas' kASStartLogEvent = b'log1' kASStopLogEvent = b'log0' kASCommentEvent = b'cmnt' kASAdd = b'+ ' kASSubtract = b'- ' kASMultiply = b'* ' kASDivide = b'/ ' kASQuotient = b'div ' kASRemainder = b'mod ' kASPower = b'^ ' kASEqual = kAEEquals kASNotEqual = 0xAD202020 kASGreaterThan = kAEGreaterThan kASGreaterThanOrEqual = kAEGreaterThanEquals kASLessThan = kAELessThan kASLessThanOrEqual = kAELessThanEquals kASComesBefore = b'cbfr' kASComesAfter = b'cafr' kASConcatenate = b'ccat' kASStartsWith = kAEBeginsWith kASEndsWith = kAEEndsWith kASContains = kAEContains kASAnd = kAEAND kASOr = kAEOR kASNot = kAENOT kASNegate = b'neg ' keyASArg = b'arg ' kASErrorEventCode = b'err ' kOSAErrorArgs = b'erra' keyAEErrorObject = b'erob' pLength = b'leng' pReverse = b'rvse' pRest = b'rest' pInherits = b'c@#^' pProperties = b'pALL' keyASUserRecordFields = b'usrf' typeUserRecordFields = typeAEList keyASPrepositionAt = b'at ' keyASPrepositionIn = b'in ' keyASPrepositionFrom = b'from' keyASPrepositionFor = b'for ' keyASPrepositionTo = b'to ' keyASPrepositionThru = b'thru' keyASPrepositionThrough = b'thgh' keyASPrepositionBy = b'by ' keyASPrepositionOn = b'on ' keyASPrepositionInto = b'into' keyASPrepositionOnto = b'onto' keyASPrepositionBetween = b'btwn' keyASPrepositionAgainst = b'agst' keyASPrepositionOutOf = b'outo' keyASPrepositionInsteadOf = b'isto' keyASPrepositionAsideFrom = b'asdf' keyASPrepositionAround = b'arnd' keyASPrepositionBeside = b'bsid' keyASPrepositionBeneath = b'bnth' keyASPrepositionUnder = b'undr' keyASPrepositionOver = b'over' keyASPrepositionAbove = b'abve' keyASPrepositionBelow = b'belw' keyASPrepositionApartFrom = b'aprt' keyASPrepositionGiven = b'givn' keyASPrepositionWith = b'with' keyASPrepositionWithout = b'wout' keyASPrepositionAbout = b'abou' keyASPrepositionSince = b'snce' keyASPrepositionUntil = b'till' kDialectBundleResType = b'Dbdl' cConstant = typeEnumerated cClassIdentifier = pClass cObjectBeingExamined = typeObjectBeingExamined cList = typeAEList cSmallReal = typeIEEE32BitFloatingPoint cReal = typeIEEE64BitFloatingPoint cRecord = typeAERecord cReference = cObjectSpecifier cUndefined = b'undf' cMissingValue = b'msng' cSymbol = b'symb' cLinkedList = b'llst' cVector = b'vect' cEventIdentifier = b'evnt' cKeyIdentifier = b'kyid' cUserIdentifier = b'uid ' cPreposition = b'prep' cKeyForm = enumKeyForm cScript = b'scpt' cHandler = b'hand' cProcedure = b'proc' cHandleBreakpoint = b'brak' cClosure = b'clsr' cRawData = b'rdat' cStringClass = typeChar cNumber = b'nmbr' cListElement = b'celm' cListOrRecord = b'lr ' cListOrString = b'ls ' cListRecordOrString = b'lrs ' cNumberOrString = b'ns ' cNumberOrDateTime = b'nd ' cNumberDateTimeOrString = b'nds ' cAliasOrString = b'sf ' cSeconds = b'scnd' typeSound = b'snd ' enumBooleanValues = b'boov' kAETrue = typeTrue kAEFalse = typeFalse enumMiscValues = b'misc' kASCurrentApplication = b'cura' formUserPropertyID = b'usrp' cString = cStringClass pASIt = b'it ' pASMe = b'me ' pASResult = b'rslt' pASSpace = b'spac' pASReturn = b'ret ' pASTab = b'tab ' pASPi = b'pi ' pASParent = b'pare' kASInitializeEventCode = b'init' pASPrintLength = b'prln' pASPrintDepth = b'prdp' pASTopLevelScript = b'ascr' kAECase = b'case' kAEDiacritic = b'diac' kAEWhiteSpace = b'whit' kAEHyphens = b'hyph' kAEExpansion = b'expa' kAEPunctuation = b'punc' kAEZenkakuHankaku = b'zkhk' kAESmallKana = b'skna' kAEKataHiragana = b'hika' kASConsiderReplies = b'rmte' kASNumericStrings = b'nume' enumConsiderations = b'cons' kAECaseConsiderMask = 0x00000001 kAEDiacriticConsiderMask = 0x00000002 kAEWhiteSpaceConsiderMask = 0x00000004 kAEHyphensConsiderMask = 0x00000008 kAEExpansionConsiderMask = 0x00000010 kAEPunctuationConsiderMask = 0x00000020 kASConsiderRepliesConsiderMask = 0x00000040 kASNumericStringsConsiderMask = 0x00000080 kAECaseIgnoreMask = 0x00010000 kAEDiacriticIgnoreMask = 0x00020000 kAEWhiteSpaceIgnoreMask = 0x00040000 kAEHyphensIgnoreMask = 0x00080000 kAEExpansionIgnoreMask = 0x00100000 kAEPunctuationIgnoreMask = 0x00200000 kASConsiderRepliesIgnoreMask = 0x00400000 kASNumericStringsIgnoreMask = 0x00800000 enumConsidsAndIgnores = b'csig' cCoercion = b'coec' cCoerceUpperCase = b'txup' cCoerceLowerCase = b'txlo' cCoerceRemoveDiacriticals = b'txdc' cCoerceRemovePunctuation = b'txpc' cCoerceRemoveHyphens = b'txhy' cCoerceOneByteToTwoByte = b'txex' cCoerceRemoveWhiteSpace = b'txws' cCoerceSmallKana = b'txsk' cCoerceZenkakuhankaku = b'txze' cCoerceKataHiragana = b'txkh' cZone = b'zone' cMachine = b'mach' cAddress = b'addr' cRunningAddress = b'radd' cStorage = b'stor' pASWeekday = b'wkdy' pASMonth = b'mnth' pASDay = b'day ' pASYear = b'year' pASTime = b'time' pASDateString = b'dstr' pASTimeString = b'tstr' cMonth = pASMonth cJanuary = b'jan ' cFebruary = b'feb ' cMarch = b'mar ' cApril = b'apr ' cMay = b'may ' cJune = b'jun ' cJuly = b'jul ' cAugust = b'aug ' cSeptember = b'sep ' cOctober = b'oct ' cNovember = b'nov ' cDecember = b'dec ' cWeekday = pASWeekday cSunday = b'sun ' cMonday = b'mon ' cTuesday = b'tue ' cWednesday = b'wed ' cThursday = b'thu ' cFriday = b'fri ' cSaturday = b'sat ' pASQuote = b'quot' pASSeconds = b'secs' pASMinutes = b'min ' pASHours = b'hour' pASDays = b'days' pASWeeks = b'week' cWritingCodeInfo = b'citl' pScriptCode = b'pscd' pLangCode = b'plcd' kASMagicTellEvent = b'tell' kASMagicEndTellEvent = b'tend' # DigitalHubRegistry.h kDigiHubEventClass = b'dhub' kDigiHubMusicCD = b'aucd' kDigiHubPictureCD = b'picd' kDigiHubVideoDVD = b'vdvd' kDigiHubBlankCD = b'bcd ' kDigiHubBlankDVD = b'bdvd' # OSA.h kOSAComponentType = b'osa ' kOSAGenericScriptingComponentSubtype = b'scpt' kOSAFileType = b'osas' kOSASuite = b'ascr' kOSARecordedText = b'recd' kOSAScriptIsModified = b'modi' kOSAScriptIsTypeCompiledScript = b'cscr' kOSAScriptIsTypeScriptValue = b'valu' kOSAScriptIsTypeScriptContext = b'cntx' kOSAScriptBestType = b'best' kOSACanGetSource = b'gsrc' typeOSADialectInfo = b'difo' keyOSADialectName = b'dnam' keyOSADialectCode = b'dcod' keyOSADialectLangCode = b'dlcd' keyOSADialectScriptCode = b'dscd' kOSANullScript = 0 kOSANullMode = 0 kOSAModeNull = 0 kOSASupportsCompiling = 0x0002 kOSASupportsGetSource = 0x0004 kOSASupportsAECoercion = 0x0008 kOSASupportsAESending = 0x0010 kOSASupportsRecording = 0x0020 kOSASupportsConvenience = 0x0040 kOSASupportsDialects = 0x0080 kOSASupportsEventHandling = 0x0100 kOSASelectLoad = 0x0001 kOSASelectStore = 0x0002 kOSASelectExecute = 0x0003 kOSASelectDisplay = 0x0004 kOSASelectScriptError = 0x0005 kOSASelectDispose = 0x0006 kOSASelectSetScriptInfo = 0x0007 kOSASelectGetScriptInfo = 0x0008 kOSASelectSetActiveProc = 0x0009 kOSASelectGetActiveProc = 0x000A kOSASelectCopyDisplayString = 0x000B kOSASelectScriptingComponentName = 0x0102 kOSASelectCompile = 0x0103 kOSASelectCopyID = 0x0104 kOSASelectCopyScript = 0x0105 kOSASelectGetSource = 0x0201 kOSASelectCopySourceString = 0x0202 kOSASelectCoerceFromDesc = 0x0301 kOSASelectCoerceToDesc = 0x0302 kOSASelectSetSendProc = 0x0401 kOSASelectGetSendProc = 0x0402 kOSASelectSetCreateProc = 0x0403 kOSASelectGetCreateProc = 0x0404 kOSASelectSetDefaultTarget = 0x0405 kOSASelectStartRecording = 0x0501 kOSASelectStopRecording = 0x0502 kOSASelectLoadExecute = 0x0601 kOSASelectCompileExecute = 0x0602 kOSASelectDoScript = 0x0603 kOSASelectSetCurrentDialect = 0x0701 kOSASelectGetCurrentDialect = 0x0702 kOSASelectAvailableDialects = 0x0703 kOSASelectGetDialectInfo = 0x0704 kOSASelectAvailableDialectCodeList = 0x0705 kOSASelectSetResumeDispatchProc = 0x0801 kOSASelectGetResumeDispatchProc = 0x0802 kOSASelectExecuteEvent = 0x0803 kOSASelectDoEvent = 0x0804 kOSASelectMakeContext = 0x0805 kOSASelectComponentSpecificStart = 0x1001 kOSAModePreventGetSource = 0x00000001 kOSAModeNeverInteract = kAENeverInteract kOSAModeCanInteract = kAECanInteract kOSAModeAlwaysInteract = kAEAlwaysInteract kOSAModeDontReconnect = kAEDontReconnect kOSAModeCantSwitchLayer = 0x00000040 kOSAModeDoRecord = 0x00001000 kOSAModeCompileIntoContext = 0x00000002 kOSAModeAugmentContext = 0x00000004 kOSAModeDisplayForHumans = 0x00000008 kOSAModeDontStoreParent = 0x00010000 kOSAModeDispatchToDirectObject = 0x00020000 kOSAModeDontGetDataForArguments = 0x00040000 kOSAModeFullyQualifyDescriptors = 0x00080000 kOSAScriptResourceType = kOSAGenericScriptingComponentSubtype typeOSAGenericStorage = kOSAScriptResourceType kOSAErrorNumber = keyErrorNumber kOSAErrorMessage = keyErrorString kOSAErrorBriefMessage = b'errb' kOSAErrorApp = b'erap' kOSAErrorPartialResult = b'ptlr' kOSAErrorOffendingObject = b'erob' kOSAErrorExpectedType = b'errt' kOSAErrorRange = b'erng' typeOSAErrorRange = b'erng' keyOSASourceStart = b'srcs' keyOSASourceEnd = b'srce' kOSAUseStandardDispatch = kAEUseStandardDispatch kOSANoDispatch = kAENoDispatch kOSADontUsePhac = 0x0001 # OSAComp.h # OSAGeneric.h kGenericComponentVersion = 0x0100 kGSSSelectGetDefaultScriptingComponent = 0x1001 kGSSSelectSetDefaultScriptingComponent = 0x1002 kGSSSelectGetScriptingComponent = 0x1003 kGSSSelectGetScriptingComponentFromStored = 0x1004 kGSSSelectGenericToRealID = 0x1005 kGSSSelectRealToGenericID = 0x1006 kGSSSelectOutOfRange = 0x1007 # Miscellaneous
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
""" applescript -- Easy-to-use Python wrapper for NSAppleScript """ import sys from Foundation import NSAppleScript, NSAppleEventDescriptor, NSURL, \ NSAppleScriptErrorMessage, NSAppleScriptErrorBriefMessage, \ NSAppleScriptErrorNumber, NSAppleScriptErrorAppName, NSAppleScriptErrorRange from .aecodecs import Codecs, fourcharcode, AEType, AEEnum from . import kae __all__ = ['AppleScript', 'ScriptError', 'AEType', 'AEEnum', 'kMissingValue', 'kae'] ###################################################################### class AppleScript: """ Represents a compiled AppleScript. The script object is persistent; its handlers may be called multiple times and its top-level properties will retain current state until the script object's disposal. """ _codecs = Codecs() def __init__(self, source=None, path=None): """ source : str | None -- AppleScript source code path : str | None -- full path to .scpt/.applescript file Notes: - Either the path or the source argument must be provided. - If the script cannot be read/compiled, a ScriptError is raised. """ if path: url = NSURL.fileURLWithPath_(path) self._script, errorinfo = NSAppleScript.alloc().initWithContentsOfURL_error_(url, None) if errorinfo: raise ScriptError(errorinfo) elif source: self._script = NSAppleScript.alloc().initWithSource_(source) else: raise ValueError("Missing source or path argument.") if not self._script.isCompiled(): errorinfo = self._script.compileAndReturnError_(None)[1] if errorinfo: raise ScriptError(errorinfo) def __repr__(self): s = self.source return 'AppleScript({})'.format(repr(s) if len(s) < 100 else '{}...{}'.format(repr(s)[:80], repr(s)[-17:])) ## def _newevent(self, suite, code, args): evt = NSAppleEventDescriptor.appleEventWithEventClass_eventID_targetDescriptor_returnID_transactionID_( fourcharcode(suite), fourcharcode(code), NSAppleEventDescriptor.nullDescriptor(), 0, 0) evt.setDescriptor_forKeyword_(self._codecs.pack(args), fourcharcode(kae.keyDirectObject)) return evt def _unpackresult(self, result, errorinfo): if not result: raise ScriptError(errorinfo) return self._codecs.unpack(result) ## source = property(lambda self: str(self._script.source()), doc="str -- the script's source code") def run(self, *args): """ Run the script, optionally passing arguments to its run handler. args : anything -- arguments to pass to script, if any; see also supported type mappings documentation Result : anything | None -- the script's return value, if any Notes: - The run handler must be explicitly declared in order to pass arguments. - AppleScript will ignore excess arguments. Passing insufficient arguments will result in an error. - If execution fails, a ScriptError is raised. """ if args: evt = self._newevent(kae.kCoreEventClass, kae.kAEOpenApplication, args) return self._unpackresult(*self._script.executeAppleEvent_error_(evt, None)) else: return self._unpackresult(*self._script.executeAndReturnError_(None)) def call(self, name, *args): """ Call the specified user-defined handler. name : str -- the handler's name (case-sensitive) args : anything -- arguments to pass to script, if any; see documentation for supported types Result : anything | None -- the script's return value, if any Notes: - The handler's name must be a user-defined identifier, not an AppleScript keyword; e.g. 'myCount' is acceptable; 'count' is not. - AppleScript will ignore excess arguments. Passing insufficient arguments will result in an error. - If execution fails, a ScriptError is raised. """ evt = self._newevent(kae.kASAppleScriptSuite, kae.kASPrepositionalSubroutine, args) evt.setDescriptor_forKeyword_(NSAppleEventDescriptor.descriptorWithString_(name), fourcharcode(kae.keyASSubroutineName)) return self._unpackresult(*self._script.executeAppleEvent_error_(evt, None)) ## class ScriptError(Exception): """ Indicates an AppleScript compilation/execution error. """ def __init__(self, errorinfo): self._errorinfo = dict(errorinfo) def __repr__(self): return 'ScriptError({})'.format(self._errorinfo) @property def message(self): """ str -- the error message """ msg = self._errorinfo.get(NSAppleScriptErrorMessage) if not msg: msg = self._errorinfo.get(NSAppleScriptErrorBriefMessage, 'Script Error') return msg number = property(lambda self: self._errorinfo.get(NSAppleScriptErrorNumber), doc="int | None -- the error number, if given") appname = property(lambda self: self._errorinfo.get(NSAppleScriptErrorAppName), doc="str | None -- the name of the application that reported the error, where relevant") @property def range(self): """ (int, int) -- the start and end points (1-indexed) within the source code where the error occurred """ range = self._errorinfo.get(NSAppleScriptErrorRange) if range: start = range.rangeValue().location end = start + range.rangeValue().length return (start, end) else: return None def __str__(self): msg = self.message for s, v in [(' ({})', self.number), (' app={!r}', self.appname), (' range={0[0]}-{0[1]}', self.range)]: if v is not None: msg += s.format(v) return msg.encode('ascii', 'replace') if sys.version_info.major < 3 else msg # 2.7 compatibility ## kMissingValue = AEType(kae.cMissingValue) # convenience constant
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
""" aecodecs -- Convert from common Python types to Apple Event Manager types and vice-versa. """ import datetime, struct, sys from Foundation import NSAppleEventDescriptor, NSURL from . import kae __all__ = ['Codecs', 'AEType', 'AEEnum'] ###################################################################### def fourcharcode(code): """ Convert four-char code for use in NSAppleEventDescriptor methods. code : bytes -- four-char code, e.g. b'utxt' Result : int -- OSType, e.g. 1970567284 """ return struct.unpack('>I', code)[0] ####### class Codecs: """ Implements mappings for common Python types with direct AppleScript equivalents. Used by AppleScript class. """ kMacEpoch = datetime.datetime(1904, 1, 1) kUSRF = fourcharcode(kae.keyASUserRecordFields) def __init__(self): # Clients may add/remove/replace encoder and decoder items: self.encoders = { NSAppleEventDescriptor.class__(): self.packdesc, type(None): self.packnone, bool: self.packbool, int: self.packint, float: self.packfloat, bytes: self.packbytes, str: self.packstr, list: self.packlist, tuple: self.packlist, dict: self.packdict, datetime.datetime: self.packdatetime, AEType: self.packtype, AEEnum: self.packenum, } if sys.version_info.major < 3: # 2.7 compatibility self.encoders[unicode] = self.packstr self.decoders = {fourcharcode(k): v for k, v in { kae.typeNull: self.unpacknull, kae.typeBoolean: self.unpackboolean, kae.typeFalse: self.unpackboolean, kae.typeTrue: self.unpackboolean, kae.typeSInt32: self.unpacksint32, kae.typeIEEE64BitFloatingPoint: self.unpackfloat64, kae.typeUTF8Text: self.unpackunicodetext, kae.typeUTF16ExternalRepresentation: self.unpackunicodetext, kae.typeUnicodeText: self.unpackunicodetext, kae.typeLongDateTime: self.unpacklongdatetime, kae.typeAEList: self.unpackaelist, kae.typeAERecord: self.unpackaerecord, kae.typeAlias: self.unpackfile, kae.typeFSS: self.unpackfile, kae.typeFSRef: self.unpackfile, kae.typeFileURL: self.unpackfile, kae.typeType: self.unpacktype, kae.typeEnumeration: self.unpackenumeration, }.items()} def pack(self, data): """Pack Python data. data : anything -- a Python value Result : NSAppleEventDescriptor -- an AE descriptor, or error if no encoder exists for this type of data """ try: return self.encoders[data.__class__](data) # quick lookup by type/class except (KeyError, AttributeError) as e: for type, encoder in self.encoders.items(): # slower but more thorough lookup that can handle subtypes/subclasses if isinstance(data, type): return encoder(data) raise TypeError("Can't pack data into an AEDesc (unsupported type): {!r}".format(data)) def unpack(self, desc): """Unpack an Apple event descriptor. desc : NSAppleEventDescriptor Result : anything -- a Python value, or the original NSAppleEventDescriptor if no decoder is found """ decoder = self.decoders.get(desc.descriptorType()) # unpack known type if decoder: return decoder(desc) # if it's a record-like desc, unpack as dict with an extra AEType(b'pcls') key containing the desc type rec = desc.coerceToDescriptorType_(fourcharcode(kae.typeAERecord)) if rec: rec = self.unpackaerecord(rec) rec[AEType(kae.pClass)] = AEType(struct.pack('>I', desc.descriptorType())) return rec # return as-is return desc ## def _packbytes(self, desctype, data): return NSAppleEventDescriptor.descriptorWithDescriptorType_bytes_length_( fourcharcode(desctype), data, len(data)) def packdesc(self, val): return val def packnone(self, val): return NSAppleEventDescriptor.nullDescriptor() def packbool(self, val): return NSAppleEventDescriptor.descriptorWithBoolean_(int(val)) def packint(self, val): if (-2**31) <= val < (2**31): return NSAppleEventDescriptor.descriptorWithInt32_(val) else: return self.pack(float(val)) def packfloat(self, val): return self._packbytes(kae.typeFloat, struct.pack('d', val)) def packbytes(self, val): return self._packbytes(kae.typeData, val) def packstr(self, val): return NSAppleEventDescriptor.descriptorWithString_(val) def packdatetime(self, val): delta = val - self.kMacEpoch sec = delta.days * 3600 * 24 + delta.seconds return self._packbytes(kae.typeLongDateTime, struct.pack('q', sec)) def packlist(self, val): lst = NSAppleEventDescriptor.listDescriptor() for item in val: lst.insertDescriptor_atIndex_(self.pack(item), 0) return lst def packdict(self, val): record = NSAppleEventDescriptor.recordDescriptor() usrf = desctype = None for key, value in val.items(): if isinstance(key, AEType): if key.code == kae.pClass and isinstance(value, AEType): # AS packs records that contain a 'class' property by coercing the packed record to the descriptor type specified by the property's value (assuming it's an AEType) desctype = value else: record.setDescriptor_forKeyword_(self.pack(value), fourcharcode(key.code)) else: if not usrf: usrf = NSAppleEventDescriptor.listDescriptor() usrf.insertDescriptor_atIndex_(self.pack(key), 0) usrf.insertDescriptor_atIndex_(self.pack(value), 0) if usrf: record.setDescriptor_forKeyword_(usrf, self.kUSRF) if desctype: newrecord = record.coerceToDescriptorType_(fourcharcode(desctype.code)) if newrecord: record = newrecord else: # coercion failed for some reason, so pack as normal key-value pair record.setDescriptor_forKeyword_(self.pack(desctype), fourcharcode(key.code)) return record def packtype(self, val): return NSAppleEventDescriptor.descriptorWithTypeCode_(fourcharcode(val.code)) def packenum(self, val): return NSAppleEventDescriptor.descriptorWithEnumCode_(fourcharcode(val.code)) ####### def unpacknull(self, desc): return None def unpackboolean(self, desc): return desc.booleanValue() def unpacksint32(self, desc): return desc.int32Value() def unpackfloat64(self, desc): return struct.unpack('d', bytes(desc.data()))[0] def unpackunicodetext(self, desc): return desc.stringValue() def unpacklongdatetime(self, desc): return self.kMacEpoch + datetime.timedelta(seconds=struct.unpack('q', bytes(desc.data()))[0]) def unpackaelist(self, desc): return [self.unpack(desc.descriptorAtIndex_(i + 1)) for i in range(desc.numberOfItems())] def unpackaerecord(self, desc): dct = {} for i in range(desc.numberOfItems()): key = desc.keywordForDescriptorAtIndex_(i + 1) value = desc.descriptorForKeyword_(key) if key == self.kUSRF: lst = self.unpackaelist(value) for i in range(0, len(lst), 2): dct[lst[i]] = lst[i+1] else: dct[AEType(struct.pack('>I', key))] = self.unpack(value) return dct def unpacktype(self, desc): return AEType(struct.pack('>I', desc.typeCodeValue())) def unpackenumeration(self, desc): return AEEnum(struct.pack('>I', desc.enumCodeValue())) def unpackfile(self, desc): url = bytes(desc.coerceToDescriptorType_(fourcharcode(kae.typeFileURL)).data()).decode('utf8') return NSURL.URLWithString_(url).path() ####### class AETypeBase: """ Base class for AEType and AEEnum. Notes: - Hashable and comparable, so may be used as keys in dictionaries that map to AE records. """ def __init__(self, code): """ code : bytes -- four-char code, e.g. b'utxt' """ if not isinstance(code, bytes): raise TypeError('invalid code (not a bytes object): {!r}'.format(code)) elif len(code) != 4: raise ValueError('invalid code (not four bytes long): {!r}'.format(code)) self._code = code code = property(lambda self:self._code, doc="bytes -- four-char code, e.g. b'utxt'") def __hash__(self): return hash(self._code) def __eq__(self, val): return val.__class__ == self.__class__ and val.code == self._code def __ne__(self, val): return not self == val def __repr__(self): return "{}({!r})".format(self.__class__.__name__, self._code) ## class AEType(AETypeBase): """An AE type. Maps to an AppleScript type class, e.g. AEType(b'utxt') <=> 'unicode text'.""" class AEEnum(AETypeBase): """An AE enumeration. Maps to an AppleScript constant, e.g. AEEnum(b'yes ') <=> 'yes'."""
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
Metadata-Version: 2.1 Name: py-applescript Version: 1.0.3 Summary: An easy-to-use Python wrapper for NSAppleScript, allowing Python scripts to communicate with AppleScripts and AppleScriptable applications. Home-page: https://github.com/rdhyee/py-applescript License: Public Domain Platform: Mac OS X Classifier: License :: Public Domain Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: MacOS :: MacOS X Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 License-File: LICENSE UNKNOWN
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
LICENSE README setup.cfg setup.py applescript/__init__.py applescript/aecodecs.py applescript/kae.py py_applescript.egg-info/PKG-INFO py_applescript.egg-info/SOURCES.txt py_applescript.egg-info/dependency_links.txt py_applescript.egg-info/pbr.json py_applescript.egg-info/requires.txt py_applescript.egg-info/top_level.txt
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
applescript
{ "repo_name": "rdhyee/py-applescript", "stars": "116", "repo_language": "Python", "file_name": "top_level.txt", "mime_type": "text/plain" }
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.31101.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "leven", "leven\leven.vcxproj", "{CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 MinSizeRel|Win32 = MinSizeRel|Win32 MinSizeRel|x64 = MinSizeRel|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 RelWithDebInfo|Win32 = RelWithDebInfo|Win32 RelWithDebInfo|x64 = RelWithDebInfo|x64 Testing|Win32 = Testing|Win32 Testing|x64 = Testing|x64 UnitTest - Release|Win32 = UnitTest - Release|Win32 UnitTest - Release|x64 = UnitTest - Release|x64 UnitTest - Testing|Win32 = UnitTest - Testing|Win32 UnitTest - Testing|x64 = UnitTest - Testing|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Debug|Win32.ActiveCfg = Debug|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Debug|Win32.Build.0 = Debug|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Debug|x64.ActiveCfg = Debug|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Debug|x64.Build.0 = Debug|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.MinSizeRel|Win32.ActiveCfg = UnitTest - Testing|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.MinSizeRel|Win32.Build.0 = UnitTest - Testing|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.MinSizeRel|x64.ActiveCfg = UnitTest - Testing|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.MinSizeRel|x64.Build.0 = UnitTest - Testing|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Release|Win32.ActiveCfg = Release|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Release|Win32.Build.0 = Release|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Release|x64.ActiveCfg = Release|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Release|x64.Build.0 = Release|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.RelWithDebInfo|Win32.ActiveCfg = Release|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.RelWithDebInfo|Win32.Build.0 = Release|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.RelWithDebInfo|x64.ActiveCfg = Release|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.RelWithDebInfo|x64.Build.0 = Release|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Testing|Win32.ActiveCfg = Testing|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Testing|Win32.Build.0 = Testing|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Testing|x64.ActiveCfg = Testing|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.Testing|x64.Build.0 = Testing|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Release|Win32.ActiveCfg = UnitTest - Release|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Release|Win32.Build.0 = UnitTest - Release|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Release|x64.ActiveCfg = UnitTest - Release|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Release|x64.Build.0 = UnitTest - Release|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Testing|Win32.ActiveCfg = UnitTest - Testing|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Testing|Win32.Build.0 = UnitTest - Testing|Win32 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Testing|x64.ActiveCfg = UnitTest - Testing|x64 {CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}.UnitTest - Testing|x64.Build.0 = UnitTest - Testing|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
# leven Complete source for my experimental voxel engine which features in posts on my blog: http://ngildea.blogspot.co.uk/ This is a dump of the project in its current state rather than a real release of a project. I had for a long time planned to make some fixes and updates and do a "proper" release but that doesn't seem like it will ever happen so instead I've just uploaded all the code as it exists now. ## Build Instructions A VS2013 solution and project file are supplied. These include hardcoded paths to the installation dirs of the project dependencies on my machine. The dependencies are: * Remotery (disabled by default but there are manually placed instrumentations) * Bullet Physics 2.83.6 * Dear ImGui * Catch unit testing library (only required for the unit test configurations) * The OpenCL SDK for your dev machine (e.g. NVidia CUDA/OpenCL SDK) * GLEW 1.13.0 * GLM 0.9.3 * SDL 2.0.3 It's highly likely that versions other than those specified will also work. ## Prebuilt A prebuilt Win64 executable along with the dependencies can be downloaded here: https://github.com/nickgildea/leven/blob/master/prebuilt-win64.zip ## Features The main point of the project was to investigate building a chunked terrain world using Dual Contouring. This more or less works, making use of my method for joining the chunk meshes described here: http://ngildea.blogspot.co.uk/2014/09/dual-contouring-chunked-terrain.html The main chunk meshes are generated via OpenCL as described (more or less, there are some changes) here: http://ngildea.blogspot.co.uk/2015/06/dual-contouring-with-opencl.html I've also added additional features like Bullet Physics integration so the user can walk around the terrains and spawn interactive objects. ## Problems There are a few problems I never got around to fixing. The main problem is caused by the technologies used to implement the engine. Rendering is implemented via OpenGL and the GPGPU voxel component using OpenCL. On the face of things you might think these two techs work well together. In practise I found the oppposite to be true: the interop between the two APIs requires the thread performing the rendering to block while the GPU data is transferred from one API's ownership to the other. I found this to be unworkable and instead the following happens when a mesh is created: * the mesh data is generated on the GPU via OpenCL * the data is then downloaded into main memory * the mesh data is then reuploaded to the GPU via OpenGL Obviously this a less than optimal solution. Additionally the mesh generation in OpenCL can occasionally starve the OpenGL operations of execution resources and hitches will occur. The solution to these issues would be to use the Vulkan API, I think. Aside from that there are problems which I never fixed since it was just a personal project (I was the only user and so didn't particularly care..) like no overall memory management solution and things like fixed-size global arrays used instead which will occasionally become full, causing crashes. ## Contact If you have an questions you can reach me by email: nick dot gildea at gmail or @ngildea85 on twitter.
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
FullScreen False #WindowHeight 720 WindowHeight 1080 #WindowHeight 2160 #NoiseSeed 8571149 NoiseSeed 93923590 #NoiseSeed 4347234 # Enable/Disable shadow mapping UseShadows True ShadowMapSize 4096
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Testing|Win32"> <Configuration>Testing</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Testing|x64"> <Configuration>Testing</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="UnitTest - Release|Win32"> <Configuration>UnitTest - Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="UnitTest - Release|x64"> <Configuration>UnitTest - Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="UnitTest - Testing|Win32"> <Configuration>UnitTest - Testing</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="UnitTest - Testing|x64"> <Configuration>UnitTest - Testing</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{CFB7C1A4-D7AD-4B2B-B02B-505F9CAEE9F8}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>leven</RootNamespace> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Testing|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>false</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>false</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Testing|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Testing|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>LEVEN;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4\;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <RuntimeTypeInfo>false</RuntimeTypeInfo> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x86;C:\dev\glew-1.13.0\lib\Release\Win32;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>Bullet3Common_vs2010.lib;Bullet3Collision_vs2010.lib;Bullet3Dynamics_vs2010.lib;Bullet3Geometry_vs2010.lib;LinearMath_vs2010.lib;BulletCollision_vs2010.lib;BulletDynamics_vs2010.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <StackReserveSize> </StackReserveSize> <ForceSymbolReferences> </ForceSymbolReferences> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>LEVEN;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4\;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <RuntimeTypeInfo>false</RuntimeTypeInfo> <EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\vs2013_x64\lib\Release;C:\dev\SDL2-2.0.3\lib\x64;C:\dev\glew-1.13.0\bin\Release\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>BulletCollision.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <StackReserveSize> </StackReserveSize> <ForceSymbolReferences> </ForceSymbolReferences> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>LEVEN;TESTING;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4\;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <BasicRuntimeChecks>Default</BasicRuntimeChecks> <InlineFunctionExpansion>Disabled</InlineFunctionExpansion> <IntrinsicFunctions>true</IntrinsicFunctions> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <OmitFramePointers>true</OmitFramePointers> <WholeProgramOptimization>true</WholeProgramOptimization> <EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet> <RuntimeTypeInfo>false</RuntimeTypeInfo> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x86;C:\dev\glew-1.13.0\lib\Release\Win32;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>LinearMath_vs2010.lib;BulletCollision_vs2010.lib;BulletDynamics_vs2010.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <ForceSymbolReferences> </ForceSymbolReferences> <LargeAddressAware>true</LargeAddressAware> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Testing|x64'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>LEVEN;TESTING;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4\;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <BasicRuntimeChecks>Default</BasicRuntimeChecks> <InlineFunctionExpansion>Disabled</InlineFunctionExpansion> <IntrinsicFunctions>true</IntrinsicFunctions> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <OmitFramePointers>true</OmitFramePointers> <WholeProgramOptimization>true</WholeProgramOptimization> <EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet> <RuntimeTypeInfo>false</RuntimeTypeInfo> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\vs2013_x64\lib\Release;C:\dev\SDL2-2.0.3\lib\x64;C:\dev\glew-1.13.0\bin\Release\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>BulletCollision.lib;BulletDynamics.lib;LinearMath.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <ForceSymbolReferences> </ForceSymbolReferences> <LargeAddressAware>true</LargeAddressAware> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>LEVEN;LVN_UNIT_TEST;TESTING;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4\;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <BasicRuntimeChecks>Default</BasicRuntimeChecks> <InlineFunctionExpansion>Disabled</InlineFunctionExpansion> <IntrinsicFunctions>true</IntrinsicFunctions> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <OmitFramePointers>true</OmitFramePointers> <WholeProgramOptimization>true</WholeProgramOptimization> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <RuntimeTypeInfo>false</RuntimeTypeInfo> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x86;C:\dev\glew-1.13.0\lib\Release\Win32;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>Bullet3Common_vs2010_debug.lib;Bullet3Collision_vs2010_debug.lib;Bullet3Dynamics_vs2010_debug.lib;Bullet3Geometry_vs2010_debug.lib;LinearMath_vs2010_debug.lib;BulletCollision_vs2010_debug.lib;BulletDynamics_vs2010_debug.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <ForceSymbolReferences> </ForceSymbolReferences> <LargeAddressAware>true</LargeAddressAware> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>LEVEN;LVN_UNIT_TEST;TESTING;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4\;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <BasicRuntimeChecks>Default</BasicRuntimeChecks> <InlineFunctionExpansion>Disabled</InlineFunctionExpansion> <IntrinsicFunctions>true</IntrinsicFunctions> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <OmitFramePointers>true</OmitFramePointers> <WholeProgramOptimization>true</WholeProgramOptimization> <EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet> <RuntimeTypeInfo>false</RuntimeTypeInfo> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x64;C:\dev\glew-1.13.0\bin\Release\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>Bullet3Common_vs2010_x64_release.lib;Bullet3Collision_vs2010_x64_release.lib;Bullet3Dynamics_vs2010_x64_release.lib;Bullet3Geometry_vs2010_x64_release.lib;LinearMath_vs2010_x64_release.lib;BulletCollision_vs2010_x64_release.lib;BulletDynamics_vs2010_x64_release.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <ForceSymbolReferences> </ForceSymbolReferences> <LargeAddressAware>true</LargeAddressAware> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>false</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>LEVEN;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(SolutionDir)/libsimdpp/;c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet> <OmitFramePointers>true</OmitFramePointers> <ExceptionHandling>Sync</ExceptionHandling> <BufferSecurityCheck>false</BufferSecurityCheck> <RuntimeTypeInfo>false</RuntimeTypeInfo> <BrowseInformation>true</BrowseInformation> <AdditionalOptions>/d2Zi+ %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>false</EnableCOMDATFolding> <OptimizeReferences>false</OptimizeReferences> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x86;C:\dev\glew-1.13.0\lib\Release\Win32;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>LinearMath_vs2010.lib;BulletCollision_vs2010.lib;BulletDynamics_vs2010.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <HeapReserveSize>1073741824</HeapReserveSize> <LargeAddressAware>true</LargeAddressAware> <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers> <ForceSymbolReferences> </ForceSymbolReferences> <IgnoreSpecificDefaultLibraries> </IgnoreSpecificDefaultLibraries> <LinkTimeCodeGeneration>Default</LinkTimeCodeGeneration> </Link> <Bscmake> <PreserveSbr>true</PreserveSbr> </Bscmake> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>false</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>LEVEN;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>$(SolutionDir)/libsimdpp/;c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet> <OmitFramePointers>true</OmitFramePointers> <ExceptionHandling>Sync</ExceptionHandling> <BufferSecurityCheck>false</BufferSecurityCheck> <RuntimeTypeInfo>false</RuntimeTypeInfo> <BrowseInformation>true</BrowseInformation> <AdditionalOptions>/d2Zi+ %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>false</EnableCOMDATFolding> <OptimizeReferences>false</OptimizeReferences> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\vs2013_x64\lib\Release;C:\dev\SDL2-2.0.3\lib\x64;C:\dev\glew-1.13.0\bin\Release\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>BulletCollision.lib;BulletDynamics.lib;LinearMath.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <HeapReserveSize>1073741824</HeapReserveSize> <LargeAddressAware>true</LargeAddressAware> <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers> <ForceSymbolReferences> </ForceSymbolReferences> <IgnoreSpecificDefaultLibraries> </IgnoreSpecificDefaultLibraries> <LinkTimeCodeGeneration>Default</LinkTimeCodeGeneration> </Link> <Bscmake> <PreserveSbr>true</PreserveSbr> </Bscmake> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>false</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>LEVEN;LVN_UNIT_TEST;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <FloatingPointModel>Precise</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> <OmitFramePointers>true</OmitFramePointers> <ExceptionHandling>Sync</ExceptionHandling> <BufferSecurityCheck>false</BufferSecurityCheck> <RuntimeTypeInfo>false</RuntimeTypeInfo> <BrowseInformation>true</BrowseInformation> <AdditionalOptions>/d2Zi+ %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x86;C:\dev\glew-1.13.0\lib\Release\Win32;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\Win32;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>Bullet3Common_vs2010.lib;Bullet3Collision_vs2010.lib;Bullet3Dynamics_vs2010.lib;Bullet3Geometry_vs2010.lib;LinearMath_vs2010.lib;BulletCollision_vs2010.lib;BulletDynamics_vs2010.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <HeapReserveSize>1073741824</HeapReserveSize> <LargeAddressAware>true</LargeAddressAware> <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers> <ForceSymbolReferences> </ForceSymbolReferences> <IgnoreSpecificDefaultLibraries> </IgnoreSpecificDefaultLibraries> <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration> </Link> <Bscmake> <PreserveSbr>true</PreserveSbr> </Bscmake> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>false</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>LEVEN;LVN_UNIT_TEST;_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>c:\dev\Remotery\lib;C:\dev\bullet3-2.83.6\src;C:\dev\imgui;c:\dev\Catch\include;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include;C:\dev\leven\leven\include;C:\dev\glew-1.13.0\include;C:\dev\leven\glm-0.9.3.4;c:\dev\SDL2-2.0.3\include;%(AdditionalIncludeDirectories);</AdditionalIncludeDirectories> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <FloatingPointModel>Fast</FloatingPointModel> <ForcedIncludeFiles>force_include.h</ForcedIncludeFiles> <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion> <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed> <EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet> <OmitFramePointers>true</OmitFramePointers> <ExceptionHandling>Sync</ExceptionHandling> <BufferSecurityCheck>false</BufferSecurityCheck> <RuntimeTypeInfo>false</RuntimeTypeInfo> <BrowseInformation>true</BrowseInformation> <AdditionalOptions>/d2Zi+ %(AdditionalOptions)</AdditionalOptions> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalLibraryDirectories>C:\dev\bullet3-2.83.6\bin;C:\dev\SDL2-2.0.3\lib\x64;C:\dev\glew-1.13.0\bin\Release\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalDependencies>Bullet3Common_vs2010_x64_release.lib;Bullet3Collision_vs2010_x64_release.lib;Bullet3Dynamics_vs2010_x64_release.lib;Bullet3Geometry_vs2010_x64_release.lib;LinearMath_vs2010_x64_release.lib;BulletCollision_vs2010_x64_release.lib;BulletDynamics_vs2010_x64_release.lib;OpenCL.lib;SDL2.lib;SDL2main.lib;glew32.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies)</AdditionalDependencies> <HeapReserveSize>1073741824</HeapReserveSize> <LargeAddressAware>true</LargeAddressAware> <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers> <ForceSymbolReferences> </ForceSymbolReferences> <IgnoreSpecificDefaultLibraries> </IgnoreSpecificDefaultLibraries> <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration> </Link> <Bscmake> <PreserveSbr>true</PreserveSbr> </Bscmake> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="..\..\imgui\imgui.cpp"> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Release|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <WholeProgramOptimization Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">false</WholeProgramOptimization> <WholeProgramOptimization Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">false</WholeProgramOptimization> </ClCompile> <ClCompile Include="..\..\imgui\imgui_draw.cpp"> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Release|x64'">c:\dev\leven\leven\src\force_include.h</ForcedIncludeFiles> <WholeProgramOptimization Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">false</WholeProgramOptimization> <WholeProgramOptimization Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">false</WholeProgramOptimization> </ClCompile> <ClCompile Include="..\..\Remotery\lib\Remotery.c"> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Testing|x64'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> </ForcedIncludeFiles> <ForcedIncludeFiles Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> </ForcedIncludeFiles> </ClCompile> <ClCompile Include="src\actors.cpp" /> <ClCompile Include="src\clipmap.cpp" /> <ClCompile Include="src\compute.cpp" /> <ClCompile Include="src\compute_csg.cpp" /> <ClCompile Include="src\compute_cuckoo.cpp" /> <ClCompile Include="src\compute_density_field.cpp" /> <ClCompile Include="src\compute_octree.cpp" /> <ClCompile Include="src\compute_program.cpp" /> <ClCompile Include="src\config.cpp" /> <ClCompile Include="src\file_utils.cpp" /> <!--ClCompile Include="src\game.cpp" /--> <ClCompile Include="src\frustum.cpp" /> <ClCompile Include="src\gui.cpp"> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</PreprocessToFile> </ClCompile> <ClCompile Include="src\imgui_handlers.cpp" /> <ClCompile Include="src\log.cpp" /> <ClCompile Include="src\main.cpp"> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">true</ExcludedFromBuild> </ClCompile> <ClCompile Include="src\ng_mesh_simplify.cpp" /> <ClCompile Include="src\octree.cpp" /> <ClCompile Include="src\physics.cpp" /> <ClCompile Include="src\pool_allocator.cpp" /> <ClCompile Include="src\primes.cpp" /> <ClCompile Include="src\qef_simd.cpp" /> <ClCompile Include="src\random.cpp" /> <ClCompile Include="src\render_actor.cpp" /> <ClCompile Include="src\render_debug.cpp" /> <ClCompile Include="src\render_mesh.cpp" /> <ClCompile Include="src\render_program.cpp" /> <ClCompile Include="src\camera.cpp" /> <ClCompile Include="src\render_shapes.cpp" /> <ClCompile Include="src\resource.cpp" /> <ClCompile Include="src\render.cpp" /> <!--ClCompile Include="src\terrain.cpp" /--> <ClCompile Include="src\test_allocator.cpp"> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> </ClCompile> <ClCompile Include="src\test_compute.cpp"> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">false</ExcludedFromBuild> </ClCompile> <ClCompile Include="src\test_cuckoo.cpp"> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">false</ExcludedFromBuild> </ClCompile> <ClCompile Include="src\test_main.cpp"> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">false</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild> <ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild> </ClCompile> <ClCompile Include="src\threadpool.cpp" /> <ClCompile Include="src\util.cpp" /> <ClCompile Include="src\stb_image.c" /> <ClCompile Include="src\viewer.cpp" /> <ClCompile Include="src\volume.cpp"> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Testing|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Testing|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</PreprocessToFile> <PreprocessToFile Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</PreprocessToFile> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="..\..\Remotery\lib\Remotery.h" /> <ClInclude Include="src\aabb.h" /> <ClInclude Include="src\actors.h" /> <ClInclude Include="src\clipmap.h" /> <ClInclude Include="src\compute.h" /> <ClInclude Include="src\compute_cuckoo.h" /> <ClInclude Include="src\compute_local.h" /> <ClInclude Include="src\compute_program.h" /> <ClInclude Include="src\config.h" /> <ClInclude Include="src\contour_constants.h" /> <ClInclude Include="src\cuckoo.h" /> <ClInclude Include="src\double_buffer.h" /> <ClInclude Include="src\file_utils.h" /> <!--ClInclude Include="src\game.h" /--> <ClInclude Include="src\force_include.h" /> <ClInclude Include="src\frustum.h" /> <ClInclude Include="src\glm_hash.h" /> <ClInclude Include="src\gui.h" /> <ClInclude Include="src\imgui_handlers.h" /> <ClInclude Include="src\log.h" /> <ClInclude Include="src\lrucache.h" /> <ClInclude Include="src\materials.h" /> <ClInclude Include="src\ng_mesh_simplify.h" /> <ClInclude Include="src\octree.h" /> <ClInclude Include="src\options.h" /> <ClInclude Include="src\physics.h" /> <ClInclude Include="src\pool_allocator.h" /> <ClInclude Include="src\primes.h" /> <ClInclude Include="src\qef_simd.h" /> <ClInclude Include="src\random.h" /> <ClInclude Include="src\render_actor.h" /> <ClInclude Include="src\render_debug.h" /> <ClInclude Include="src\render_local.h" /> <ClInclude Include="src\render_mesh.h" /> <ClInclude Include="src\render_program.h" /> <ClInclude Include="src\camera.h" /> <ClInclude Include="src\render_shapes.h" /> <ClInclude Include="src\render_types.h" /> <ClInclude Include="src\resource.h" /> <ClInclude Include="src\render.h" /> <!--ClInclude Include="src\terrain.h" /--> <ClInclude Include="src\sdl_wrapper.h" /> <ClInclude Include="src\slab_allocator.h" /> <ClInclude Include="src\threadpool.h" /> <ClInclude Include="src\timer.h" /> <ClInclude Include="src\util.h" /> <ClInclude Include="src\viewer.h" /> <ClInclude Include="src\volume.h" /> <ClInclude Include="src\volume_constants.h" /> <ClInclude Include="src\volume_materials.h" /> </ItemGroup> <ItemGroup> <None Include="cl\apply_csg_operation.cl" /> <None Include="cl\compact.cl" /> <None Include="cl\cuckoo.cl" /> <None Include="cl\density_field.cl" /> <None Include="cl\duplicate.cl" /> <None Include="cl\fill_buffer.cl" /> <None Include="cl\find_active_voxels.cl" /> <None Include="cl\find_default_edges.cl" /> <None Include="cl\generate_default_field.cl" /> <None Include="cl\noise.cl" /> <None Include="cl\octree.cl" /> <None Include="cl\qef.cl" /> <None Include="cl\scan.cl" /> <None Include="cl\shared_constants.cl" /> <None Include="cl\simplex.cl" /> <None Include="default.cfg" /> <None Include="shaders\pass1.frag" /> <None Include="shaders\pass1.vert" /> <None Include="shaders\pass2.frag" /> <None Include="shaders\pass2.vert" /> <None Include="shaders\shadowmap.frag" /> <None Include="shaders\shadowmap.vert" /> <None Include="shaders\ui.frag" /> <None Include="shaders\ui.vert" /> <None Include="shaders\wireframe.frag" /> <None Include="shaders\wireframe.vert" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|Win32'"> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> <LocalDebuggerCommandArguments>-s [sort]</LocalDebuggerCommandArguments> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Release|x64'"> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> <LocalDebuggerCommandArguments>-s [sort]</LocalDebuggerCommandArguments> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|Win32'"> <LocalDebuggerCommandArguments>[allocator]</LocalDebuggerCommandArguments> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='UnitTest - Testing|x64'"> <LocalDebuggerCommandArguments>[allocator]</LocalDebuggerCommandArguments> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> </PropertyGroup> </Project>
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
s/OPENCL_/CUDA_/g s/ndrange/grid/g s/workitem/thread/g s/workgroupsize/threadblocksize/g s/stapmemperworkgroup/stasmemperblock/g
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
profilelogformat CSV streamid gpustarttimestamp gpuendtimestamp gridsize threadblocksize dynsmemperblock stasmemperblock regperthread memtransfersize
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="System"> <UniqueIdentifier>{a26574f9-9f64-472f-a524-c1c1ab7fc892}</UniqueIdentifier> </Filter> <Filter Include="Renderer"> <UniqueIdentifier>{c088df94-bc16-4b82-8467-b613e135a7de}</UniqueIdentifier> </Filter> <Filter Include="Voxel"> <UniqueIdentifier>{06201de1-85f2-41f9-87c6-eb1df83ace81}</UniqueIdentifier> </Filter> <Filter Include="Viewer"> <UniqueIdentifier>{df5c8c9b-6a4b-4289-b0f9-8054fe77d054}</UniqueIdentifier> </Filter> <Filter Include="Scripts"> <UniqueIdentifier>{42a2ef9c-55f3-4eb6-a88e-615f74a83263}</UniqueIdentifier> </Filter> <Filter Include="Scripts\Shaders"> <UniqueIdentifier>{f9200b1c-a4f1-4392-8dc7-77270102f9c5}</UniqueIdentifier> </Filter> <Filter Include="Scripts\OpenCL"> <UniqueIdentifier>{f8b77d53-dd27-4784-b7a3-7f29536a8725}</UniqueIdentifier> </Filter> <Filter Include="Tests"> <UniqueIdentifier>{879d6f96-173a-4a71-93d5-0ae835f958de}</UniqueIdentifier> </Filter> <Filter Include="Remotery"> <UniqueIdentifier>{f05710cf-6a6a-48fa-a17d-05aeff46ba9e}</UniqueIdentifier> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="src\file_utils.cpp"> <Filter>System</Filter> </ClCompile> <ClCompile Include="src\stb_image.c"> <Filter>System</Filter> </ClCompile> <ClCompile Include="src\threadpool.cpp"> <Filter>System</Filter> </ClCompile> <ClCompile Include="src\render.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\render_program.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\camera.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\compute.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\octree.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\volume.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\util.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\config.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\log.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\main.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\resource.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\primes.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\viewer.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\test_main.cpp"> <Filter>Tests</Filter> </ClCompile> <ClCompile Include="src\test_cuckoo.cpp"> <Filter>Tests</Filter> </ClCompile> <ClCompile Include="src\test_compute.cpp"> <Filter>Tests</Filter> </ClCompile> <ClCompile Include="src\compute_cuckoo.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\compute_octree.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\compute_density_field.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="..\..\imgui\imgui.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\imgui_handlers.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\compute_program.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="..\..\imgui\imgui_draw.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\gui.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\render_debug.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\pool_allocator.cpp"> <Filter>System</Filter> </ClCompile> <ClCompile Include="src\test_allocator.cpp"> <Filter>Tests</Filter> </ClCompile> <ClCompile Include="..\..\Remotery\lib\Remotery.c"> <Filter>Remotery</Filter> </ClCompile> <ClCompile Include="src\physics.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\frustum.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\clipmap.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\render_actor.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\render_shapes.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\render_mesh.cpp"> <Filter>Renderer</Filter> </ClCompile> <ClCompile Include="src\actors.cpp"> <Filter>Viewer</Filter> </ClCompile> <ClCompile Include="src\random.cpp"> <Filter>System</Filter> </ClCompile> <ClCompile Include="src\compute_csg.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\qef_simd.cpp"> <Filter>Voxel</Filter> </ClCompile> <ClCompile Include="src\ng_mesh_simplify.cpp"> <Filter>Voxel</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="src\timer.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\threadpool.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\slab_allocator.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\pool_allocator.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\lrucache.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\file_utils.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\render_program.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\render.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\camera.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\octree.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\volume.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\volume_constants.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\volume_materials.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\contour_constants.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\compute.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\aabb.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\util.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\config.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\force_include.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\log.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\resource.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\primes.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\compute_local.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\render_types.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\viewer.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\cuckoo.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\compute_cuckoo.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\imgui_handlers.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\materials.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\compute_program.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\gui.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\sdl_wrapper.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\render_debug.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\render_local.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="..\..\Remotery\lib\Remotery.h"> <Filter>Remotery</Filter> </ClInclude> <ClInclude Include="src\physics.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\frustum.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\clipmap.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\double_buffer.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\render_actor.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\render_shapes.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\render_mesh.h"> <Filter>Renderer</Filter> </ClInclude> <ClInclude Include="src\actors.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\random.h"> <Filter>System</Filter> </ClInclude> <ClInclude Include="src\glm_hash.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\options.h"> <Filter>Viewer</Filter> </ClInclude> <ClInclude Include="src\qef_simd.h"> <Filter>Voxel</Filter> </ClInclude> <ClInclude Include="src\ng_mesh_simplify.h"> <Filter>Voxel</Filter> </ClInclude> </ItemGroup> <ItemGroup> <None Include="default.cfg" /> <None Include="shaders\pass1.frag"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\pass1.vert"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\pass2.frag"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\pass2.vert"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\shadowmap.frag"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\shadowmap.vert"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\ui.frag"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\ui.vert"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\wireframe.frag"> <Filter>Scripts\Shaders</Filter> </None> <None Include="shaders\wireframe.vert"> <Filter>Scripts\Shaders</Filter> </None> <None Include="cl\apply_csg_operation.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\compact.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\duplicate.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\find_active_voxels.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\find_default_edges.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\generate_default_field.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\noise.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\scan.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\shared_constants.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\simplex.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\fill_buffer.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\qef.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\density_field.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\octree.cl"> <Filter>Scripts\OpenCL</Filter> </None> <None Include="cl\cuckoo.cl"> <Filter>Scripts\OpenCL</Filter> </None> </ItemGroup> </Project>
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "config.h" #include "log.h" #include <fstream> #include <sstream> #include <vector> bool Config_Load(Config& cfg, const std::string& filepath) { std::ifstream stream(filepath); if (!stream.is_open()) { return false; } std::string line; while (std::getline(stream, line)) { std::stringstream ss(line); std::string key; ss >> key; if (key[0] == '#') { // comments! continue; } if (_stricmp(key.c_str(), "WindowWidth") == 0) { ss >> cfg.windowWidth; // set the height incase its not specified if (cfg.windowHeight == -1) { cfg.windowHeight = (9 * cfg.windowWidth) / 16; } } else if (_stricmp(key.c_str(), "WindowHeight") == 0) { ss >> cfg.windowHeight; // set the width incase its not specified if (cfg.windowWidth == -1) { cfg.windowWidth = (16 * cfg.windowHeight) / 9; } } else if (_stricmp(key.c_str(), "ThreadpoolCount") == 0) { ss >> cfg.threadpoolCount; } else if (_stricmp(key.c_str(), "NoiseSeed") == 0) { ss >> cfg.noiseSeed; } else if (_stricmp(key.c_str(), "UseShadows") == 0) { std::string value; ss >> value; cfg.useShadows = _stricmp(value.c_str(), "True") == 0; } else if (_stricmp(key.c_str(), "ShadowMapSize") == 0) { ss >> cfg.shadowMapSize; } else if (_stricmp(key.c_str(), "FullScreen") == 0) { std::string value; ss >> value; cfg.fullscreen = _stricmp(value.c_str(), "True") == 0; } else { LogPrintf("Unknown key for line '%s'\n", line.c_str()); } } return true; }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_VOLUME_MATERIALS_H_BEEN_INCLUDED #define HAS_VOLUME_MATERIALS_H_BEEN_INCLUDED // ---------------------------------------------------------------------------- // TODO this is baws const uint32_t MATERIAL_NONE = 200; const uint32_t MATERIAL_AIR = 201; #endif // HAS_VOLUME_MATERIALS_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_COMPUTE_CUCKOO_BEEN_INCLUDED #define HAS_COMPUTE_CUCKOO_BEEN_INCLUDED #include <CL/cl.hpp> const uint64_t CUCKOO_EMPTY_VALUE = ~0ULL; const int CUCKOO_STASH_HASH_INDEX = 4; const int CUCKOO_HASH_FN_COUNT = CUCKOO_STASH_HASH_INDEX + 1; const int CUCKOO_STASH_SIZE = 101; const int CUCKOO_MAX_ITERATIONS = 32; struct CuckooData { cl::Buffer table, stash; cl::Buffer hashParams; int prime = -1; int insertedKeys = 0; int stashUsed = 0; // int rather than bool as bools seem somewhat iffy in OpenCL }; int Compute_InitialiseCuckoo(); int Cuckoo_InitialiseTable(CuckooData* data, const unsigned int tableSize); int Cuckoo_InsertKeys(CuckooData* data, const cl::Buffer& d_keys, const unsigned int count); #endif // HAS_COMPUTE_CUCKOO_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RENDER_DEBUG_H_BEEN_INCLUDED #define HAS_RENDER_DEBUG_H_BEEN_INCLUDED #include "render_types.h" #include <vector> #include <glm/glm.hpp> using glm::vec3; static const vec3 RenderColour_Red(1.f, 0.f, 0.f); static const vec3 RenderColour_Green(0.f, 1.f, 0.f); static const vec3 RenderColour_Blue(0.f, 0.f, 1.f); static const vec3 RenderColour_Black(0.f, 0.f, 0.f); static const vec3 RenderColour_White(1.f, 1.f, 1.f); struct RenderDebugCubeInfo { float min[3]; float max[3]; }; struct RenderDebugSphereInfo { float origin[3]; float radius; }; struct RenderDebugLineInfo { float start[3]; float end[3]; }; struct RenderDebugCmd { RenderShape shape; vec3 rgb; float alpha; union { RenderDebugCubeInfo cube; RenderDebugSphereInfo sphere; RenderDebugLineInfo line; }; }; typedef std::vector<RenderDebugCmd> RenderDebugCmdArray; class RenderDebugCmdBuffer { public: RenderDebugCmdBuffer& addCube(const vec3& rgb, const float alpha, const vec3& min, const float size) { RenderDebugCmd cmd; cmd.shape = RenderShape_Cube; cmd.rgb = rgb; cmd.alpha = alpha; cmd.cube.min[0] = min.x; cmd.cube.min[1] = min.y; cmd.cube.min[2] = min.z; cmd.cube.max[0] = min.x + size; cmd.cube.max[1] = min.y + size; cmd.cube.max[2] = min.z + size; cmds_.push_back(cmd); return *this; } RenderDebugCmdBuffer& addSphere(const vec3& rgb, const float alpha, const vec3& origin, const float radius) { RenderDebugCmd cmd; cmd.shape = RenderShape_Sphere; cmd.rgb = rgb; cmd.alpha = alpha; cmd.sphere.origin[0] = origin.x; cmd.sphere.origin[1] = origin.y; cmd.sphere.origin[2] = origin.z; cmd.sphere.radius = radius; cmds_.push_back(cmd); return *this; } RenderDebugCmdBuffer& addLine(const vec3& rgb, const float alpha, const vec3& start, const vec3& end) { RenderDebugCmd cmd; cmd.shape = RenderShape_Line; cmd.rgb = rgb; cmd.alpha = alpha; cmd.line.start[0] = start.x; cmd.line.start[1] = start.y; cmd.line.start[2] = start.z; cmd.line.end[0] = end.x; cmd.line.end[1] = end.y; cmd.line.end[2] = end.z; cmds_.push_back(cmd); return *this; } bool empty() const { return cmds_.empty(); } const RenderDebugCmdArray& commands() const { return cmds_; } private: RenderDebugCmdArray cmds_; }; int Render_AllocDebugDrawBuffer(); int Render_FreeDebugDrawBuffer(int* id); int Render_SetDebugDrawCmds(const int id, const RenderDebugCmdBuffer& cmds); int Render_EnableDebugDrawBuffer(int id); int Render_DisableDebugDrawBuffer(int id); #endif // HAS_RENDER_DEBUG_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_SLAB_ALLOCATOR_BEEN_INCLUDED #define HAS_SLAB_ALLOCATOR_BEEN_INCLUDED #include <vector> template <typename T, int COUNT_PER_SLAB> class SlabAllocator { public: static const int COUNT_PER_SLAB = COUNT_PER_SLAB; SlabAllocator() : count_(COUNT_PER_SLAB) // cause a slab to be allocated on first alloc() call { } ~SlabAllocator() { for (T* p: slabs_) { delete[] p; } } void clear() { for (T* p : slabs_) { delete[] p; } slabs_.clear(); count_ = COUNT_PER_SLAB; } T* alloc() { if (count_ == COUNT_PER_SLAB) { count_ = 0; slabs_.push_back(new T[COUNT_PER_SLAB]); } T* p = slabs_.back(); return &p[count_++]; } size_t size() const { return slabs_.empty() ? 0 : count_ + (slabs_.size() - 1) * COUNT_PER_SLAB; } private: // make non-copyable SlabAllocator(const SlabAllocator&); SlabAllocator& operator=(const SlabAllocator&); std::vector<T*> slabs_; int count_; }; #endif // HAS_SLAB_ALLOCATOR_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "file_utils.h" #include <stdio.h> #include <fstream> #include <sstream> bool LoadTextFile(const std::string& path, std::string& data) { std::ifstream file(path.c_str()); if (!file.is_open()) { return false; } std::stringstream fileData; fileData << file.rdbuf(); file.close(); data = fileData.str(); return true; }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef __FILE_UTILS_H__ #define __FILE_UTILS_H__ #include <string> bool LoadTextFile(const std::string& path, std::string& data); #endif // __FILE_UTILS_H__
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_OCTREE_H_BEEN_INCLUDED #define HAS_OCTREE_H_BEEN_INCLUDED #include "volume_constants.h" #include "render_types.h" #include "volume_materials.h" #include "slab_allocator.h" #include <stdint.h> #include <vector> #include <memory> #include <functional> #include <glm/glm.hpp> struct OctreeDrawInfo; class OctreeNode; class Octree; // ---------------------------------------------------------------------------- OctreeNode* Octree_ConstructUpwards( Octree* octree, const std::vector<OctreeNode*>& inputNodes, const glm::ivec3& rootMin, const int rootNodeSize ); // ---------------------------------------------------------------------------- MeshBuffer* Octree_GenerateMesh( OctreeNode* root, const glm::vec3& colour ); // ---------------------------------------------------------------------------- enum OctreeNodeType { Node_None, Node_Internal, Node_Leaf, }; // ---------------------------------------------------------------------------- struct OctreeDrawInfo { OctreeDrawInfo() : index(-1) , colour(1.f) , materialInfo(0) , qefIndex(-1) , error(-1.f) { } int index; // TODO should be unsigned int? or unsigned short? glm::vec3 position; glm::vec3 averageNormal; glm::vec3 colour; int materialInfo; int qefIndex; // TODO remove qefIndex as its only required temporarily float error; }; // ---------------------------------------------------------------------------- class OctreeNode { public: OctreeNode() : type(Node_None) , min(0, 0, 0) , size(0) , drawInfo(nullptr) { for (int i = 0; i < 8; i++) { children[i] = nullptr; } } OctreeNodeType getType() const { return type; } OctreeNodeType type; glm::ivec3 min; int size; OctreeNode* children[8]; OctreeDrawInfo* drawInfo; }; // ---------------------------------------------------------------------------- class Octree { public: Octree() : root_(nullptr) { } OctreeNode* allocNode() { return nodeAlloc_.alloc(); } OctreeDrawInfo* allocDrawInfo() { return drawInfoAlloc_.alloc(); } void clear() { nodeAlloc_.clear(); drawInfoAlloc_.clear(); root_ = nullptr; } void setRoot(OctreeNode* root) { root_ = root; } OctreeNode* getRoot() const { return root_; } size_t allocSize() const { return (nodeAlloc_.size() * sizeof(OctreeNode)) + (drawInfoAlloc_.size() * sizeof(OctreeDrawInfo)); } size_t nodeCount() const { return nodeAlloc_.size(); } private: typedef SlabAllocator<OctreeNode, 512> NodeAlloc; typedef SlabAllocator<OctreeDrawInfo, 512> DrawInfoAlloc; // make non-copyable Octree(const Octree&); Octree& operator=(const Octree&); OctreeNode* root_; NodeAlloc nodeAlloc_; DrawInfoAlloc drawInfoAlloc_; }; #endif // HAS_OCTREE_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "render_vertex.h" void Vertex_SetNormal(GeometryVertex& v, const glm::vec3& normal) { v.n[0] = normal.x; v.n[1] = normal.y; v.n[2] = normal.z; v.n[3] = 0.f; } const glm::vec3 Vertex_GetPosition(GeometryVertex& v) { return glm::vec3(v.p[0], v.p[1], v.p[2]); } template <> void Vertex_SetGLState<BillboardVertex>() { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(BillboardVertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(BillboardVertex), (void*)(sizeof(float) * 4)); } template <> void Vertex_ResetGLState<BillboardVertex>() { glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); } template <> void Vertex_SetGLState<GeometryVertex>() { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GeometryVertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(GeometryVertex), (void*)(sizeof(float) * 4)); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(GeometryVertex), (void*)(sizeof(float) * 8)); } template <> void Vertex_ResetGLState<GeometryVertex>() { glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_UTIL_H_BEEN_INCLUDED #define HAS_UTIL_H_BEEN_INCLUDED #include <glm/glm.hpp> const glm::ivec3 RoundVec3(const glm::vec3& v); // ---------------------------------------------------------------------------- #endif // !HAS_UTIL_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_SDL_WRAPPER_H_BEEN_INCLUDED #define HAS_SDL_WRAPPER_H_BEEN_INCLUDED #include <GL/glew.h> #include <SDL.h> #include <SDL_syswm.h> #include <SDL_opengl.h> // these are #define'd and not undef'd which causes problems with cl.hpp #undef __SSE__ #undef __SSE2__ // also left defined #undef near #undef far #endif // HAS_SDL_WRAPPER_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_ACTORS_H_BEEN_INCLUDED #define HAS_ACTORS_H_BEEN_INCLUDED #include "frustum.h" #include "aabb.h" #include <vector> #include <glm/glm.hpp> using glm::vec3; using glm::mat3; class RenderMesh; struct Actor; enum ActorShape { ActorShape_Cube, ActorShape_Sphere, }; void Actor_Initialise(const AABB& worldBounds); void Actor_Shutdown(); void Actor_Update(); Actor* Actor_Spawn(const ActorShape shape, const vec3& colour, const float size, const vec3& position); void Actor_Destroy(Actor* actor); void Actor_SetPosition(const vec3& position); void Actor_SetTransform(const mat3& transform); std::vector<RenderMesh*> Actor_GetVisibleActors(const Frustum& frustum); #endif // HAS_ACTORS_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_COMPUTE_H_BEEN_INCLUDED #define HAS_COMPUTE_H_BEEN_INCLUDED #include "render_types.h" #include "aabb.h" #include <vector> #include <glm/glm.hpp> #include <stdint.h> // need an error value to return from compute functions that encounter an non-OpenCL error #define LVN_CL_ERROR (-99999) // ---------------------------------------------------------------------------- struct CSGOperationInfo { int type = 0; RenderShape brushShape = RenderShape_Cube; int material = 0; float rotateY = 0.f; glm::vec4 origin; glm::vec4 dimensions; }; struct SeamNodeInfo { glm::ivec4 localspaceMin; glm::vec4 position; glm::vec4 normal; }; // ---------------------------------------------------------------------------- int Compute_Initialise(const int noiseSeed, const unsigned int defaultMaterial, const int numCSGBrushes); int Compute_Shutdown(); int Compute_SetNoiseSeed(const int noiseSeed); int Compute_StoreCSGOperation(const CSGOperationInfo& opInfo, const AABB& aabb); int Compute_ClearCSGOperations(); // ---------------------------------------------------------------------------- struct MeshGenerationContext; class Compute_MeshGenContext { public: static Compute_MeshGenContext* create(const int voxelsPerChunk); int voxelsPerChunk() const; int applyCSGOperations( const std::vector<CSGOperationInfo>& opInfo, const glm::ivec3& clipmapNodeMin, const int clipmapNodeSize); int freeChunkOctree( const glm::ivec3& min, const int size); int isChunkEmpty( const glm::ivec3& min, const int size, bool& isEmpty); int generateChunkMesh( const glm::ivec3& min, const int clipmapNodeSize, MeshBuffer* meshBuffer, std::vector<SeamNodeInfo>& seamNodeBuffer); private: MeshGenerationContext* privateCtx_; }; // ---------------------------------------------------------------------------- const char* GetCLErrorString(int error); // ---------------------------------------------------------------------------- #endif // HAS_COMPUTE_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "catch.hpp" #include "compute.h" #include "compute_local.h" #include "compute_cuckoo.h" #include "compute_sort.h" #include "timer.h" #include "volume_constants.h" #include "testdata/octree_keys_3.cpp" #include "testdata/duplicate_data_3.cpp" #include <random> #define CL_REQUIRE(f) REQUIRE((f) == CL_SUCCESS) int EnsureComputeInitialised() { static bool s_initialised = false; if (!s_initialised) { s_initialised = true; return Compute_Initialise(0x7d3af, 0, 2); } return CL_SUCCESS; } int TestRemoveDuplicate( ComputeContext* ctx, const uint32_t* values, uint32_t count, std::vector<uint32_t>& uniqueValues) { cl::Buffer d_values; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(uint32_t) * count, (void*)values, d_values)); unsigned int uniqueCount = 0; cl::Buffer d_uniqueValues = RemoveDuplicates(ctx->queue, d_values, count, &uniqueCount); uniqueValues.resize(uniqueCount); CL_CALL(ctx->queue.enqueueReadBuffer(d_uniqueValues, CL_TRUE, 0, sizeof(uint32_t) * uniqueCount, &uniqueValues[0])); return CL_SUCCESS; } TEST_CASE("Compute (Remove Duplicates)", "[compute]") { REQUIRE(EnsureComputeInitialised() == CL_SUCCESS); auto ctx = GetComputeContext(); const uint32_t* values = OCTREE_KEYS_DUPLICATE_3; const uint32_t count = (sizeof(OCTREE_KEYS_DUPLICATE_3) / sizeof(uint32_t)) - 1; std::vector<uint32_t> uniqueValues; REQUIRE(TestRemoveDuplicate(ctx, values, count, uniqueValues) == CL_SUCCESS); const uint32_t* uniques = OCTREE_KEYS_3; const uint32_t uniqueCount = (sizeof(OCTREE_KEYS_3) / sizeof(uint32_t)) - 1; REQUIRE(uniqueCount == uniqueValues.size()); std::vector<uint32_t> uniqueReference; uniqueReference.insert(end(uniqueReference), &uniques[0], &uniques[uniqueCount]); std::sort(begin(uniqueValues), end(uniqueValues)); std::sort(begin(uniqueReference), end(uniqueReference)); REQUIRE(memcmp(&uniqueReference[0], &uniqueValues[0], sizeof(uint32_t) * uniqueCount) == 0); } TEST_CASE("Compute (Cuckoo)", "[compute] [hashtable]") { REQUIRE(EnsureComputeInitialised() == CL_SUCCESS); const int KEY_COUNT = 100; std::vector<uint32_t> keys(KEY_COUNT); for (int i = 0; i < 100; i++) { keys[i] = i; } cl::Buffer d_keys; REQUIRE(CreateBuffer(CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(uint32_t) * KEY_COUNT, &keys[0], d_keys) == CL_SUCCESS); CuckooData cuckooData; REQUIRE(Cuckoo_InitialiseTable(&cuckooData, KEY_COUNT) == CL_SUCCESS); REQUIRE(Cuckoo_InsertKeys(&cuckooData, d_keys, KEY_COUNT) == CL_SUCCESS); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef __FORCE_INCLUDE_H__ #define __FORCE_INCLUDE_H__ #ifdef _HAS_ITERATOR_DEBUGGING #undef _HAS_ITERATOR_DEBUGGING #endif #define _HAS_ITERATOR_DEBUGGING 0 #ifdef USE_DEBUG_NEW #if defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new DEBUG_NEW #endif #endif #if defined(_DEBUG) || defined(TESTING) #define LVN_ASSERT(x) { if (!(x)) __debugbreak(); } #else #define LVN_ASSERT(x) (x); #endif #define LVN_ALWAYS_ASSERT(msg, x) { if (!(x)) { printf("%s\n", msg); __debugbreak(); } } #include <stdint.h> typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; const int LVN_SUCCESS = 0; const int LVN_ERR_INVALID_PARAM = 1; const int LVN_ERR_INVALID_PARAM_SIZE = 2; const int LVN_ERR_INVALID_PARAM_PTR = 3; #endif // __FORCE_INCLUDE_H__
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "model_obj.h" #include "file_utils.h" #include "log.h" #include <glm/glm.hpp> #include <functional> // ---------------------------------------------------------------------------- bool IsSpace(const char c) { return isspace(c) != 0; } std::vector<std::string> Tokenise(const std::string& str, const std::function<bool(const char)>& pred = IsSpace) { std::vector<std::string> tokens; std::string s; for (size_t i = 0; i < str.size(); i++) { if (pred(str[i])) { if (s != "") { tokens.push_back(s); s = ""; } } else { s += str[i]; } } if (s != "") { tokens.push_back(s); } return tokens; } // ---------------------------------------------------------------------------- ObjModel loadModel(const std::string& name, const std::vector<std::string>& vertexPositionData, const std::vector<std::string>& vertexNormalData, const std::vector<std::string>& faceData) { std::vector<glm::vec4> positions(vertexPositionData.size()); std::vector<glm::vec4> normals(vertexNormalData.size()); ObjModel model; for (size_t i = 0; i < vertexPositionData.size(); i++) { const std::string& v = vertexPositionData[i]; glm::vec4 position; sscanf(v.c_str(), "v %f %f %f\n", &position.x, &position.y, &position.z); positions[i] = position; const std::string& n = vertexNormalData[i]; glm::vec4 normal; sscanf(n.c_str(), "vn %f %f %f\n", &normal.x, &normal.y, &normal.z); normals[i] = normal; // TODO texture co-ords } // the face data is made up by referencing combinations of the position and normal data // e.g. position x and tex coord y and normal z, for each of the face's vertices: "f x/y/z a/b/c/ d/e/f" const auto isSlash = [](const char c) -> bool { return c == '/'; }; for (const std::string& f: faceData) { const auto tokens = Tokenise(f); if (tokens.size() != 4) { printf("Error: unsupported face specification '%s'\n", f.c_str()); return model; } // parse the data items (TODO texture coords) for (int i = 1; i < 4; i++) { const auto indices = Tokenise(tokens[i], isSlash); switch (indices.size()) { case 1: } } } // certain (xyz, st) pairs may be specified multiple times, we use // this indexMap to map the (xyz, st) pair to the index in m->vertexes_ std::map<FaceIndex, size_t> indexMap; for (size_t i = 0; i < faceData.size(); i++) { const std::string& f = faceData[i]; char type[4] = { 0 }; char buffer[128]; char* str = buffer; strncpy(str, f.c_str(), 128); if (sscanf(str, "%s", type) != 1) { LogPrintf("Error: bad face data '%s'\n", str); continue; } str = strstr(str, " ") + 1; std::vector<FaceIndex> faceIndexes; while (true) { unsigned short v = 0, t = 0; if (sscanf(str, "%hu/%hu", &v, &t) != 2) { break; } FaceIndex face(v, t); if (indexMap.find(face) == indexMap.end()) { indexMap[face] = m->vertexes_.size(); const Position& p = xyz[face.first - 1]; const TexPosition& t = st[face.second - 1]; m->vertexes_.push_back(GeometryVertex(p.x, p.y, p.z, t.u, t.v)); } faceIndexes.push_back(face); str = strstr(str, " "); if (str == NULL) { break; } str += 1; } bool flipWinding = false; for (size_t i = 3; i <= faceIndexes.size(); i++) { Index f0 = indexMap[faceIndexes[0]]; Index f1 = indexMap[faceIndexes[i-1]]; Index f2 = indexMap[faceIndexes[i-2]]; if (!flipWinding) { m->indexes_.push_back(f0); m->indexes_.push_back(f2); m->indexes_.push_back(f1); } else { m->indexes_.push_back(f1); m->indexes_.push_back(f0); m->indexes_.push_back(f2); } flipWinding = !flipWinding; } } std::vector<glm::vec3> normals; std::vector<int> normalsUsed; normalsUsed.resize(m->vertexes_.size(), 0); normals.resize(m->vertexes_.size(), glm::vec3(0)); for (size_t i = 0; i < m->indexes_.size() - 2; i += 3) { const Index ia = m->indexes_[i + 0]; const Index ib = m->indexes_[i + 1]; const Index ic = m->indexes_[i + 2]; if (ic >= m->vertexes_.size()) { LogPrintf("ic >= vertexes.size(): %d >= %d\n", ic, m->vertexes_.size()); continue; } const glm::vec3 a = Vertex_GetPosition(m->vertexes_[ia]); const glm::vec3 b = Vertex_GetPosition(m->vertexes_[ib]); const glm::vec3 c = Vertex_GetPosition(m->vertexes_[ic]); const glm::vec3 normal = glm::normalize(glm::cross(b - a, c - a)); for (size_t j = 0; j < 3; j++) { Index currentV = m->indexes_[i + j]; normalsUsed[currentV]++; if (normalsUsed[currentV] == 1) { normals[currentV] = normal; } else { const glm::vec3& n = normals[currentV]; const int used = normalsUsed[currentV]; normals[currentV] = (n * (1.f - (1.f / used))) + (normal * (1.f / used)); normals[currentV] = glm::normalize(normals[currentV]); } } } for (size_t i = 0; i < m->vertexes_.size(); i++) { GeometryVertex& v = m->vertexes_[i]; Vertex_SetNormal(v, normals[i]); } return m; } ObjModel LoadModelsFromFile(const std::string& path) { std::string data; if (!LoadTextFile(path, data)) { LogPrintf("WavefrontModel: can't load file '%s'\n", path.c_str()); return false; } enum State { STATE_NONE, STATE_VERTEX, STATE_FACE }; std::string name; std::vector<std::string> vertexData; std::vector<std::string> textureData; std::vector<std::string> normalData; std::vector<std::string> faceData; std::stringstream stream(data); std::string line; while (!stream.eof()) { getline(stream, line); if (line.find("g ") == 0 || line.find("o ") == 0) { LVN_ALWAYS_ASSERT("Only 1 model per file supported", name == ""); name = line.substr(2); } else if (line.find("v ") == 0) { vertexData.push_back(line); } else if (line.find("vn ") == 0) { normalData.push_back(line); } else if (line.find("vt ") == 0) { textureData.push_back(line); } else if (line.find("f ") == 0) { faceData.push_back(line); } } if (name != "" && !faceData.empty()) { // TODO assumes only 1 model per file return loadModel(name, vertexData, normalData, faceData); } return true; }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "pool_allocator.h" void IndexPoolAllocator::initialise(const int size) { LVN_ASSERT(!pool_); clear(); pool_ = new int[size]; for (int i = 0; i < (size - 1); i++) { pool_[i] = i + 1; } pool_[size - 1] = -1; firstFree_ = 0; size_ = size; allocated_ = 0; } void IndexPoolAllocator::clear() { delete[] pool_; pool_ = nullptr; firstFree_ = -1; size_ = -1; allocated_ = -1; } int IndexPoolAllocator::alloc() { int allocIndex = -1; if (firstFree_ != -1) { LVN_ASSERT(firstFree_ >= 0 && firstFree_ < size_); allocIndex = firstFree_; firstFree_ = pool_[allocIndex]; pool_[allocIndex] = -1; allocated_++; } return allocIndex; } void IndexPoolAllocator::free(int* p) { if (!p || *p < 0 || *p >= size_) { LVN_ASSERT(false); return; } pool_[*p] = firstFree_; firstFree_ = *p; *p = -1; allocated_--; }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RESOURCE_H_BEEN_INCLUDED #define HAS_RESOURCE_H_BEEN_INCLUDED #include "model_obj.h" #include "sdl_wrapper.h" GLuint Resource_LoadTexture(const char* path); GLuint Resource_LoadTextureArray(const std::vector<std::string>& textureFiles); #endif // HAS_RESOURCE_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_MATERIALS_H_BEEN_INCLUDED #define HAS_MATERIALS_H_BEEN_INCLUDED #include "resource.h" #include <stdint.h> #include <string> #include <vector> #include <glm/glm.hpp> class MaterialSet { public: // ---------------------------------------------------------------------------- MaterialSet() : textureArrayID_(0) { } // ---------------------------------------------------------------------------- void addMaterial(const std::string& path) { const float id = (float)texturePaths_.size(); texturePaths_.push_back(path); materials_.push_back(glm::vec3(id)); } // ---------------------------------------------------------------------------- void addMaterial(const std::string& pathX, const std::string& pathY, const std::string& pathZ) { const float idX = (float)texturePaths_.size(); const float idY = idX + 1.f; const float idZ = idX + 2.f; texturePaths_.push_back(pathX); texturePaths_.push_back(pathY); texturePaths_.push_back(pathZ); materials_.push_back(glm::vec3(idX, idY, idZ)); } // ---------------------------------------------------------------------------- uint32_t bakeTextureArray() { if (texturePaths_.empty()) { return 0; } if (textureArrayID_ == 0) { textureArrayID_ = Resource_LoadTextureArray(texturePaths_); } return textureArrayID_; } // ---------------------------------------------------------------------------- std::vector<float> exportMaterialTextures() const { std::vector<float> textureIDs(materials_.size() * 3); for (size_t i = 0; i < materials_.size(); i++) { textureIDs[(i * 3) + 0] = materials_[i].x; textureIDs[(i * 3) + 1] = materials_[i].y; textureIDs[(i * 3) + 2] = materials_[i].z; } return textureIDs; } // ---------------------------------------------------------------------------- unsigned int size() const { return materials_.size(); } // ---------------------------------------------------------------------------- private: std::vector<std::string> texturePaths_; std::vector<glm::vec3> materials_; uint32_t textureArrayID_; }; #endif // HAS_MATERIALS_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "gui.h" #include "imgui.h" #include "imgui_handlers.h" #include "viewer.h" #include "options.h" #include <random> // ---------------------------------------------------------------------------- SDL_Window* g_guiWindow = nullptr; // ---------------------------------------------------------------------------- void GUI_Initialise(SDL_Window* window) { g_guiWindow = window; ImGui_ImplSdl_Init(g_guiWindow); } // ---------------------------------------------------------------------------- void GUI_Shutdown() { g_guiWindow = nullptr; ImGui_ImplSdl_Shutdown(); } // ---------------------------------------------------------------------------- void GUI_DrawFrame(GUIOptions* options, const GUIFrameInfo& frameInfo) { EditContext ctx = Viewer_GetEditContextState(); static std::mt19937 prng; static std::uniform_int_distribution<uint32_t> distribution(1 << 28, INT_MAX); ImGui::GetIO().MouseDrawCursor = false; ImGui_ImplSdl_NewFrame(g_guiWindow); SDL_ShowCursor(options->showOptions ? 1 : 0); if (options->showOptions) { ImGui::Begin("Options"); if (ImGui::Button("Close Window")) { options->showOptions = false; } ImGui::SameLine(); if (ImGui::Button("Toggle Overlay")) { options->showOverlay = !options->showOverlay; } if (ImGui::CollapsingHeader("Options")) { if (ImGui::TreeNode("Terrain")) { static char seed[9] = ""; SDL_snprintf(seed, 9, "%x", options->noiseSeed); if (ImGui::InputText("Noise seed", seed, 9, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { char* end = nullptr; options->noiseSeed = SDL_strtol(seed, &end, 16); } ImGui::SliderInt("Size", &options->worldBrickCountXZ, 2, 16); ImGui::BeginGroup(); if (ImGui::Button("Random Noise Seed")) { options->noiseSeed = distribution(prng); } ImGui::SameLine(); options->regenerateVolume = ImGui::Button("Regenerate Volume"); ImGui::SameLine(); ImGui::EndGroup(); ImGui::TreePop(); } if (ImGui::TreeNode("Brush")) { int brushSize = ctx.brushSize[0]; if (ImGui::SliderInt("Brush size", &brushSize, MIN_BRUSH_SIZE, MAX_BRUSH_SIZE)) { ctx.brushSize = ivec3(brushSize); } ImGui::BeginGroup(); ImGui::Text("Snap mode:"); ImGui::SameLine(); ImGui::RadioButton("Off", &ctx.snapMode, EditSnapMode_Off); ImGui::SameLine(); ImGui::RadioButton("Grid", &ctx.snapMode, EditSnapMode_Grid); ImGui::SameLine(); ImGui::RadioButton("Follow camera", &ctx.snapMode, EditSnapMode_FollowCamera); ImGui::EndGroup(); ImGui::TreePop(); Viewer_UpdateEditContext(ctx); } if (ImGui::TreeNode("Mesh Simplification")) { auto& options = Options::get(); ImGui::SliderFloat("Max error", &options.meshMaxError_, 0.f, 50.f); ImGui::SliderFloat("Max edge length", &options.meshMaxEdgeLen_, 0.5, 5.0); ImGui::SliderFloat("Max normal angle", &options.meshMinCosAngle_, 0, 1); } } ImGui::End(); } if (options->showOverlay) { ImGui::SetNextWindowPos(ImVec2(10,10)); if (ImGui::Begin("Info", nullptr, ImVec2(250,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) { ImGui::Text("%.1f FPS", ImGui::GetIO().Framerate); ImGui::Text("Position: %.1f %.1f %.1f", frameInfo.position.x, frameInfo.position.y, frameInfo.position.z); ImGui::Text("Triangles: %.1f k", frameInfo.numTriangles / 1000.f); ImGui::Text("Clipmap Nodes: %d\n", frameInfo.numVisibleNodes); } ImGui::End(); } // Rendering ImGuiIO& io = ImGui::GetIO(); glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); ImGui::Render(); } void GUI_ProcessEvent(SDL_Event* event) { ImGui_ImplSdl_ProcessEvent(event); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "actors.h" #include "render.h" #include "physics.h" #include "pool_allocator.h" #include <unordered_set> #include <mutex> using glm::ivec3; // ---------------------------------------------------------------------------- struct Actor { RenderMesh* mesh = nullptr; PhysicsHandle body = nullptr; }; const int MAX_ACTORS = 4 * 1024; // arbitrary static PoolAllocator<Actor> g_actorAlloc; static std::unordered_set<Actor*> g_actors; static std::mutex g_actorMutex; static AABB g_worldBounds; // ---------------------------------------------------------------------------- void Actor_Initialise(const AABB& worldBounds) { g_actorAlloc.initialise(MAX_ACTORS); g_worldBounds = worldBounds; } // ---------------------------------------------------------------------------- void Actor_Shutdown() { g_actorAlloc.clear(); g_actors.clear(); } // ---------------------------------------------------------------------------- Actor* Actor_Spawn(const ActorShape shape, const vec3& colour, const float size, const vec3& position) { Actor* actor = nullptr; { std::lock_guard<std::mutex> lock(g_actorMutex); actor = g_actorAlloc.alloc(); } if (actor) { RenderShape renderShape = RenderShape_None; if (shape == ActorShape_Cube) { renderShape = RenderShape_Cube; actor->body = Physics_SpawnCube(vec3(size / 2.f), 10.f, position); } else { renderShape = RenderShape_Sphere; actor->body = Physics_SpawnSphere(size, 10.f, position); } LVN_ASSERT(renderShape != RenderShape_None); LVN_ASSERT(actor->body); if (ActorMeshBuffer* buffer = Render_CreateActorMesh(renderShape, size)) { actor->mesh = Render_AllocRenderMesh("actor", buffer); actor->mesh->setPosition(position); actor->mesh->setColour(vec4(colour, 0.f)); } LVN_ASSERT(actor->mesh); LVN_ASSERT(actor->body); std::lock_guard<std::mutex> lock(g_actorMutex); g_actors.insert(actor); } return actor; } // ---------------------------------------------------------------------------- void Actor_Destroy(Actor* actor) { LVN_ASSERT(actor); LVN_ASSERT(actor->mesh); LVN_ASSERT(actor->body); Render_FreeRenderMesh(&actor->mesh); PhysicsBody_Free(actor->body); std::lock_guard<std::mutex> lock(g_actorMutex); g_actors.erase(actor); g_actorAlloc.free(actor); } // ---------------------------------------------------------------------------- void Actor_Update() { std::vector<Actor*> outOfBoundsActors; for (Actor* actor: g_actors) { const vec3 position = PhysicsBody_GetPosition(actor->body); if (!g_worldBounds.pointIsInside(ivec3(position))) { outOfBoundsActors.push_back(actor); continue; } RenderMesh* mesh = actor->mesh; mesh->setPosition(position); mesh->setTransform(PhysicsBody_GetTransform(actor->body)); } for (Actor* actor: outOfBoundsActors) { Actor_Destroy(actor); } } // ---------------------------------------------------------------------------- std::vector<RenderMesh*> Actor_GetVisibleActors(const Frustum& frustum) { // TODO frustum cull std::vector<RenderMesh*> meshes; for (Actor* actor: g_actors) { RenderMesh* mesh = actor->mesh; meshes.push_back(mesh); } return meshes; } // ----------------------------------------------------------------------------
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "threadpool.h" #include <thread> #include <condition_variable> #include <deque> #include <atomic> #include <vector> #include <algorithm> #include "compute.h" // ---------------------------------------------------------------------------- namespace { // ---------------------------------------------------------------------------- std::vector<std::thread> g_threads; std::condition_variable g_cond; std::mutex g_mutex; std::condition_variable g_jobFinishedCondition; std::mutex g_jobFinishedMutex; using ThreadJobFinishedFunc = std::function<void()>; struct Job { Job(const ThreadPoolFunc& func = nullptr, const ThreadJobFinishedFunc& callback = nullptr) : func_(func) , finishedCallback_(callback) { } ThreadPoolFunc func_ = nullptr; ThreadPoolJob id_ = -1; ThreadJobFinishedFunc finishedCallback_ = nullptr; }; std::deque<Job> g_jobs; std::atomic<bool> g_stop = false; std::atomic<int> g_activeJobs = 0; std::thread::id g_mainThreadId; // ---------------------------------------------------------------------------- void ThreadFunction() { while (true) { Job job; { std::unique_lock<std::mutex> lock(g_mutex); while (!g_stop && g_jobs.empty()) { g_cond.wait(lock); } if (g_stop) { return; } job = g_jobs.front(); g_jobs.pop_front(); } if (job.func_) { g_activeJobs++; job.func_(); if (job.finishedCallback_) { job.finishedCallback_(); } g_activeJobs--; } { std::unique_lock<std::mutex> lock(g_jobFinishedMutex); g_jobFinishedCondition.notify_all(); } } } // ---------------------------------------------------------------------------- } // ---------------------------------------------------------------------------- void ThreadPool_Initialise(const int numThreads) { g_mainThreadId = std::this_thread::get_id(); for (int i = 0; i < numThreads; i++) { g_threads.push_back(std::thread(ThreadFunction)); } } // ---------------------------------------------------------------------------- ThreadPoolJob ThreadPool_ScheduleJob(const std::function<void()>& f) { { std::unique_lock<std::mutex> lock(g_mutex); g_jobs.push_back(Job(f)); } g_cond.notify_one(); return 0; } // ---------------------------------------------------------------------------- void ThreadPool_WaitForJobs() { while (true) { bool empty = false; { std::unique_lock<std::mutex> lock(g_mutex); empty = g_jobs.empty(); } if (empty) { std::unique_lock<std::mutex> lock(g_jobFinishedMutex); g_jobFinishedCondition.notify_all(); break; } else { #if 1 std::this_thread::yield(); #else std::unique_lock<std::mutex> lock(g_jobFinishedMutex); g_jobFinishedCondition.wait(lock); #endif } } // TODO this may still have an occasional deadlock when doing CSG edits while (g_activeJobs > 0) { std::this_thread::yield(); // std::unique_lock<std::mutex> lock(g_jobFinishedMutex); // g_jobFinishedCondition.wait(lock, [&]() { return g_activeJobs == 0; }); } } // ---------------------------------------------------------------------------- void ThreadPool_Destroy() { g_stop = true; { std::unique_lock<std::mutex> lock(g_mutex); g_cond.notify_all(); } std::for_each(begin(g_threads), end(g_threads), [](std::thread& t) { t.join(); }); } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- void JobGroup::schedule(const ThreadPoolFunc& func) { numScheduledJobs_++; { auto callback = std::bind(&JobGroup::onJobFinished, this); std::unique_lock<std::mutex> lock(g_mutex); g_jobs.push_back(Job(func, callback)); } g_cond.notify_one(); } // ---------------------------------------------------------------------------- void JobGroup::onJobFinished() { numCompletedJobs_++; } // ---------------------------------------------------------------------------- void JobGroup::wait() { while (numCompletedJobs_ != numScheduledJobs_) { std::this_thread::yield(); } } // ----------------------------------------------------------------------------
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "compute_local.h" #include "compute_cuckoo.h" #include "volume_materials.h" #include "volume_constants.h" #include "timer.h" #include "file_utils.h" #include "glsl_svd.h" #include <vector> #include <sstream> #include <unordered_map> #include <glm/glm.hpp> #include <glm/gtx/integer.hpp> using namespace glm; #include <Remotery.h> // ---------------------------------------------------------------------------- // TODO remove const glm::vec3 ColourForMinLeafSize(const int minLeafSize); // ---------------------------------------------------------------------------- int ConstructOctreeFromField( MeshGenerationContext* meshGen, const glm::ivec3& min, const GPUDensityField& field, GPUOctree* octree) { rmt_ScopedCPUSample(ConstructOctree); // printf("Constuct octree (%d %d %d)\n", min.x, min.y, min.z); Timer timer; timer.start(); timer.disable(); timer.printElapsed("initialise field"); if (field.numEdges == 0) { // no voxels to find timer.printElapsed("no edges"); return CL_SUCCESS; } auto ctx = GetComputeContext(); const int chunkBufferSize = meshGen->voxelsPerChunk * meshGen->voxelsPerChunk * meshGen->voxelsPerChunk; cl::Buffer d_leafOccupancy(ctx->context, CL_MEM_READ_WRITE, chunkBufferSize * sizeof(int)); cl::Buffer d_leafEdgeInfo(ctx->context, CL_MEM_READ_WRITE, chunkBufferSize * sizeof(int)); cl::Buffer d_leafCodes(ctx->context, CL_MEM_READ_WRITE, chunkBufferSize * sizeof(int)); cl::Buffer d_leafMaterials(ctx->context, CL_MEM_READ_WRITE, chunkBufferSize * sizeof(cl_int)); cl::Buffer d_voxelScan(ctx->context, CL_MEM_READ_WRITE, chunkBufferSize * sizeof(int)); { rmt_ScopedCPUSample(Find); int index = 0; cl::Kernel findActiveKernel(meshGen->octreeProgram.get(), "FindActiveVoxels"); CL_CALL(findActiveKernel.setArg(index++, field.materials)); CL_CALL(findActiveKernel.setArg(index++, d_leafOccupancy)); CL_CALL(findActiveKernel.setArg(index++, d_leafEdgeInfo)); CL_CALL(findActiveKernel.setArg(index++, d_leafCodes)); CL_CALL(findActiveKernel.setArg(index++, d_leafMaterials)); CL_CALL(ctx->queue.enqueueNDRangeKernel(findActiveKernel, cl::NullRange, cl::NDRange(meshGen->voxelsPerChunk, meshGen->voxelsPerChunk, meshGen->voxelsPerChunk), cl::NullRange)); octree->numNodes = ExclusiveScan(ctx->queue, d_leafOccupancy, d_voxelScan, chunkBufferSize); if (octree->numNodes <= 0) { // i.e. an error if < 0, == 0 is ok just no surface for this chunk timer.printElapsed("no voxels"); const int error = octree->numNodes; octree->numNodes = 0; return error; } } cl::Buffer d_compactLeafEdgeInfo(ctx->context, CL_MEM_READ_WRITE, octree->numNodes * sizeof(int)); { rmt_ScopedCPUSample(Compact); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * octree->numNodes, nullptr, octree->d_nodeCodes)); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * octree->numNodes, nullptr, octree->d_nodeMaterials)); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_float4) * octree->numNodes, nullptr, octree->d_vertexPositions)); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_float4) * octree->numNodes, nullptr, octree->d_vertexNormals)); int index = 0; cl::Kernel compactVoxelsKernel(meshGen->octreeProgram.get(), "CompactVoxels"); CL_CALL(compactVoxelsKernel.setArg(index++, d_leafOccupancy)); CL_CALL(compactVoxelsKernel.setArg(index++, d_leafEdgeInfo)); CL_CALL(compactVoxelsKernel.setArg(index++, d_leafCodes)); CL_CALL(compactVoxelsKernel.setArg(index++, d_leafMaterials)); CL_CALL(compactVoxelsKernel.setArg(index++, d_voxelScan)); CL_CALL(compactVoxelsKernel.setArg(index++, octree->d_nodeCodes)); CL_CALL(compactVoxelsKernel.setArg(index++, d_compactLeafEdgeInfo)); CL_CALL(compactVoxelsKernel.setArg(index++, octree->d_nodeMaterials)); CL_CALL(ctx->queue.enqueueNDRangeKernel(compactVoxelsKernel, cl::NullRange, chunkBufferSize, cl::NullRange)); } cl::Buffer d_qefs; { rmt_ScopedCPUSample(Leafs); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(QEFData) * octree->numNodes, nullptr, d_qefs)); CuckooData edgeHashTable; CL_CALL(Cuckoo_InitialiseTable(&edgeHashTable, field.numEdges)); CL_CALL(Cuckoo_InsertKeys(&edgeHashTable, field.edgeIndices, field.numEdges)); int index = 0; const int sampleScale = field.size / (meshGen->voxelsPerChunk * LEAF_SIZE_SCALE); cl::Kernel createLeafNodes(meshGen->octreeProgram.get(), "CreateLeafNodes"); CL_CALL(createLeafNodes.setArg(index++, sampleScale)); CL_CALL(createLeafNodes.setArg(index++, octree->d_nodeCodes)); CL_CALL(createLeafNodes.setArg(index++, d_compactLeafEdgeInfo)); CL_CALL(createLeafNodes.setArg(index++, field.normals)); CL_CALL(createLeafNodes.setArg(index++, octree->d_vertexNormals)); CL_CALL(createLeafNodes.setArg(index++, d_qefs)); CL_CALL(createLeafNodes.setArg(index++, edgeHashTable.table)); CL_CALL(createLeafNodes.setArg(index++, edgeHashTable.stash)); CL_CALL(createLeafNodes.setArg(index++, edgeHashTable.prime)); CL_CALL(createLeafNodes.setArg(index++, edgeHashTable.hashParams)); CL_CALL(createLeafNodes.setArg(index++, edgeHashTable.stashUsed)); CL_CALL(ctx->queue.enqueueNDRangeKernel(createLeafNodes, cl::NullRange, octree->numNodes, cl::NullRange)); } { rmt_ScopedCPUSample(QEF); cl_float4 d_worldSpaceOffset = { min.x, min.y, min.z, 0 }; cl::Kernel solveQEFs(meshGen->octreeProgram.get(), "SolveQEFs"); int index = 0; CL_CALL(solveQEFs.setArg(index++, d_worldSpaceOffset)); CL_CALL(solveQEFs.setArg(index++, d_qefs)); CL_CALL(solveQEFs.setArg(index++, octree->d_vertexPositions)); CL_CALL(ctx->queue.enqueueNDRangeKernel(solveQEFs, cl::NullRange, octree->numNodes, cl::NullRange)); } { rmt_ScopedCPUSample(Cuckoo); CL_CALL(Cuckoo_InitialiseTable(&octree->d_hashTable, octree->numNodes)); CL_CALL(Cuckoo_InsertKeys(&octree->d_hashTable, octree->d_nodeCodes, octree->numNodes)); } timer.printElapsed("done"); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int LoadOctree(MeshGenerationContext* meshGen, const ivec3& min, const int clipmapNodeSize, GPUOctree* octree) { rmt_ScopedCPUSample(LoadOctree); const ivec4 key(min, clipmapNodeSize); auto iter = meshGen->octreeCache.find(key); if (iter != end(meshGen->octreeCache)) { *octree = iter->second; return CL_SUCCESS; } GPUDensityField field; CL_CALL(LoadDensityField(meshGen, min, clipmapNodeSize, &field)); if (field.numEdges == 0) { // no point in trying to construct the octree octree->numNodes = 0; } else { CL_CALL(ConstructOctreeFromField(meshGen, min, field, octree)); meshGen->octreeCache[key] = *octree; } // printf("%d octrees cached\n", meshGen->octreeCache.size()); return CL_SUCCESS; } // ---------------------------------------------------------------------------- // Use the nodes extracted from the octree(s) to generate a mesh. The nodes in // the buffer are treated as leaf nodes in an octree and as such their positions // should be in the [0, VOXELS_PER_CHUNK) range -- when constructing the buffer from // multiple octrees the nodes will need to be remapped to the new composite octree // ---------------------------------------------------------------------------- int GenerateMeshFromOctree( MeshGenerationContext* meshGen, const glm::ivec3& min, const int clipmapNodeSize, const GPUOctree& octree, MeshBufferGPU* meshBuffer) { rmt_ScopedCPUSample(GenerateMeshFromOctree); ComputeContext* ctx = GetComputeContext(); int index = 0; // printf("Generate mesh: size=%d\n", clipmapNodeSize); Timer timer; timer.start(); timer.disable(); const int numVertices = octree.numNodes; const int indexBufferSize = numVertices * 6 * 3; const int trianglesValidSize = numVertices * 3; cl::Buffer d_indexBuffer, d_trianglesValid; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * indexBufferSize, nullptr, d_indexBuffer)); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * trianglesValidSize, nullptr, d_trianglesValid)); index = 0; cl::Kernel k_GenerateMesh(meshGen->octreeProgram.get(), "GenerateMesh"); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_nodeCodes)); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_nodeMaterials)); CL_CALL(k_GenerateMesh.setArg(index++, d_indexBuffer)); CL_CALL(k_GenerateMesh.setArg(index++, d_trianglesValid)); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_hashTable.table)); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_hashTable.stash)); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_hashTable.prime)); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_hashTable.hashParams)); CL_CALL(k_GenerateMesh.setArg(index++, octree.d_hashTable.stashUsed)); CL_CALL(ctx->queue.enqueueNDRangeKernel(k_GenerateMesh, cl::NullRange, octree.numNodes, cl::NullRange)); cl::Buffer d_trianglesScan; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * trianglesValidSize, nullptr, d_trianglesScan)); int numTriangles = ExclusiveScan(ctx->queue, d_trianglesValid, d_trianglesScan, trianglesValidSize); if (numTriangles <= 0) { // < 0 is an error, so return that, 0 is ok just no tris to generate, return 0 which is CL_SUCCESS return numTriangles; } numTriangles *= 2; LVN_ALWAYS_ASSERT("Mesh triangle count too high", numTriangles < MAX_MESH_TRIANGLES); LVN_ALWAYS_ASSERT("Mesh vertex count too high", numVertices < MAX_MESH_VERTICES); cl::Buffer d_compactIndexBuffer; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * numTriangles * 3, nullptr, d_compactIndexBuffer)); index = 0; cl::Kernel k_CompactMeshTriangles(meshGen->octreeProgram.get(), "CompactMeshTriangles"); CL_CALL(k_CompactMeshTriangles.setArg(index++, d_trianglesValid)); CL_CALL(k_CompactMeshTriangles.setArg(index++, d_trianglesScan)); CL_CALL(k_CompactMeshTriangles.setArg(index++, d_indexBuffer)); CL_CALL(k_CompactMeshTriangles.setArg(index++, d_compactIndexBuffer)); CL_CALL(ctx->queue.enqueueNDRangeKernel(k_CompactMeshTriangles, cl::NullRange, trianglesValidSize, cl::NullRange)); cl::Buffer d_vertexBuffer; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(MeshVertex) * numVertices, nullptr, d_vertexBuffer)); index = 0; const auto colour = ColourForMinLeafSize(clipmapNodeSize / CLIPMAP_LEAF_SIZE); cl_float4 d_colour = { colour.x, colour.y, colour.z, 0.f }; cl::Kernel k_GenerateMeshVertexBuffer(meshGen->octreeProgram.get(), "GenerateMeshVertexBuffer"); CL_CALL(k_GenerateMeshVertexBuffer.setArg(index++, octree.d_vertexPositions)); CL_CALL(k_GenerateMeshVertexBuffer.setArg(index++, octree.d_vertexNormals)); CL_CALL(k_GenerateMeshVertexBuffer.setArg(index++, octree.d_nodeMaterials)); CL_CALL(k_GenerateMeshVertexBuffer.setArg(index++, d_colour)); CL_CALL(k_GenerateMeshVertexBuffer.setArg(index++, d_vertexBuffer)); CL_CALL(ctx->queue.enqueueNDRangeKernel(k_GenerateMeshVertexBuffer, cl::NullRange, numVertices, cl::NullRange)); meshBuffer->vertices = d_vertexBuffer; meshBuffer->countVertices = numVertices; meshBuffer->triangles = d_compactIndexBuffer; meshBuffer->countTriangles = numTriangles; timer.printElapsed("generated mesh"); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int GatherSeamNodesFromOctree( MeshGenerationContext* meshGen, const glm::ivec3& nodeMin, const int nodeSize, const GPUOctree& octree, std::vector<SeamNodeInfo>& seamNodeBuffer) { rmt_ScopedCPUSample(GatherSeamNodes); auto ctx = GetComputeContext(); cl::Buffer d_isSeamNode, d_isSeamNodeScan; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * octree.numNodes, nullptr, d_isSeamNode)); CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(cl_int) * octree.numNodes, nullptr, d_isSeamNodeScan)); int index = 0; cl::Kernel k_FindSeamNodes(meshGen->octreeProgram.get(), "FindSeamNodes"); CL_CALL(k_FindSeamNodes.setArg(index++, octree.d_nodeCodes)); CL_CALL(k_FindSeamNodes.setArg(index++, d_isSeamNode)); CL_CALL(ctx->queue.enqueueNDRangeKernel(k_FindSeamNodes, cl::NullRange, octree.numNodes, cl::NullRange)); const int numSeamNodes = ExclusiveScan(ctx->queue, d_isSeamNode, d_isSeamNodeScan, octree.numNodes); if (numSeamNodes <= 0) { return numSeamNodes; } cl::Buffer d_seamNodeInfo; CL_CALL(CreateBuffer(CL_MEM_READ_WRITE, sizeof(SeamNodeInfo) * numSeamNodes, nullptr, d_seamNodeInfo)); cl_int4 d_min = { nodeMin.x, nodeMin.y, nodeMin.z, 0 }; index = 0; cl::Kernel k_ExtractSeamNodeInfo(meshGen->octreeProgram.get(), "ExtractSeamNodeInfo"); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, d_isSeamNode)); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, d_isSeamNodeScan)); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, octree.d_nodeCodes)); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, octree.d_nodeMaterials)); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, octree.d_vertexPositions)); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, octree.d_vertexNormals)); CL_CALL(k_ExtractSeamNodeInfo.setArg(index++, d_seamNodeInfo)); CL_CALL(ctx->queue.enqueueNDRangeKernel(k_ExtractSeamNodeInfo, cl::NullRange, octree.numNodes, cl::NullRange)); seamNodeBuffer.resize(numSeamNodes); CL_CALL(ctx->queue.enqueueReadBuffer(d_seamNodeInfo, CL_TRUE, 0, sizeof(SeamNodeInfo) * numSeamNodes, &seamNodeBuffer[0])); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int ExportMeshBuffer( const MeshBufferGPU& gpuBuffer, MeshBuffer* cpuBuffer) { rmt_ScopedCPUSample(ExportMesh); cpuBuffer->numVertices = gpuBuffer.countVertices; cpuBuffer->numTriangles = gpuBuffer.countTriangles; if (gpuBuffer.countVertices == 0) { return CL_SUCCESS; } auto ctx = GetComputeContext(); CL_CALL(ctx->queue.enqueueReadBuffer(gpuBuffer.vertices, CL_FALSE, 0, sizeof(MeshVertex) * gpuBuffer.countVertices, &cpuBuffer->vertices[0])); CL_CALL(ctx->queue.enqueueReadBuffer(gpuBuffer.triangles, CL_TRUE, 0, sizeof(MeshTriangle) * gpuBuffer.countTriangles, &cpuBuffer->triangles[0])); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int Compute_GenerateChunkMesh( MeshGenerationContext* meshGen, const glm::ivec3& min, const int clipmapNodeSize, MeshBuffer* meshBuffer, std::vector<SeamNodeInfo>& seamNodeBuffer) { rmt_ScopedCPUSample(Compute_GenerateChunkMesh); seamNodeBuffer.clear(); GPUOctree octree; CL_CALL(LoadOctree(meshGen, min, clipmapNodeSize, &octree)); if (octree.numNodes > 0) { MeshBufferGPU meshBufferGPU; CL_CALL(GenerateMeshFromOctree(meshGen, min, clipmapNodeSize, octree, &meshBufferGPU)); CL_CALL(ExportMeshBuffer(meshBufferGPU, meshBuffer)); // TODO can do this on creation now CL_CALL(GatherSeamNodesFromOctree(meshGen, min, clipmapNodeSize, octree, seamNodeBuffer)); } return CL_SUCCESS; } // ---------------------------------------------------------------------------- int Compute_FreeChunkOctree( MeshGenerationContext* meshGen, const glm::ivec3& min, const int clipmapNodeSize) { const glm::ivec4 key(min, clipmapNodeSize); meshGen->octreeCache.erase(key); return CL_SUCCESS; } // ----------------------------------------------------------------------------
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "render_program.h" #include "log.h" #include "file_utils.h" GLSLProgram::GLSLProgram() : program_(0) { } GLSLProgram::~GLSLProgram() { if (program_ > 0) { glDeleteProgram(program_); } } bool GLSLProgram::initialise() { program_ = glCreateProgram(); prependLine("#version 420"); return true; } void GLSLProgram::printShaderInfo(GLuint shader) const { int maxLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); static char buffer[2048]; int length = 0; glGetShaderInfoLog(shader, maxLength, &length, buffer); LogPrintf(" shader (%s): %s\n", filePath_.c_str(), buffer); } void GLSLProgram::printProgramInfo(GLuint program) const { int maxLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); static char buffer[2048]; int length = 0; glGetProgramInfoLog(program, maxLength, &length, buffer); LogPrintf(" program (%s): %s\n", filePath_.c_str(), buffer); } void GLSLProgram::prependLine(const std::string& line) { header_ += line; header_ += "\n"; } bool GLSLProgram::compileShader(const GLenum type, const std::string& filePath) { std::string data; if (!LoadTextFile(filePath.c_str(), data)) { return false; } filePath_ = filePath; const GLchar* inputCode[] = { header_.c_str(), data.c_str() }; const GLuint shader = glCreateShader(type); glShaderSource(shader, 2, inputCode, NULL); glCompileShader(shader); GLint status = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); printShaderInfo(shader); if (status == GL_FALSE) { return false; } glAttachShader(program_, shader); shaders_.push_back(shader); return true; } bool GLSLProgram::link() { if (shaders_.empty()) { return true; } glLinkProgram(program_); if (GLenum err = glGetError() != GL_NO_ERROR) { printf("GLSLProgram: err=%d\n", err); return false; } printProgramInfo(program_); GLint status = 0; glGetProgramiv(program_, GL_LINK_STATUS, &status); if (status == GL_FALSE) { return false; } for (size_t i = 0; i < shaders_.size(); i++) { glDetachShader(program_, shaders_[i]); glDeleteShader(shaders_[i]); } shaders_.clear(); return true; } GLuint GLSLProgram::getId() const { return program_; } const GLint GLSLProgram::getUniformLocation(const std::string& name) { const auto iter = uniformLocations_.find(name); if (iter == end(uniformLocations_)) { const GLint location = glGetUniformLocation(program_, name.c_str()); uniformLocations_[name] = location; } return uniformLocations_[name]; } bool GLSLProgram::getSubroutineIndex(const std::string& name, GLuint& uniform) { // TODO hardcoded to fragment shaders uniform = glGetSubroutineIndex(program_, GL_FRAGMENT_SHADER, name.c_str()); return uniform != GL_INVALID_INDEX; } bool GLSLProgram::setUniform(const std::string& name, const glm::mat4& uniform) { const GLint location = getUniformLocation(name); if (location == -1) { return false; } glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniform)); return true; } bool GLSLProgram::setUniform(const std::string& name, const glm::mat3& uniform) { const GLint location = getUniformLocation(name); if (location == -1) { return false; } glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(uniform)); return true; } bool GLSLProgram::setUniform(const std::string& name, const glm::vec4& uniform) { const GLint location = getUniformLocation(name); if (location == -1) { return false; } glUniform4fv(location, 1, glm::value_ptr(uniform)); return true; } bool GLSLProgram::setUniform(const std::string& name, const glm::vec3& uniform) { const GLint location = getUniformLocation(name); if (location == -1) { return false; } glUniform3fv(location, 1, glm::value_ptr(uniform)); return true; } bool GLSLProgram::setUniformFloat(const std::string& name, const float uniform) { const GLint location = getUniformLocation(name); if (location == -1) { return false; } glUniform1f(location, uniform); return true; } bool GLSLProgram::setUniformInt(const std::string& name, const GLuint uniform) { const GLint location = getUniformLocation(name); if (location == -1) { return false; } glUniform1i(location, uniform); return true; }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RENDER_TYPES_H_BEEN_INCLUDED #define HAS_RENDER_TYPES_H_BEEN_INCLUDED #include <glm/glm.hpp> using glm::vec4; using glm::vec3; // ---------------------------------------------------------------------------- enum RenderShape { RenderShape_Cube, RenderShape_Sphere, RenderShape_Line, RenderShape_SIZE, // None is placed after size to prevent it being picked as a valid value RenderShape_None, }; // ---------------------------------------------------------------------------- struct MeshVertex { MeshVertex() { } MeshVertex(const glm::vec4& pos, const glm::vec4& n, const glm::vec4& c) : xyz(pos) , normal(n) , colour(c) { } glm::vec4 xyz, normal, colour; }; // ---------------------------------------------------------------------------- struct MeshTriangle { MeshTriangle() { // indices_[0] = indices_[1] = indices_[2] = -1; indices_[0] = indices_[1] = indices_[2] = 0; } MeshTriangle(const int i0, const int i1, const int i2) { indices_[0] = i0; indices_[1] = i1; indices_[2] = i2; } int indices_[3]; }; // ---------------------------------------------------------------------------- #ifdef LEVEN const int MAX_MESH_VERTICES = 14 * 1024; #else const int MAX_MESH_VERTICES = 1 << 23; // i.e. 8 million #endif const int MAX_MESH_TRIANGLES = MAX_MESH_VERTICES * 2; class MeshBuffer { public: MeshBuffer() : numVertices(0) , numTriangles(0) , tag(nullptr) { } static void initialiseVertexArray(); const char* tag; MeshVertex vertices[MAX_MESH_VERTICES]; int numVertices; MeshTriangle triangles[MAX_MESH_TRIANGLES]; int numTriangles; }; // ---------------------------------------------------------------------------- struct ActorVertex { glm::vec4 pos; }; struct ActorMeshBuffer { static void initialiseVertexArray(); ActorVertex* vertices = nullptr; int numVertices = 0; int* indices = nullptr; int numIndices = 0; }; // ---------------------------------------------------------------------------- #endif // HAS_RENDER_TYPES_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "render_mesh.h" #include "render_local.h" #include "pool_allocator.h" #include <mutex> #include <unordered_set> #include <Remotery.h> const int MAX_RENDER_MESH = 8 * 1024; IndexPoolAllocator g_renderMeshAlloc; RenderMesh* g_renderMeshBuffer = nullptr; std::unordered_set<RenderMesh*> g_activeMeshes; std::mutex g_renderMeshMutex; const int MAX_MESH_BUFFERS = 2 * 1024; PoolAllocator<MeshBuffer> g_meshBufferAlloc; std::mutex g_meshBufferMutex; // ---------------------------------------------------------------------------- void InitialiseRenderMesh() { g_renderMeshAlloc.initialise(MAX_RENDER_MESH); g_renderMeshBuffer = new RenderMesh[MAX_RENDER_MESH]; g_activeMeshes.reserve(MAX_RENDER_MESH); g_meshBufferAlloc.initialise(MAX_MESH_BUFFERS); } // ---------------------------------------------------------------------------- void DestroyRenderMesh() { g_meshBufferAlloc.clear(); for (RenderMesh* mesh: g_activeMeshes) { mesh->destroy(); } g_activeMeshes.clear(); delete[] g_renderMeshBuffer; g_renderMeshBuffer = nullptr; g_renderMeshAlloc.clear(); } // ---------------------------------------------------------------------------- MeshBuffer* Render_AllocMeshBuffer(const char* const tag) { std::lock_guard<std::mutex> lock(g_meshBufferMutex); MeshBuffer* b = g_meshBufferAlloc.alloc(); if (!b) { printf("Error! Could not alloc mesh buffer\n"); return nullptr; } b->tag = tag; return b; } // ---------------------------------------------------------------------------- void Render_FreeMeshBuffer(MeshBuffer* buffer) { std::lock_guard<std::mutex> lock(g_meshBufferMutex); g_meshBufferAlloc.free(buffer); } // ---------------------------------------------------------------------------- RenderMesh* AllocRenderMesh() { RenderMesh* mesh = nullptr; std::lock_guard<std::mutex> lock(g_renderMeshMutex); // printf("Alloc mesh (%d alloc'd)\n", g_renderMeshAlloc.size()); const int index = g_renderMeshAlloc.alloc(); if (index != -1) { mesh = &g_renderMeshBuffer[index]; LVN_ASSERT(g_activeMeshes.find(mesh) == end(g_activeMeshes)); g_activeMeshes.insert(mesh); } return mesh; } // ---------------------------------------------------------------------------- static bool InitialiseMesh( RenderMesh* mesh, void (*initVertexArrayFn)(), const u32 vertexSize, MeshBuffer* buffer) { rmt_ScopedCPUSample(InitMesh); // TODO setPosition broken since the vertices are specified with absolute/world coords! // mesh->setPosition(position); mesh->uploadData(MeshBuffer::initialiseVertexArray, sizeof(MeshVertex), buffer->numVertices, buffer->vertices, buffer->numTriangles * 3, buffer->triangles); Render_FreeMeshBuffer(buffer); return true; } // ---------------------------------------------------------------------------- RenderMesh* Render_AllocRenderMesh(const char* const tag, MeshBuffer* buffer, const glm::vec3& position) { if (!buffer || buffer->numTriangles == 0) { return nullptr; } LVN_ASSERT(buffer->numTriangles > 0); LVN_ASSERT(buffer->numVertices > 0); RenderMesh* mesh = AllocRenderMesh(); if (mesh) { PushRenderCommand( std::bind(InitialiseMesh, mesh, MeshBuffer::initialiseVertexArray, sizeof(MeshVertex), buffer)); } else { Render_FreeMeshBuffer(buffer); printf("Error: unable to allocate render mesh [tag='%s']\n", tag); } return mesh; } // ---------------------------------------------------------------------------- RenderMesh* Render_AllocRenderMesh(const char* const tag, ActorMeshBuffer* buffer) { if (!buffer || buffer->numIndices == 0) { return nullptr; } LVN_ASSERT(buffer->numIndices > 0); LVN_ASSERT(buffer->numVertices > 0); RenderMesh* mesh = AllocRenderMesh(); if (mesh) { PushRenderCommand([=]() { mesh->uploadData(ActorMeshBuffer::initialiseVertexArray, sizeof(ActorVertex), buffer->numVertices, buffer->vertices, buffer->numIndices, buffer->indices); Render_ReleaseActorMeshBuffer(buffer); return true; }); } else { Render_ReleaseActorMeshBuffer(buffer); printf("Error: unable to allocate render mesh [tag='%s']\n", tag); } return mesh; } // ---------------------------------------------------------------------------- void Render_FreeRenderMesh(RenderMesh** mesh) { const auto ptrOffset = *mesh - &g_renderMeshBuffer[0]; LVN_ASSERT(ptrOffset >= 0 && ptrOffset < MAX_RENDER_MESH); { // TODO maybe a bit dodgy on x64? int index = ptrOffset & 0xffffffff; std::lock_guard<std::mutex> lock(g_renderMeshMutex); g_renderMeshAlloc.free(&index); g_activeMeshes.erase(*mesh); } *mesh = nullptr; } // ---------------------------------------------------------------------------- void MeshBuffer::initialiseVertexArray() { rmt_ScopedCPUSample(InitVertexAttrib); // xyz glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(MeshVertex), 0); // normal glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(MeshVertex), (void*)(sizeof(vec4) * 1)); // colour glEnableVertexAttribArray(2); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(MeshVertex), (void*)(sizeof(vec4) * 2)); } // ---------------------------------------------------------------------------- void ActorMeshBuffer::initialiseVertexArray() { rmt_ScopedCPUSample(InitVertexAttrib_Actor); // xyz glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(ActorVertex), 0); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RANDOM_H_BEEN_INCLUDED #define HAS_RANDOM_H_BEEN_INCLUDED #include <glm/glm.hpp> s32 RandomS32(const s32 min, const s32 max); float RandomF32(const float min, const float max); glm::vec3 RandomColour(); #endif // HAS_RANDOM_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RENDER_SHAPES_H_BEEN_INCLUDED #define HAS_RENDER_SHAPES_H_BEEN_INCLUDED #include "render_types.h" #include <vector> #include <glm/glm.hpp> using glm::vec4; using glm::vec3; // ---------------------------------------------------------------------------- void GetSphereData( const vec3& origin, const float radius, vec4* vertexDataBuffer, u16* indexDataBuffer, u32* vertexBufferSize, u32* indexBufferSize); void GetCubeData( const vec3& min, const vec3& max, vec4* vertexDataBuffer, u16* indexDataBuffer, u32* vertexBufferSize, u32* indexBufferSize); void GetLineData( const vec3& start, const vec3& end, vec4* vertexDataBuffer, u16* indexDataBuffer, u32* vertexBufferSize, u32* indexBufferSize); void GetShapeData(const RenderShape shape, std::vector<vec4>& vertexData, std::vector<int>& indices); // ---------------------------------------------------------------------------- void GetCubeDataSizes(int* numVertices, int* numIndices); void GetSphereDataSizes(int* numVertices, int* numIndices); void GetLineDataSizes(int* numVertices, int* numIndices); // ---------------------------------------------------------------------------- #endif // HAS_RENDER_SHAPES_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "compute.h" #include "compute_local.h" #include "compute_cuckoo.h" #include "compute_program.h" #include "volume_constants.h" #include "volume_materials.h" #include "timer.h" #include "file_utils.h" #include "glsl_svd.h" #include "volume.h" #include "primes.h" #include "lrucache.h" #include <Remotery.h> #include "sdl_wrapper.h" #include <functional> #include <sstream> #include <unordered_map> #include <array> #include <random> #include <memory> #include <glm/gtx/integer.hpp> // ---------------------------------------------------------------------------- ComputeProgram g_utilProgram; // ---------------------------------------------------------------------------- int CreateBuffer( cl_int permissions, u32 bufferSize, void* hostDataPtr, cl::Buffer& buffer) { cl_int error = CL_SUCCESS; auto ctx = GetComputeContext(); if (hostDataPtr) { permissions |= CL_MEM_COPY_HOST_PTR; } buffer = cl::Buffer(ctx->context, permissions, bufferSize, hostDataPtr, &error); if (buffer() == 0) { printf("clCreateBuffer returned null pointer: size=%d error=%d\n", bufferSize, error); } return error; } // ---------------------------------------------------------------------------- int FillBufferInt( cl::CommandQueue& queue, cl::Buffer& buffer, const u32 count, const cl_int value) { cl::Kernel k_FillBuffer(g_utilProgram.get(), "FillBufferInt"); int index = 0; CL_CALL(k_FillBuffer.setArg(index++, buffer)); CL_CALL(k_FillBuffer.setArg(index++, value)); CL_CALL(queue.enqueueNDRangeKernel(k_FillBuffer, 0, count)); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int FillBufferLong( cl::CommandQueue& queue, cl::Buffer& buffer, const u32 count, const cl_long value) { cl::Kernel k_FillBuffer(g_utilProgram.get(), "FillBufferLong"); int index = 0; CL_CALL(k_FillBuffer.setArg(index++, buffer)); CL_CALL(k_FillBuffer.setArg(index++, value)); CL_CALL(queue.enqueueNDRangeKernel(k_FillBuffer, 0, count)); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int InitialiseContext(ComputeContext* ctx) { if (ctx->context()) { // already initialised return CL_SUCCESS; } std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if (platforms.empty()) { printf("OpenCL: no platforms\n"); return LVN_CL_ERROR; } #ifdef USE_OPENGL_INTEROP cl_context_properties properties[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(), CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0 }; clGetGLContextInfoKHR_fn clGetGLContextInfoKHR = (clGetGLContextInfoKHR_fn)clGetExtensionFunctionAddressForPlatform(platforms[0](), "clGetGLContextInfoKHR"); cl_device_id device_ids[32]; size_t size = 0; CL_CALL(clGetGLContextInfoKHR(properties, CL_DEVICES_FOR_GL_CONTEXT_KHR, sizeof(cl_device_id) * 32, &device_ids[0], &size)); const u32 countDevices = size / sizeof(cl_device_id); printf("Found %d devices capable of OpenGL/OpenCL interop\n", countDevices); std::vector<cl::Device> devices; for (u32 i = 0; i < countDevices; i++) { devices.push_back(cl::Device(device_ids[i])); } ctx->context = cl::Context(devices, properties); ctx->device = devices[0]; #else cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0 }; ctx->context = cl::Context(CL_DEVICE_TYPE_GPU, properties); auto devices = ctx->context.getInfo<CL_CONTEXT_DEVICES>(); printf("OpenCL found %d devices\n", devices.size()); if (devices.empty()) { return LVN_CL_ERROR; } ctx->device = devices[0]; #endif cl_int err = 0; ctx->queue = cl::CommandQueue(ctx->context, ctx->device, 0, &err); if (err < 0) { printf("Couldn't create queue\n"); return err; } return CL_SUCCESS; } // ---------------------------------------------------------------------------- //#define CONTEXT_PER_THREAD #ifdef CONTEXT_PER_THREAD __declspec(thread) ComputeContext* context; #endif ComputeContext* GetComputeContext() { static std::unique_ptr<ComputeContext> computeContext = nullptr; if (computeContext == nullptr) { computeContext.reset(new ComputeContext); InitialiseContext(computeContext.get()); } #ifdef CONTEXT_PER_THREAD if (!context) { context = new ComputeContext; context->context = computeContext->context; context->device = computeContext->device; context->queue = cl::CommandQueue(computeContext->context, computeContext->device, 0); } return context; #else return computeContext.get(); #endif } // ---------------------------------------------------------------------------- int Compute_Initialise(const int noiseSeed, const unsigned int defaultMaterial, const int numCSGBrushes) { auto ctx = GetComputeContext(); printf("OpenCL device: %s\n", ctx->device.getInfo<CL_DEVICE_NAME>().c_str()); printf("OpenCL device version: %s\n", ctx->device.getInfo<CL_DEVICE_VERSION>().c_str()); printf(" Global Memory Size: %d\n", ctx->device.getInfo<CL_DEVICE_GLOBAL_MEM_CACHE_SIZE>()); printf(" Max Memory Alloc Size: %d\n", ctx->device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>()); printf(" Max Work Group Size: %d\n", ctx->device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>()); printf(" Max Work Item Dimensions: %d\n", ctx->device.getInfo<CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS>()); printf(" Min Data Type Align Size: %d\n", ctx->device.getInfo<CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE>()); printf(" Memory Base Address Align: %d\n", ctx->device.getInfo<CL_DEVICE_MEM_BASE_ADDR_ALIGN>()); printf(" Extensions: %s\n", ctx->device.getInfo<CL_DEVICE_EXTENSIONS>().c_str()); std::stringstream buildOptions; // buildOptions << "-cl-nv-verbose "; buildOptions << "-cl-denorms-are-zero "; buildOptions << "-cl-finite-math-only "; buildOptions << "-cl-no-signed-zeros "; buildOptions << "-cl-fast-relaxed-math "; buildOptions << "-Werror "; buildOptions << "-I. "; buildOptions << "-DCUCKOO_EMPTY_VALUE=" << CUCKOO_EMPTY_VALUE << " "; buildOptions << "-DCUCKOO_STASH_HASH_INDEX=" << CUCKOO_STASH_HASH_INDEX << " "; buildOptions << "-DCUCKOO_HASH_FN_COUNT=" << CUCKOO_HASH_FN_COUNT << " "; buildOptions << "-DCUCKOO_STASH_SIZE=" << CUCKOO_STASH_SIZE << " "; buildOptions << "-DCUCKOO_MAX_ITERATIONS=" << CUCKOO_MAX_ITERATIONS << " "; buildOptions << "-DNUM_CSG_BRUSHES=" << numCSGBrushes << " "; g_utilProgram.initialise("cl/compact.cl", buildOptions.str()); g_utilProgram.addHeader("cl/duplicate.cl"); g_utilProgram.addHeader("cl/scan.cl"); g_utilProgram.addHeader("cl/fill_buffer.cl"); CL_CALL(g_utilProgram.build()); ctx->defaultMaterial = defaultMaterial; CL_CALL(Compute_InitialiseCuckoo()); CL_CALL(Compute_SetNoiseSeed(noiseSeed)); return CL_SUCCESS; } // ---------------------------------------------------------------------------- int Compute_Shutdown() { return CL_SUCCESS; } // ---------------------------------------------------------------------------- MeshGenerationContext* Compute_CreateMeshGenContext(const int voxelsPerChunk) { MeshGenerationContext* meshGen = new MeshGenerationContext; meshGen->voxelsPerChunk = voxelsPerChunk; meshGen->hermiteIndexSize = meshGen->voxelsPerChunk + 1; meshGen->fieldSize = meshGen->hermiteIndexSize + 1; meshGen->indexShift = glm::log2(voxelsPerChunk) + 1; meshGen->indexMask = (1 << meshGen->indexShift) - 1; const int fieldBufferSize = meshGen->fieldSize * meshGen->fieldSize * meshGen->fieldSize; const int maxTerrainHeight = 900.f; std::stringstream buildOptions; // buildOptions << "-cl-nv-verbose "; buildOptions << "-cl-fast-relaxed-math "; buildOptions << "-Werror "; buildOptions << "-DVOXELS_PER_CHUNK=" << meshGen->voxelsPerChunk << " "; buildOptions << "-DLEAF_SIZE_SCALE=" << LEAF_SIZE_SCALE << " "; buildOptions << "-DFIELD_DIM=" << meshGen->fieldSize << " "; buildOptions << "-DHERMITE_INDEX_SIZE=" << meshGen->hermiteIndexSize << " "; buildOptions << "-DVOXEL_INDEX_SHIFT=" << meshGen->indexShift << " "; buildOptions << "-DVOXEL_INDEX_MASK=" << meshGen->indexMask << " "; buildOptions << "-DMAX_TERRAIN_HEIGHT=" << maxTerrainHeight << " "; buildOptions << "-DMATERIAL_AIR=" << MATERIAL_AIR << " "; buildOptions << "-DMATERIAL_NONE=" << MATERIAL_NONE << " "; buildOptions << "-DFIND_EDGE_INFO_STEPS=" << 16 << " "; buildOptions << "-DFIND_EDGE_INFO_INCREMENT=" << (1.f/16.f) << " "; buildOptions << "-DMAX_OCTREE_DEPTH=" << glm::log2(meshGen->voxelsPerChunk) << " "; buildOptions << "-DCUCKOO_EMPTY_VALUE=" << CUCKOO_EMPTY_VALUE << " "; buildOptions << "-DCUCKOO_STASH_HASH_INDEX=" << CUCKOO_STASH_HASH_INDEX << " "; buildOptions << "-DCUCKOO_HASH_FN_COUNT=" << CUCKOO_HASH_FN_COUNT << " "; buildOptions << "-DCUCKOO_STASH_SIZE=" << CUCKOO_STASH_SIZE << " "; buildOptions << "-DCUCKOO_MAX_ITERATIONS=" << CUCKOO_MAX_ITERATIONS << " "; buildOptions << "-DFIELD_BUFFER_SIZE=" << fieldBufferSize << " "; buildOptions << "-DNUM_CSG_BRUSHES=" << 2 << " "; meshGen->densityFieldProgram.initialise("cl/density_field.cl", buildOptions.str()); meshGen->densityFieldProgram.addHeader("cl/shared_constants.cl"); meshGen->densityFieldProgram.addHeader("cl/simplex.cl"); meshGen->densityFieldProgram.addHeader("cl/noise.cl"); if (int error = meshGen->densityFieldProgram.build()) { printf("Error: unable to build density field program for voxelsPerChunk=%d\n '%s' (%d)\n", voxelsPerChunk, GetCLErrorString(error), error); return nullptr; } meshGen->octreeProgram.initialise("cl/octree.cl", buildOptions.str()); meshGen->octreeProgram.addHeader("cl/shared_constants.cl"); meshGen->octreeProgram.addHeader("cl/cuckoo.cl"); meshGen->octreeProgram.addHeader("cl/qef.cl"); if (int error = meshGen->octreeProgram.build()) { printf("Error: unable to build octree program for voxelsPerChunk=%d\n '%s' (%d)\n", voxelsPerChunk, GetCLErrorString(error), error); return nullptr; } meshGen->csgProgram.initialise("cl/apply_csg_operation.cl", buildOptions.str()); meshGen->csgProgram.addHeader("cl/shared_constants.cl"); if (int error = meshGen->csgProgram.build()) { printf("Error: unable to build CSG program for voxelsPerChunk=%d\n '%s' (%d)\n", voxelsPerChunk, GetCLErrorString(error), error); return nullptr; } return meshGen; } // ---------------------------------------------------------------------------- int Compute_MeshGenVoxelsPerChunk(MeshGenerationContext* meshGen) { if (meshGen) { return meshGen->voxelsPerChunk; } return 0; } // ---------------------------------------------------------------------------- int PickScanBlockSize(const int count) { if(count == 0) { return 0; } else if(count <= 1) { return 1; } else if(count <= 2) { return 2; } else if(count <= 4) { return 4; } else if(count <= 8) { return 8; } else if(count <= 16) { return 16; } else if(count <= 32) { return 32; } else if(count <= 64) { return 64; } else if(count <= 128) { return 128; } else { return 256; } } // ---------------------------------------------------------------------------- int Scan(cl::CommandQueue& queue, cl::Buffer& data, cl::Buffer& scanData, const int count, const bool exclusive) { const u32 blockSize = PickScanBlockSize(count); u32 blockCount = count / blockSize; if (blockCount * blockSize < count) { blockCount++; } auto ctx = GetComputeContext(); cl::Buffer blockSums(ctx->context, CL_MEM_READ_WRITE, sizeof(int) * blockCount); CL_CALL(FillBufferInt(ctx->queue, blockSums, blockCount, 0)); const char* scanKernelName = exclusive ? "ExclusiveLocalScan" : "InclusiveLocalScan"; cl::Kernel localScanKernel(g_utilProgram.get(), scanKernelName); CL_CALL(localScanKernel.setArg(0, blockSums)); CL_CALL(localScanKernel.setArg(1, blockSize * sizeof(int), 0)); CL_CALL(localScanKernel.setArg(2, blockSize)); CL_CALL(localScanKernel.setArg(3, count)); CL_CALL(localScanKernel.setArg(4, data)); CL_CALL(localScanKernel.setArg(5, scanData)); CL_CALL(ctx->queue.enqueueNDRangeKernel(localScanKernel, cl::NullRange, blockCount * blockSize, blockSize)); if (blockCount > 1) { Scan(ctx->queue, blockSums, blockSums, blockCount, false); cl::Kernel writeOutputKernel(g_utilProgram.get(), "WriteScannedOutput"); writeOutputKernel.setArg(0, scanData); writeOutputKernel.setArg(1, blockSums); writeOutputKernel.setArg(2, count); CL_CALL(ctx->queue.enqueueNDRangeKernel(writeOutputKernel, blockSize, blockCount * blockSize, blockSize)); } return CL_SUCCESS; } // ---------------------------------------------------------------------------- int ExclusiveScan(cl::CommandQueue& queue, cl::Buffer& data, cl::Buffer& scan, const u32 count) { auto ctx = GetComputeContext(); CL_CALL(Scan(ctx->queue, data, scan, count, true)); int lastValue = 0; int lastScanValue = 0; CL_CALL(ctx->queue.enqueueReadBuffer(data, CL_FALSE, (count - 1) * sizeof(int), sizeof(int), &lastValue)); CL_CALL(ctx->queue.enqueueReadBuffer(scan, CL_TRUE, (count - 1) * sizeof(int), sizeof(int), &lastScanValue)); return lastValue + lastScanValue; } // ---------------------------------------------------------------------------- int CompactArray_Long( cl::CommandQueue& queue, cl::Buffer& valuesArray, cl::Buffer& validity, const u32 count, cl::Buffer& compactArray) { auto ctx = GetComputeContext(); cl::Buffer scan(ctx->context, CL_MEM_READ_WRITE, sizeof(cl_int) * count); const int compactCount = ExclusiveScan(ctx->queue, validity, scan, count); if (compactCount > 0) { compactArray = cl::Buffer(ctx->context, CL_MEM_READ_WRITE, sizeof(cl_long) * compactCount); cl::Kernel k(g_utilProgram.get(), "CompactArray_Long"); k.setArg(0, validity); k.setArg(1, valuesArray); k.setArg(2, scan); k.setArg(3, compactArray); CL_CALL(ctx->queue.enqueueNDRangeKernel(k, cl::NullRange, count, cl::NullRange)); } return compactCount; } // ---------------------------------------------------------------------------- int CompactIndexArray(cl::CommandQueue& queue, cl::Buffer& indexArray, cl::Buffer& validity, const int count, cl::Buffer& compactArray) { auto ctx = GetComputeContext(); cl::Buffer scan(ctx->context, CL_MEM_READ_WRITE, count * sizeof(int)); const int compactCount = ExclusiveScan(ctx->queue, validity, scan, count); if (compactCount > 0) { compactArray = cl::Buffer(ctx->context, CL_MEM_READ_WRITE, compactCount * sizeof(int)); cl::Kernel k(g_utilProgram.get(), "CompactIndexArray"); k.setArg(0, validity); k.setArg(1, indexArray); k.setArg(2, scan); k.setArg(3, compactArray); CL_CALL(ctx->queue.enqueueNDRangeKernel(k, cl::NullRange, count, cl::NullRange)); } return compactCount; } // ---------------------------------------------------------------------------- cl::Buffer RemoveDuplicates(cl::CommandQueue& queue, cl::Buffer& inputData, const int inputCount, unsigned int* resultCount) { rmt_ScopedCPUSample(RemoveDuplicates); auto ctx = GetComputeContext(); cl::Buffer result(ctx->context, CL_MEM_READ_WRITE, inputCount * sizeof(int)); FillBufferInt(ctx->queue, result, inputCount, -1); cl::Buffer sequence(ctx->context, CL_MEM_READ_WRITE, inputCount * sizeof(int)); ctx->queue.enqueueCopyBuffer(inputData, sequence, 0, 0, inputCount * sizeof(int)); Timer timer; timer.start(); timer.disable(); // printf("RemoveDuplicates: inputCount=%d\n", inputCount); int prime = FindNextPrime(inputCount * 2); cl::Buffer table(ctx->context, CL_MEM_READ_WRITE, prime * sizeof(int)); cl::Buffer winnersValid(ctx->context, CL_MEM_READ_WRITE, prime * sizeof(int)); cl::Buffer winners(ctx->context, CL_MEM_READ_WRITE, prime * sizeof(int)); cl::Buffer losers(ctx->context, CL_MEM_READ_WRITE, prime * sizeof(int)); cl::Buffer losersValid(ctx->context, CL_MEM_READ_WRITE, prime * sizeof(int)); cl::Kernel mapSequenceKernel(g_utilProgram.get(), "MapSequenceIndices"); cl::Kernel extractWinnersKernel(g_utilProgram.get(), "ExtractWinners"); cl::Kernel mapValuesKernel(g_utilProgram.get(), "MapSequenceValues"); cl::Kernel extractLosersKernel(g_utilProgram.get(), "ExtractLosers"); int resultsSize = 0; int numItems = inputCount; int xorValue = 0xdecb7a37; while (numItems > 0) { // const int prime = FindNextPrime(numItems * 2); // prime = FindNextPrime(numItems * 2); // printf(" prime=%d\n", prime); // printf("*** xor=%x\n", xorValue); // printf(" edges remaining=%d\n", numItems); FillBufferInt(ctx->queue, table, prime, -1); mapSequenceKernel.setArg(0, sequence); mapSequenceKernel.setArg(1, table); mapSequenceKernel.setArg(2, prime); mapSequenceKernel.setArg(3, xorValue); ctx->queue.enqueueNDRangeKernel(mapSequenceKernel, cl::NullRange, numItems, cl::NullRange); extractWinnersKernel.setArg(0, table); extractWinnersKernel.setArg(1, sequence); extractWinnersKernel.setArg(2, winnersValid); extractWinnersKernel.setArg(3, winners); ctx->queue.enqueueNDRangeKernel(extractWinnersKernel, cl::NullRange, prime, cl::NullRange); cl::Buffer compactWinners; const int numWinners = CompactIndexArray(ctx->queue, winners, winnersValid, prime, compactWinners); // printf(" %d winners\n", numWinners); (ctx->queue.enqueueCopyBuffer(compactWinners, result, 0, resultsSize * sizeof(int), numWinners * sizeof(int))); resultsSize += numWinners; mapValuesKernel.setArg(0, compactWinners); mapValuesKernel.setArg(1, table); mapValuesKernel.setArg(2, prime); mapValuesKernel.setArg(3, xorValue); (ctx->queue.enqueueNDRangeKernel(mapValuesKernel, cl::NullRange, numWinners, cl::NullRange)); extractLosersKernel.setArg(0, sequence); extractLosersKernel.setArg(1, table); extractLosersKernel.setArg(2, losersValid); extractLosersKernel.setArg(3, losers); extractLosersKernel.setArg(4, prime); extractLosersKernel.setArg(5, xorValue); (ctx->queue.enqueueNDRangeKernel(extractLosersKernel, cl::NullRange, numItems, cl::NullRange)); cl::Buffer compactLosers; const int numLosers = CompactIndexArray(ctx->queue, losers, losersValid, numItems, compactLosers); // printf(" %d losers\n", numLosers); if (numLosers == 0) { break; } numItems = numLosers; sequence = compactLosers; xorValue = (xorValue * prime) & -1; xorValue ^= 0xe93fbc48; } // printf(" %d ms\n", timer.elapsedMilli()); *resultCount = resultsSize; return std::move(result); } // ---------------------------------------------------------------------------- cl::size_t<3> Size3(const u32 size) { cl::size_t<3> s; s[0] = size; s[1] = size; s[2] = size; return s; } // ---------------------------------------------------------------------------- cl::size_t<3> Size3(const u32 x, const u32 y, const u32 z) { cl::size_t<3> s; s[0] = x; s[1] = y; s[2] = z; return s; } // ---------------------------------------------------------------------------- cl_int4 LeafScaleVec(const glm::ivec3& v) { cl_int4 s; s.x = v.x / LEAF_SIZE_SCALE; s.y = v.y / LEAF_SIZE_SCALE; s.z = v.z / LEAF_SIZE_SCALE; s.w = 0; return s; } // ---------------------------------------------------------------------------- cl_float4 LeafScaleVec(const glm::vec3& v) { cl_float4 s; s.x = v.x / LEAF_SIZE_SCALE; s.y = v.y / LEAF_SIZE_SCALE; s.z = v.z / LEAF_SIZE_SCALE; s.w = 0; return s; } // ---------------------------------------------------------------------------- cl_float4 LeafScaleVec(const glm::vec4& v) { cl_float4 s; s.x = v.x / LEAF_SIZE_SCALE; s.y = v.y / LEAF_SIZE_SCALE; s.z = v.z / LEAF_SIZE_SCALE; s.w = 0; return s; } // ---------------------------------------------------------------------------- Compute_MeshGenContext* Compute_MeshGenContext::create(const int voxelsPerChunk) { Compute_MeshGenContext* ctx = new Compute_MeshGenContext; ctx->privateCtx_ = Compute_CreateMeshGenContext(voxelsPerChunk); return ctx; } int Compute_MeshGenContext::voxelsPerChunk() const { return privateCtx_->voxelsPerChunk; } int Compute_MeshGenContext::applyCSGOperations( const std::vector<CSGOperationInfo>& opInfo, const glm::ivec3& clipmapNodeMin, const int clipmapNodeSize) { return Compute_ApplyCSGOperations(privateCtx_, opInfo, clipmapNodeMin, clipmapNodeSize); } int Compute_MeshGenContext::freeChunkOctree( const glm::ivec3& min, const int size) { return Compute_FreeChunkOctree(privateCtx_, min, size); } int Compute_MeshGenContext::isChunkEmpty( const glm::ivec3& min, const int size, bool& isEmpty) { return Compute_ChunkIsEmpty(privateCtx_, min, size, isEmpty); } int Compute_MeshGenContext::generateChunkMesh( const glm::ivec3& min, const int clipmapNodeSize, MeshBuffer* meshBuffer, std::vector<SeamNodeInfo>& seamNodeBuffer) { return Compute_GenerateChunkMesh(privateCtx_, min, clipmapNodeSize, meshBuffer, seamNodeBuffer); } // ---------------------------------------------------------------------------- const char* GetCLErrorString(int error) { switch (error) { case CL_SUCCESS: return "CL_SUCCESS"; case CL_DEVICE_NOT_FOUND: return "CL_DEVICE_NOT_FOUND"; case CL_DEVICE_NOT_AVAILABLE: return "CL_DEVICE_NOT_AVAILABLE"; case CL_COMPILER_NOT_AVAILABLE: return "CL_COMPILER_NOT_AVAILABLE"; case CL_MEM_OBJECT_ALLOCATION_FAILURE: return "CL_MEM_OBJECT_ALLOCATION_FAILURE"; case CL_OUT_OF_RESOURCES: return "CL_OUT_OF_RESOURCES"; case CL_OUT_OF_HOST_MEMORY: return "CL_OUT_OF_HOST_MEMORY"; case CL_PROFILING_INFO_NOT_AVAILABLE: return "CL_PROFILING_INFO_NOT_AVAILABLE"; case CL_MEM_COPY_OVERLAP: return "CL_MEM_COPY_OVERLAP"; case CL_IMAGE_FORMAT_MISMATCH: return "CL_IMAGE_FORMAT_MISMATCH"; case CL_IMAGE_FORMAT_NOT_SUPPORTED: return "CL_IMAGE_FORMAT_NOT_SUPPORTED"; case CL_BUILD_PROGRAM_FAILURE: return "CL_BUILD_PROGRAM_FAILURE"; case CL_MAP_FAILURE: return "CL_MAP_FAILURE"; case CL_INVALID_VALUE: return "CL_INVALID_VALUE"; case CL_INVALID_DEVICE_TYPE: return "CL_INVALID_DEVICE_TYPE"; case CL_INVALID_PLATFORM: return "CL_INVALID_PLATFORM"; case CL_INVALID_DEVICE: return "CL_INVALID_DEVICE"; case CL_INVALID_CONTEXT: return "CL_INVALID_CONTEXT"; case CL_INVALID_QUEUE_PROPERTIES: return "CL_INVALID_QUEUE_PROPERTIES"; case CL_INVALID_COMMAND_QUEUE: return "CL_INVALID_COMMAND_QUEUE"; case CL_INVALID_HOST_PTR: return "CL_INVALID_HOST_PTR"; case CL_INVALID_MEM_OBJECT: return "CL_INVALID_MEM_OBJECT"; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR"; case CL_INVALID_IMAGE_SIZE: return "CL_INVALID_IMAGE_SIZE"; case CL_INVALID_SAMPLER: return "CL_INVALID_SAMPLER"; case CL_INVALID_BINARY: return "CL_INVALID_BINARY"; case CL_INVALID_BUILD_OPTIONS: return "CL_INVALID_BUILD_OPTIONS"; case CL_INVALID_PROGRAM: return "CL_INVALID_PROGRAM"; case CL_INVALID_PROGRAM_EXECUTABLE: return "CL_INVALID_PROGRAM_EXECUTABLE"; case CL_INVALID_KERNEL_NAME: return "CL_INVALID_KERNEL_NAME"; case CL_INVALID_KERNEL_DEFINITION: return "CL_INVALID_KERNEL_DEFINITION"; case CL_INVALID_KERNEL: return "CL_INVALID_KERNEL"; case CL_INVALID_ARG_INDEX: return "CL_INVALID_ARG_INDEX"; case CL_INVALID_ARG_VALUE: return "CL_INVALID_ARG_VALUE"; case CL_INVALID_ARG_SIZE: return "CL_INVALID_ARG_SIZE"; case CL_INVALID_KERNEL_ARGS: return "CL_INVALID_KERNEL_ARGS"; case CL_INVALID_WORK_DIMENSION: return "CL_INVALID_WORK_DIMENSION"; case CL_INVALID_WORK_GROUP_SIZE: return "CL_INVALID_WORK_GROUP_SIZE"; case CL_INVALID_WORK_ITEM_SIZE: return "CL_INVALID_WORK_ITEM_SIZE"; case CL_INVALID_GLOBAL_OFFSET: return "CL_INVALID_GLOBAL_OFFSET"; case CL_INVALID_EVENT_WAIT_LIST: return "CL_INVALID_EVENT_WAIT_LIST"; case CL_INVALID_EVENT: return "CL_INVALID_EVENT"; case CL_INVALID_OPERATION: return "CL_INVALID_OPERATION"; case CL_INVALID_GL_OBJECT: return "CL_INVALID_GL_OBJECT"; case CL_INVALID_BUFFER_SIZE: return "CL_INVALID_BUFFER_SIZE"; case CL_INVALID_MIP_LEVEL: return "CL_INVALID_MIP_LEVEL"; case CL_INVALID_GLOBAL_WORK_SIZE: return "CL_INVALID_GLOBAL_WORK_SIZE"; default: return "Unknown OpenCL error code!"; } }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
// ImGui SDL2 binding with OpenGL with the render stuff lifted from the GL3 sample // https://github.com/ocornut/imgui #include "imgui_handlers.h" // Data static double g_Time = 0.0f; static bool g_MousePressed[3] = { false, false, false }; static float g_MouseWheel = 0.0f; static GLuint g_FontTexture = 0; static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data) { // Backup GL state GLint last_program, last_texture, last_array_buffer, last_element_array_buffer, last_vertex_array; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) ImGuiIO& io = ImGui::GetIO(); float fb_height = io.DisplaySize.y * io.DisplayFramebufferScale.y; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Setup orthographic projection matrix const float ortho_projection[4][4] = { { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, {-1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(g_ShaderHandle); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(g_VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBindVertexArray(last_vertex_array); glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); } static const char* ImGui_ImplSdl_GetClipboardText() { return SDL_GetClipboardText(); } static void ImGui_ImplSdl_SetClipboardText(const char* text) { SDL_SetClipboardText(text); } bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event) { ImGuiIO& io = ImGui::GetIO(); switch (event->type) { case SDL_MOUSEWHEEL: { if (event->wheel.y > 0) g_MouseWheel = 1; if (event->wheel.y < 0) g_MouseWheel = -1; return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true; return true; } case SDL_TEXTINPUT: { ImGuiIO& io = ImGui::GetIO(); io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK; io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); return true; } } return false; } bool ImGui_ImplSdl_CreateDeviceObjects() { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar *vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; g_ShaderHandle = glCreateProgram(); g_VertHandle = glCreateShader(GL_VERTEX_SHADER); g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_VertHandle, 1, &vertex_shader, 0); glShaderSource(g_FragHandle, 1, &fragment_shader, 0); glCompileShader(g_VertHandle); glCompileShader(g_FragHandle); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); glGenVertexArrays(1, &g_VaoHandle); glBindVertexArray(g_VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_AttribLocationPosition); glEnableVertexAttribArray(g_AttribLocationUV); glEnableVertexAttribArray(g_AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); #undef OFFSETOF { ImGuiIO& io = ImGui::GetIO(); // Build texture atlas unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // Create OpenGL texture glGenTextures(1, &g_FontTexture); glBindTexture(GL_TEXTURE_2D, g_FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; // Cleanup (don't clear the input data if you want to append new fonts later) io.Fonts->ClearInputData(); io.Fonts->ClearTexData(); } // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); return true; } void ImGui_ImplSdl_InvalidateDeviceObjects() { if (g_FontTexture) { glDeleteTextures(1, &g_FontTexture); ImGui::GetIO().Fonts->TexID = 0; g_FontTexture = 0; } } bool ImGui_ImplSdl_Init(SDL_Window *window) { ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; io.KeyMap[ImGuiKey_A] = SDLK_a; io.KeyMap[ImGuiKey_C] = SDLK_c; io.KeyMap[ImGuiKey_V] = SDLK_v; io.KeyMap[ImGuiKey_X] = SDLK_x; io.KeyMap[ImGuiKey_Y] = SDLK_y; io.KeyMap[ImGuiKey_Z] = SDLK_z; io.RenderDrawListsFn = ImGui_ImplSdl_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer. io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText; #ifdef _WIN32 SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); io.ImeWindowHandle = wmInfo.info.win.window; #endif return true; } void ImGui_ImplSdl_Shutdown() { ImGui_ImplSdl_InvalidateDeviceObjects(); ImGui::Shutdown(); } void ImGui_ImplSdl_NewFrame(SDL_Window *window) { if (!g_FontTexture) ImGui_ImplSdl_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; SDL_GetWindowSize(window, &w, &h); io.DisplaySize = ImVec2((float)w, (float)h); // Setup time step Uint32 time = SDL_GetTicks(); double current_time = time / 1000.0; io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); g_Time = current_time; // Setup inputs // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) int mx, my; Uint32 mouseMask = SDL_GetMouseState(&mx, &my); if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) else io.MousePos = ImVec2(-1,-1); io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); // Start the frame ImGui::NewFrame(); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#define CATCH_CONFIG_MAIN #include <catch.hpp>
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "frustum.h" // ---------------------------------------------------------------------------- using namespace glm; // ---------------------------------------------------------------------------- Frustum BuildFrustum(const mat4& mvp) { Frustum frustum; frustum.p[0] = vec4(mvp[0][3] - mvp[0][0], mvp[1][3] - mvp[1][0], mvp[2][3] - mvp[2][0], mvp[3][3] - mvp[3][0]); frustum.p[1] = vec4(mvp[0][3] + mvp[0][0], mvp[1][3] + mvp[1][0], mvp[2][3] + mvp[2][0], mvp[3][3] + mvp[3][0]); frustum.p[2] = vec4(mvp[0][3] + mvp[0][1], mvp[1][3] + mvp[1][1], mvp[2][3] + mvp[2][1], mvp[3][3] + mvp[3][1]); frustum.p[3] = vec4(mvp[0][3] - mvp[0][1], mvp[1][3] - mvp[1][1], mvp[2][3] - mvp[2][1], mvp[3][3] - mvp[3][1]); frustum.p[4] = vec4(mvp[0][3] - mvp[0][2], mvp[1][3] - mvp[1][2], mvp[2][3] - mvp[2][2], mvp[3][3] - mvp[3][2]); frustum.p[5] = vec4(mvp[0][3] + mvp[0][2], mvp[1][3] + mvp[1][2], mvp[2][3] + mvp[2][2], mvp[3][3] + mvp[3][2]); for (int i = 0; i < 6; i++) { frustum.p[i] = normalize(frustum.p[i]); } return frustum; } // ---------------------------------------------------------------------------- bool AABBInsideFrustum(const AABB& aabb, const Frustum& frustum) { for (int i = 0; i < 6; i++) { const vec4& p = frustum.p[i]; int outside = 0; outside += dot(p, vec4(aabb.min.x, aabb.min.y, aabb.min.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.max.x, aabb.min.y, aabb.min.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.min.x, aabb.max.y, aabb.min.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.max.x, aabb.max.y, aabb.min.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.min.x, aabb.min.y, aabb.max.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.max.x, aabb.min.y, aabb.max.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.min.x, aabb.max.y, aabb.max.z, 1.f)) < 0.f ? 1 : 0; outside += dot(p, vec4(aabb.max.x, aabb.max.y, aabb.max.z, 1.f)) < 0.f ? 1 : 0; if (outside == 8) { // all points outside the frustum return false; } } return true; } // ----------------------------------------------------------------------------
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "camera.h" #include "physics.h" #include <memory> #include <glm/ext.hpp> using glm::vec3; using glm::vec4; using glm::mat4; struct FirstPersonCamera { void update(const vec3& speed, float rotateX, float rotateY) { rotateX_ += rotateX; rotateX_ = glm::clamp(rotateX_, -85.f, 85.f); rotateY_ += rotateY; const mat4 pitchMatrix = glm::rotate(mat4(1.f), rotateX_, vec3(1, 0, 0)); const mat4 yawMatrix = glm::rotate(mat4(1.f), rotateY_, vec3(0, 1, 0)); vec4 forward(0.f, 0.f, 1.f, 0.f); forward = pitchMatrix * forward; forward = yawMatrix * forward; forward_ = vec3(forward); vec4 right(1.f, 0.f, 0.f, 0.f); right = pitchMatrix * right; right = yawMatrix * right; right_ = vec3(right); vec4 up(0.f, 1.f, 0.f, 0.f); up = pitchMatrix * up; up = yawMatrix * up; up_ = vec3(up); position_ = Physics_GetPlayerPosition(); vec3 velocity; velocity += speed.z * forward_; velocity += speed.y * up_; velocity += speed.x * right_; Physics_SetPlayerVelocity(velocity); } void getViewAngles(float& x, float& y, float& z) { x = rotateX_; y = rotateY_; z = 0.f; } vec3 position_ { 0.f }; vec3 forward_ { 0.f, 0.f, 1.f }; vec3 up_ { 0.f, 1.f, 0.f }; vec3 right_ { 1.f, 0.f, 0.f }; float rotateX_ = 0.f; float rotateY_ = 180.f; float speed = 1.f; }; FirstPersonCamera g_camera; void Camera_Initialise() { g_camera = FirstPersonCamera(); } void Camera_Update(float deltaT, const CameraInput& input) { const float DEGREES_PER_SEC = 60.f; const float rotateX = deltaT * (input.pitch * DEGREES_PER_SEC); const float rotateY = deltaT * (input.yaw * DEGREES_PER_SEC); const vec3 adjustedSpeed = deltaT * (input.speed * g_camera.speed); g_camera.update(adjustedSpeed, rotateX, rotateY); } void Camera_SetPosition(const vec3& pos) { g_camera.position_ = pos; } void Camera_SetMoveSpeed(const float speed) { g_camera.speed = speed; } vec3 Camera_GetPosition() { return g_camera.position_; } vec3 Camera_GetForward() { return g_camera.forward_; } void Camera_GetViewAngles(float& x, float& y, float& z) { g_camera.getViewAngles(x, y, z); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_QEF_SIMD_H_BEEN_INCLUDED #define HAS_QEF_SIMD_H_BEEN_INCLUDED // // Quadric Error Function / Singluar Value Decomposition SSE2 implementation // Public domain // // Input is a set of positions / vertices of a surface and the surface normals // at these positions (i.e. Hermite data). A "best fit" position is calculated // from these positions along with an error value. // // Exmaple use cases: // - placing a vertex inside a voxel/node for algorithms like Dual Contouring // (the positions and normals corresponding to edge/isosurface intersections) // - placing the vertex resulting from collapsing an edge when simplifying a mesh // (the positions and normals of the collapsed edge should be supplied) // // Usage: // // SSE registers: // // __m128 position[2] = { ... }; // __m128 normal[2] = { ... }; // __m128 solvedPos; // float error = qef_solve_from_points(position, normal, 2, &solvedPos); // // 4D vectors: // // __declspec(align(16)) float positions[2 * 4] = { ... }; // __declspec(align(16)) float normals[2 * 4] = { ... }; // __declspec(align(16)) float solved[4]; // float error = qef_solve_from_points_4d(positions, normals, 2, solvedPos); // // 3D vectors (or struct with 3 float members, e.g. glm::vec3): // // glm::vec3 positions[2] = { ... }; // glm::vec3 normals[2] = { ... }; // glm::vec3 solvedPos; // float error = qef_solve_from_points_3d(&positions[0].x, &normals[0].x, 2, &solvedPos.x); // #include <xmmintrin.h> #include <immintrin.h> const int QEF_MAX_INPUT_COUNT = 12; // Ideally the data would already be in SSE registers & returned in a SEE register float qef_solve_from_points( const __m128* positions, const __m128* normals, const int count, __m128* solved_position); // Expects 4d vectors contiguous in memory for the positions/normals // Addresses pointed to by positions, normals and solved_position MUST be 16 byte aligned // Writes result to 4d vector. float qef_solve_from_points_4d( const float* positions, const float* normals, const int count, float* solved_position); float qef_solve_from_points_4d_interleaved( const float* data, const size_t stride, const int count, float* solved_position); // Expects 3d vectors contiguous in memory for the positions/normals // No alignment requirements. // Writes result to 3d vector. float qef_solve_from_points_3d( const float* positions, const float* normals, const int count, float* solved_position); #ifdef QEF_INCLUDE_IMPL union Mat4x4 { float m[4][4]; __m128 row[4]; __m256 d_row[2]; }; #define SVD_NUM_SWEEPS 5 const float PSUEDO_INVERSE_THRESHOLD = 0.1f; // ---------------------------------------------------------------------------- static inline __m128 vec4_abs(const __m128& x) { static const __m128 mask = _mm_set1_ps(-0.f); return _mm_andnot_ps(mask, x); } // ---------------------------------------------------------------------------- static inline float vec4_dot(const __m128& a, const __m128& b) { // apparently _mm_dp_ps isn't well implemented in hardware so this "basic" version is faster __m128 mul = _mm_mul_ps(a, b); __m128 s0 = _mm_shuffle_ps(mul, mul, _MM_SHUFFLE(2, 3, 0, 1)); __m128 add = _mm_add_ps(mul, s0); __m128 s1 = _mm_shuffle_ps(add, add, _MM_SHUFFLE(0, 1, 2, 3)); __m128 res = _mm_add_ps(add, s1); return _mm_cvtss_f32(res); } // ---------------------------------------------------------------------------- static inline __m128 vec4_mul_m4x4(const __m128& a, const Mat4x4& B) { __m128 result = _mm_mul_ps(_mm_shuffle_ps(a, a, 0x00), B.row[0]); result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a, a, 0x55), B.row[1])); result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a, a, 0xaa), B.row[2])); result = _mm_add_ps(result, _mm_mul_ps(_mm_shuffle_ps(a, a, 0xff), B.row[3])); return result; } // ---------------------------------------------------------------------------- static inline __m256 avx_vec4_mul_m4x4(const __m256& a, const Mat4x4& B) { __m256 result; result = _mm256_mul_ps(_mm256_shuffle_ps(a, a, 0x00), _mm256_broadcast_ps(&B.row[0])); result = _mm256_add_ps(result, _mm256_mul_ps(_mm256_shuffle_ps(a, a, 0x55), _mm256_broadcast_ps(&B.row[1]))); result = _mm256_add_ps(result, _mm256_mul_ps(_mm256_shuffle_ps(a, a, 0xaa), _mm256_broadcast_ps(&B.row[2]))); result = _mm256_add_ps(result, _mm256_mul_ps(_mm256_shuffle_ps(a, a, 0xff), _mm256_broadcast_ps(&B.row[3]))); return result; } // ---------------------------------------------------------------------------- static void m4x4_mul_m4x4(Mat4x4& out, const Mat4x4& A, const Mat4x4& B) { #if 1 out.row[0] = vec4_mul_m4x4(A.row[0], B); out.row[1] = vec4_mul_m4x4(A.row[1], B); out.row[2] = vec4_mul_m4x4(A.row[2], B); out.row[3] = vec4_mul_m4x4(A.row[3], B); #else _mm256_zeroupper(); __m256 a01 = _mm256_loadu_ps(&A.m[0][0]); __m256 a23 = _mm256_loadu_ps(&A.m[2][0]); __m256 out01x = avx_vec4_mul_m4x4(a01, B); __m256 out23x = avx_vec4_mul_m4x4(a23, B); _mm256_storeu_ps(&out.m[0][0], out01x); _mm256_storeu_ps(&out.m[2][0], out23x); #endif } // ---------------------------------------------------------------------------- static void givens_coeffs_sym(__m128& c_result, __m128& s_result, const Mat4x4& vtav) { __m128 simd_pp = _mm_set_ps( 0.f, vtav.row[1].m128_f32[1], vtav.row[0].m128_f32[0], vtav.row[0].m128_f32[0]); __m128 simd_pq = _mm_set_ps( 0.f, vtav.row[1].m128_f32[2], vtav.row[0].m128_f32[2], vtav.row[0].m128_f32[1]); __m128 simd_qq = _mm_set_ps( 0.f, vtav.row[2].m128_f32[2], vtav.row[2].m128_f32[2], vtav.row[1].m128_f32[1]); static const __m128 zeros = _mm_set1_ps(0.f); static const __m128 ones = _mm_set1_ps(1.f); static const __m128 twos = _mm_set1_ps(2.f); // tau = (a_qq - a_pp) / (2.f * a_pq); __m128 pq2 = _mm_mul_ps(simd_pq, twos); __m128 qq_sub_pp = _mm_sub_ps(simd_qq, simd_pp); __m128 tau = _mm_div_ps(qq_sub_pp, pq2); // stt = sqrt(1.f + tau * tau); __m128 tau_sq = _mm_mul_ps(tau, tau); __m128 tau_sq_1 = _mm_add_ps(tau_sq, ones); __m128 stt = _mm_sqrt_ps(tau_sq_1); // tan = 1.f / ((tau >= 0.f) ? (tau + stt) : (tau - stt)); __m128 tan_gt = _mm_add_ps(tau, stt); __m128 tan_lt = _mm_sub_ps(tau, stt); __m128 tan_cmp = _mm_cmpge_ps(tau, zeros); __m128 tan_cmp_gt = _mm_and_ps(tan_cmp, tan_gt); __m128 tan_cmp_lt = _mm_andnot_ps(tan_cmp, tan_lt); __m128 tan_inv = _mm_or_ps(tan_cmp_gt, tan_cmp_lt); __m128 tan = _mm_div_ps(ones, tan_inv); // c = rsqrt(1.f + tan * tan); __m128 tan_sq = _mm_mul_ps(tan, tan); __m128 tan_sq_1 = _mm_add_ps(ones, tan_sq); __m128 c = _mm_rsqrt_ps(tan_sq_1); // s = tan * c; __m128 s = _mm_mul_ps(tan, c); // if pq == 0.0: c = 1.f, s = 0.f __m128 pq_cmp = _mm_cmpeq_ps(simd_pq, zeros); __m128 c_true = _mm_and_ps(pq_cmp, ones); __m128 c_false = _mm_andnot_ps(pq_cmp, c); c_result = _mm_or_ps(c_true, c_false); __m128 s_true = _mm_and_ps(pq_cmp, zeros); __m128 s_false = _mm_andnot_ps(pq_cmp, s); s_result = _mm_or_ps(s_true, s_false); } // ---------------------------------------------------------------------------- static void rotateq_xy(Mat4x4& vtav, const __m128& c, const __m128& s) { __m128 u = _mm_set_ps( 0.f, vtav.row[1].m128_f32[1], vtav.row[0].m128_f32[0], vtav.row[0].m128_f32[0]); __m128 v = _mm_set_ps( 0.f, vtav.row[2].m128_f32[2], vtav.row[2].m128_f32[2], vtav.row[1].m128_f32[1]); __m128 a = _mm_set_ps( 0.f, vtav.row[1].m128_f32[2], vtav.row[0].m128_f32[2], vtav.row[0].m128_f32[1]); static const __m128 twos = _mm_set1_ps(2.f); __m128 cc = _mm_mul_ps(c, c); __m128 ss = _mm_mul_ps(s, s); // mx = 2.0 * c * s * a; __m128 c2 = _mm_mul_ps(twos, c); __m128 c2s = _mm_mul_ps(c2, s); __m128 mx = _mm_mul_ps(c2s, a); // x = cc * u - mx + ss * v; __m128 x0 = _mm_mul_ps(cc, u); __m128 x1 = _mm_sub_ps(x0, mx); __m128 x2 = _mm_mul_ps(ss, v); __m128 x = _mm_add_ps(x1, x2); // y = ss * u + mx + cc * v; __m128 y0 = _mm_mul_ps(ss, u); __m128 y1 = _mm_add_ps(x0, mx); __m128 y2 = _mm_add_ps(cc, v); __m128 y = _mm_add_ps(y1, y2); vtav.row[0].m128_f32[0] = x.m128_f32[0]; vtav.row[0].m128_f32[0] = x.m128_f32[1]; vtav.row[1].m128_f32[1] = x.m128_f32[2]; vtav.row[0].m128_f32[1] = y.m128_f32[0]; vtav.row[0].m128_f32[2] = y.m128_f32[1]; vtav.row[1].m128_f32[2] = y.m128_f32[2]; } // ---------------------------------------------------------------------------- static void svd_rotate(Mat4x4& vtav, Mat4x4& v, float c, float s, const int& a, const int& b) { if (vtav.row[a].m128_f32[b] == 0.f) { return; } __m128 simd_u = _mm_set_ps( vtav.row[0].m128_f32[3-b], v.row[2].m128_f32[a], v.row[1].m128_f32[a], v.row[0].m128_f32[a]); __m128 simd_v = _mm_set_ps( vtav.row[1-a].m128_f32[2], v.row[2].m128_f32[b], v.row[1].m128_f32[b], v.row[0].m128_f32[b]); __m128 simd_c = _mm_load1_ps(&c); __m128 simd_s = _mm_load1_ps(&s); __m128 x0 = _mm_mul_ps(simd_c, simd_u); __m128 x1 = _mm_mul_ps(simd_s, simd_v); __m128 x = _mm_sub_ps(x0, x1); __m128 y0 = _mm_mul_ps(simd_s, simd_u); __m128 y1 = _mm_mul_ps(simd_c, simd_v); __m128 y = _mm_add_ps(y0, y1); v.row[0].m128_f32[a] = x.m128_f32[0]; v.row[1].m128_f32[a] = x.m128_f32[1]; v.row[2].m128_f32[a] = x.m128_f32[2]; vtav.row[0].m128_f32[3-b] = x.m128_f32[3]; v.row[0].m128_f32[b] = y.m128_f32[0]; v.row[1].m128_f32[b] = y.m128_f32[1]; v.row[2].m128_f32[b] = y.m128_f32[2]; vtav.row[1-a].m128_f32[2] = y.m128_f32[3]; vtav.row[a].m128_f32[b] = 0.0; } // ---------------------------------------------------------------------------- static __m128 svd_solve_sym(Mat4x4& v, const Mat4x4& a) { Mat4x4 vtav = a; // assuming V is identity: you can also pass a matrix the rotations // should be applied to // U is not computed for (int i = 0; i < SVD_NUM_SWEEPS; ++i) { __m128 c, s; givens_coeffs_sym(c, s, vtav); rotateq_xy(vtav, c, s); svd_rotate(vtav, v, c.m128_f32[0], s.m128_f32[0], 0, 1); svd_rotate(vtav, v, c.m128_f32[1], s.m128_f32[1], 0, 2); svd_rotate(vtav, v, c.m128_f32[2], s.m128_f32[2], 1, 2); } return _mm_set_ps( 0.f, vtav.row[2].m128_f32[2], vtav.row[1].m128_f32[1], vtav.row[0].m128_f32[0]); } // ---------------------------------------------------------------------------- static inline __m128 svd_invdet(const __m128& x) { static const __m128 ones = _mm_set1_ps(1.f); static const __m128 tol = _mm_set1_ps(PSUEDO_INVERSE_THRESHOLD); __m128 abs_x = vec4_abs(x); __m128 one_over_x = _mm_div_ps(ones, x); __m128 abs_one_over_x = vec4_abs(one_over_x); __m128 min_abs = _mm_min_ps(abs_x, abs_one_over_x); __m128 cmp = _mm_cmpge_ps(min_abs, tol); return _mm_and_ps(cmp, one_over_x); } // ---------------------------------------------------------------------------- static void svd_pseudoinverse(Mat4x4& o, const __m128& sigma, const Mat4x4& v) { const __m128 invdet = svd_invdet(sigma); o.row[0] = _mm_mul_ps(v.row[0], invdet); o.row[1] = _mm_mul_ps(v.row[1], invdet); o.row[2] = _mm_mul_ps(v.row[2], invdet); o.row[3] = _mm_set1_ps(0.f); // order is important here since the invdet is pre-applied m4x4_mul_m4x4(o, o, v); } // ---------------------------------------------------------------------------- static void svd_solve_ATA_ATb(const Mat4x4& ATA, const __m128& ATb, __m128& x) { Mat4x4 V; V.row[0] = _mm_set_ps(0.f, 0.f, 0.f, 1.f); V.row[1] = _mm_set_ps(0.f, 0.f, 1.f, 0.f); V.row[2] = _mm_set_ps(0.f, 1.f, 0.f, 0.f); V.row[3] = _mm_set_ps(0.f, 0.f, 0.f, 0.f); const __m128 sigma = svd_solve_sym(V, ATA); // A = UEV^T; U = A / (E*V^T) Mat4x4 Vinv; svd_pseudoinverse(Vinv, sigma, V); x = vec4_mul_m4x4(ATb, Vinv); } // ---------------------------------------------------------------------------- void qef_simd_add( const __m128& p, const __m128& n, Mat4x4& ATA, __m128& ATb, __m128& pointaccum) { __m128 nX = _mm_mul_ps(_mm_shuffle_ps(n, n, _MM_SHUFFLE(0, 0, 0, 0)), n); __m128 nY = _mm_mul_ps(_mm_shuffle_ps(n, n, _MM_SHUFFLE(1, 1, 1, 1)), n); __m128 nZ = _mm_mul_ps(_mm_shuffle_ps(n, n, _MM_SHUFFLE(2, 2, 2, 2)), n); ATA.row[0] = _mm_add_ps(ATA.row[0], nX); ATA.row[1] = _mm_add_ps(ATA.row[1], nY); ATA.row[2] = _mm_add_ps(ATA.row[2], nZ); const float d = vec4_dot(p, n); __m128 x = _mm_set_ps(0.f, d, d, d); x = _mm_mul_ps(x, n); ATb = _mm_add_ps(ATb, x); pointaccum = _mm_add_ps(pointaccum, p); } // ---------------------------------------------------------------------------- float qef_simd_calc_error(const Mat4x4& A, const __m128& x, const __m128& b) { __m128 tmp = vec4_mul_m4x4(x, A); tmp = _mm_sub_ps(b, tmp); return vec4_dot(tmp, tmp); } // ---------------------------------------------------------------------------- float qef_simd_solve( const Mat4x4& ATA, const __m128& ATb, const __m128& pointaccum, __m128& x) { const __m128 masspoint = _mm_div_ps(pointaccum, _mm_set1_ps(pointaccum.m128_f32[3])); __m128 p = vec4_mul_m4x4(masspoint, ATA); p = _mm_sub_ps(ATb, p); svd_solve_ATA_ATb(ATA, p, x); const float error = qef_simd_calc_error(ATA, x, ATb); x = _mm_add_ps(x, masspoint); return error; } // ---------------------------------------------------------------------------- float qef_solve_from_points( const __m128* positions, const __m128* normals, const int count, __m128* solved_position) { __m128 pointaccum = _mm_set1_ps(0.f); __m128 ATb = _mm_set1_ps(0.f); Mat4x4 ATA; ATA.row[0] = _mm_set1_ps(0.f); ATA.row[1] = _mm_set1_ps(0.f); ATA.row[2] = _mm_set1_ps(0.f); ATA.row[3] = _mm_set1_ps(0.f); for (int i = 0; i < count && i < QEF_MAX_INPUT_COUNT; i++) { qef_simd_add(positions[i], normals[i], ATA, ATb, pointaccum); } return qef_simd_solve(ATA, ATb, pointaccum, *solved_position); } // ---------------------------------------------------------------------------- float qef_solve_from_points_4d( const float* positions, const float* normals, const int count, float* solved_position) { if (count < 2 || count > QEF_MAX_INPUT_COUNT) { solved_position[0] = solved_position[1] = solved_position[2] = solved_position[3] = 0.f; return 0.f; } __m128 p[QEF_MAX_INPUT_COUNT]; __m128 n[QEF_MAX_INPUT_COUNT]; for (int i = 0; i < count; i++) { p[i] = _mm_load_ps(&positions[i * 4]); n[i] = _mm_load_ps(&normals[i * 4]); } __m128 solved; const float error = qef_solve_from_points(p, n, count, &solved); _mm_store_ps(solved_position, solved); return error; } // ---------------------------------------------------------------------------- float qef_solve_from_points_4d_interleaved( const float* data, const size_t stride, const int count, float* solved_position) { if (count < 2 || count > QEF_MAX_INPUT_COUNT) { solved_position[0] = solved_position[1] = solved_position[2] = solved_position[3] = 0.f; return 0.f; } __m128 p[QEF_MAX_INPUT_COUNT]; __m128 n[QEF_MAX_INPUT_COUNT]; for (int i = 0; i < count; i++) { p[i] = _mm_load_ps(&data[(i * stride) + 0]); n[i] = _mm_load_ps(&data[(i * stride) + 4]); } __m128 solved; const float error = qef_solve_from_points(p, n, count, &solved); _mm_store_ps(solved_position, solved); return error; } // ---------------------------------------------------------------------------- float qef_solve_from_points_3d( const float* positions, const float* normals, const int count, float* solved_position) { if (count < 2 || count > QEF_MAX_INPUT_COUNT) { solved_position[0] = solved_position[1] = solved_position[2] = solved_position[3] = 0.f; return 0.f; } __m128 p[QEF_MAX_INPUT_COUNT]; __m128 n[QEF_MAX_INPUT_COUNT]; for (int i = 0; i < count; i++) { const float* pos = &positions[i * 3]; const float* nrm = &normals[i * 3]; p[i] = _mm_set_ps(1.f, pos[2], pos[1], pos[0]); n[i] = _mm_set_ps(0.f, nrm[2], nrm[1], nrm[0]); } __m128 solved; const float error = qef_solve_from_points(p, n, count, &solved); solved_position[0] = solved.m128_f32[0]; solved_position[1] = solved.m128_f32[1]; solved_position[2] = solved.m128_f32[2]; return error; } #endif // QEF_INCLUDE_IMPL #endif // HAS_QEF_SIMD_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
// minimal SVD implementation for calculating feature points from hermite data // works in C++ and GLSL // public domain #include "glsl_svd.h" #ifndef USE_GLSL #define USE_GLSL 0 #endif #ifndef USE_WEBGL #define USE_WEBGL 0 #endif #ifndef DEBUG_SVD //#define DEBUG_SVD (!USE_GLSL) #endif #ifndef SVD_COMPARE_REFERENCE //#define SVD_COMPARE_REFERENCE 1 #endif #define SVD_NUM_SWEEPS 5 #if USE_GLSL // GLSL prerequisites #define IN(t,x) in t x #define OUT(t, x) out t x #define INOUT(t, x) inout t x #define rsqrt inversesqrt #define SWIZZLE_XYZ(v) v.xyz #else // C++ prerequisites #include <math.h> //#include <glm/glm.hpp> //#include <glm/gtc/swizzle.hpp> using namespace glm; #define abs fabs #define sqrt sqrtf #define max(x,y) (((x)>(y))?(x):(y)) #define IN(t,x) const t& x #define OUT(t, x) t &x #define INOUT(t, x) t &x float rsqrt(float x) { return 1.0f / sqrt(x); } //#define SWIZZLE_XYZ(v) vec3(swizzle<X,Y,Z>(v)) #endif #if DEBUG_SVD // Debugging //////////////////////////////////////////////////////////////////////////////// void dump_vec3(vec3 v) { printf("(%.5f %.5f %.5f)\n", v[0], v[1], v[2]); } void dump_vec4(vec4 v) { printf("(%.5f %.5f %.5f %.5f)\n", v[0], v[1], v[2], v[3]); } void dump_mat3(mat3 m) { printf("(%.5f %.5f %.5f\n %.5f %.5f %.5f\n %.5f %.5f %.5f)\n", m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]); } #endif // SVD //////////////////////////////////////////////////////////////////////////////// const float PSUEDO_INVERSE_THRESHOLD = 0.1f; float svd_dot(IN(qef_vec3,a), IN(qef_vec3,b)) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } void svd_vec_sub(OUT(qef_vec3,result), IN(qef_vec3,a), IN(qef_vec3,b)) { result[0] = a[0] - b[0]; result[1] = a[1] - b[1]; result[2] = a[2] - b[2]; } void svd_mul_matrix_vec(OUT(qef_vec3,result), IN(qef_mat3,a), IN(qef_vec3,b)) { result[0] = a[0][0] * b[0] + a[0][1] * b[1] + a[0][2] * b[2]; result[1] = a[1][0] * b[0] + a[1][1] * b[1] + a[1][2] * b[2]; result[2] = a[2][0] * b[0] + a[2][1] * b[1] + a[2][2] * b[2]; } void givens_coeffs_sym(float a_pp, float a_pq, float a_qq, OUT(float,c), OUT(float,s)) { if (a_pq == 0.f) { c = 1.f; s = 0.f; return; } float tau = (a_qq - a_pp) / (2.f * a_pq); float stt = sqrt(1.f + tau * tau); float tan = 1.f / ((tau >= 0.f) ? (tau + stt) : (tau - stt)); c = rsqrt(1.f + tan * tan); s = tan * c; } void svd_rotate_xy(INOUT(float,x), INOUT(float,y), IN(float,c), IN(float,s)) { float u = x; float v = y; x = c * u - s * v; y = s * u + c * v; } void svd_rotateq_xy(INOUT(float,x), INOUT(float,y), INOUT(float,a), IN(float,c), IN(float,s)) { float cc = c * c; float ss = s * s; float mx = 2.0 * c * s * a; float u = x; float v = y; x = cc * u - mx + ss * v; y = ss * u + mx + cc * v; } #if USE_WEBGL void svd_rotate01(INOUT(mat3,vtav), INOUT(mat3,v)) { if (vtav[0][1] == 0.0) return; float c, s; givens_coeffs_sym(vtav[0][0], vtav[0][1], vtav[1][1], c, s); svd_rotateq_xy(vtav[0][0],vtav[1][1],vtav[0][1],c,s); svd_rotate_xy(vtav[0][2], vtav[1][2], c, s); vtav[0][1] = 0.0; svd_rotate_xy(v[0][0], v[0][1], c, s); svd_rotate_xy(v[1][0], v[1][1], c, s); svd_rotate_xy(v[2][0], v[2][1], c, s); } void svd_rotate02(INOUT(mat3,vtav), INOUT(mat3,v)) { if (vtav[0][2] == 0.0) return; float c, s; givens_coeffs_sym(vtav[0][0], vtav[0][2], vtav[2][2], c, s); svd_rotateq_xy(vtav[0][0],vtav[2][2],vtav[0][2],c,s); svd_rotate_xy(vtav[0][1], vtav[1][2], c, s); vtav[0][2] = 0.0; svd_rotate_xy(v[0][0], v[0][2], c, s); svd_rotate_xy(v[1][0], v[1][2], c, s); svd_rotate_xy(v[2][0], v[2][2], c, s); } void svd_rotate12(INOUT(mat3,vtav), INOUT(mat3,v)) { if (vtav[1][2] == 0.0) return; float c, s; givens_coeffs_sym(vtav[1][1], vtav[1][2], vtav[2][2], c, s); svd_rotateq_xy(vtav[1][1],vtav[2][2],vtav[1][2],c,s); svd_rotate_xy(vtav[0][1], vtav[0][2], c, s); vtav[1][2] = 0.0; svd_rotate_xy(v[0][1], v[0][2], c, s); svd_rotate_xy(v[1][1], v[1][2], c, s); svd_rotate_xy(v[2][1], v[2][2], c, s); } #else void svd_rotate(INOUT(qef_mat3,vtav), INOUT(qef_mat3,v), IN(int,a), IN(int,b)) { if (vtav[a][b] == 0.0) return; float c, s; givens_coeffs_sym(vtav[a][a], vtav[a][b], vtav[b][b], c, s); svd_rotateq_xy(vtav[a][a],vtav[b][b],vtav[a][b],c,s); svd_rotate_xy(vtav[0][3-b], vtav[1-a][2], c, s); vtav[a][b] = 0.0; svd_rotate_xy(v[0][a], v[0][b], c, s); svd_rotate_xy(v[1][a], v[1][b], c, s); svd_rotate_xy(v[2][a], v[2][b], c, s); } #endif void svd_solve_sym(IN(mat_upper_tri,a), OUT(qef_vec3,sigma), INOUT(qef_mat3,v)) { // assuming that A is symmetric: can optimize all operations for // the upper right triagonal qef_mat3 vtav; vtav[0][0] = a[0]; vtav[0][1] = a[1]; vtav[0][2] = a[2]; vtav[1][0] = 0.f; vtav[1][1] = a[3]; vtav[1][2] = a[4]; vtav[2][0] = 0.f; vtav[2][1] = 0.f; vtav[2][2] = a[5]; // assuming V is identity: you can also pass a matrix the rotations // should be applied to // U is not computed for (int i = 0; i < SVD_NUM_SWEEPS; ++i) { svd_rotate(vtav, v, 0, 1); svd_rotate(vtav, v, 0, 2); svd_rotate(vtav, v, 1, 2); } sigma[0] = vtav[0][0]; sigma[1] = vtav[1][1]; sigma[2] = vtav[2][2]; } float svd_invdet(float x, float tol) { return (abs(x) < tol || abs(1.0 / x) < tol) ? 0.0 : (1.0 / x); } void svd_pseudoinverse(OUT(qef_mat3,o), IN(qef_vec3,sigma), IN(qef_mat3,v)) { float d0 = svd_invdet(sigma[0], PSUEDO_INVERSE_THRESHOLD); float d1 = svd_invdet(sigma[1], PSUEDO_INVERSE_THRESHOLD); float d2 = svd_invdet(sigma[2], PSUEDO_INVERSE_THRESHOLD); o[0][0] = v[0][0] * d0 * v[0][0] + v[0][1] * d1 * v[0][1] + v[0][2] * d2 * v[0][2]; o[0][1] = v[0][0] * d0 * v[1][0] + v[0][1] * d1 * v[1][1] + v[0][2] * d2 * v[1][2]; o[0][2] = v[0][0] * d0 * v[2][0] + v[0][1] * d1 * v[2][1] + v[0][2] * d2 * v[2][2]; o[1][0] = v[1][0] * d0 * v[0][0] + v[1][1] * d1 * v[0][1] + v[1][2] * d2 * v[0][2]; o[1][1] = v[1][0] * d0 * v[1][0] + v[1][1] * d1 * v[1][1] + v[1][2] * d2 * v[1][2]; o[1][2] = v[1][0] * d0 * v[2][0] + v[1][1] * d1 * v[2][1] + v[1][2] * d2 * v[2][2]; o[2][0] = v[2][0] * d0 * v[0][0] + v[2][1] * d1 * v[0][1] + v[2][2] * d2 * v[0][2]; o[2][1] = v[2][0] * d0 * v[1][0] + v[2][1] * d1 * v[1][1] + v[2][2] * d2 * v[1][2]; o[2][2] = v[2][0] * d0 * v[2][0] + v[2][1] * d1 * v[2][1] + v[2][2] * d2 * v[2][2]; } void svd_solve_ATA_ATb( // IN(mat3,ATA), IN(vec3,ATb), OUT(vec3,x) IN(mat_upper_tri,ATA), IN(qef_vec3,ATb), OUT(qef_vec3,x) ) { qef_mat3 V; V[0][0] = 1.f; V[0][1] = 0.f; V[0][2] = 0.f; V[1][0] = 0.f; V[1][1] = 1.f; V[1][2] = 0.f; V[2][0] = 0.f; V[2][1] = 0.f; V[2][2] = 1.f; qef_vec3 sigma; svd_solve_sym(ATA, sigma, V); // A = UEV^T; U = A / (E*V^T) #if DEBUG_SVD printf("ATA="); dump_mat3(ATA); printf("ATb="); dump_vec3(ATb); printf("V="); dump_mat3(V); printf("sigma="); dump_vec3(sigma); #endif qef_mat3 Vinv; svd_pseudoinverse(Vinv, sigma, V); svd_mul_matrix_vec(x, Vinv, ATb); #if DEBUG_SVD printf("Vinv="); dump_mat3(Vinv); #endif } //vec3 svd_vmul_sym(IN(mat_upper_tri,a), IN(vec3,v)) { void svd_vmul_sym(OUT(qef_vec3,result), IN(mat_upper_tri,A), IN(qef_vec3,v)) { qef_vec3 A_row_x = qef_vec3(0.f); A_row_x[0] = A[0]; A_row_x[1] = A[1]; A_row_x[2] = A[2]; result[0] = svd_dot(A_row_x, v); result[1] = A[1] * v[0] + A[3] * v[1] + A[4] * v[2]; result[2] = A[2] * v[0] + A[4] * v[1] + A[5] * v[2]; } #if 0 void svd_mul_ata_sym(OUT(mat3,o), IN(mat3,a)) { o[0][0] = a[0][0] * a[0][0] + a[1][0] * a[1][0] + a[2][0] * a[2][0]; o[0][1] = a[0][0] * a[0][1] + a[1][0] * a[1][1] + a[2][0] * a[2][1]; o[0][2] = a[0][0] * a[0][2] + a[1][0] * a[1][2] + a[2][0] * a[2][2]; o[1][1] = a[0][1] * a[0][1] + a[1][1] * a[1][1] + a[2][1] * a[2][1]; o[1][2] = a[0][1] * a[0][2] + a[1][1] * a[1][2] + a[2][1] * a[2][2]; o[2][2] = a[0][2] * a[0][2] + a[1][2] * a[1][2] + a[2][2] * a[2][2]; } void svd_solve_Ax_b(IN(mat3,a), IN(vec3,b), OUT(mat3,ATA), OUT(vec3,ATb), OUT(vec3,x)) { svd_mul_ata_sym(ATA, a); ATb = b * a; // transpose(a) * b; svd_solve_ATA_ATb(ATA, ATb, x); } #endif // QEF //////////////////////////////////////////////////////////////////////////////// void qef_add( IN(qef_vec3,n), IN(qef_vec3,p), INOUT(mat_upper_tri,ATA), INOUT(qef_vec3,ATb), INOUT(qef_vec4,pointaccum)) { #if DEBUG_SVD printf("+plane=");dump_vec4(vec4(n, dot(-p,n))); #endif ATA[0] += n[0] * n[0]; ATA[1] += n[0] * n[1]; ATA[2] += n[0] * n[2]; ATA[3] += n[1] * n[1]; ATA[4] += n[1] * n[2]; ATA[5] += n[2] * n[2]; float b = svd_dot(p, n); ATb[0] += n[0] * b; ATb[1] += n[1] * b; ATb[2] += n[2] * b; pointaccum[0] += p[0]; pointaccum[1] += p[1]; pointaccum[2] += p[2]; pointaccum[3] += 1.f; } float qef_calc_error(IN(mat_upper_tri,A), IN(qef_vec3, x), IN(qef_vec3, b)) { qef_vec3 tmp; svd_vmul_sym(tmp, A, x); svd_vec_sub(tmp, b, tmp); return svd_dot(tmp, tmp); } float qef_solve( IN(mat_upper_tri,ATA), IN(qef_vec3,ATb), IN(qef_vec4,pointaccum), OUT(qef_vec3,x) ) { qef_vec3 masspoint; masspoint[0] = pointaccum[0] / pointaccum[3]; masspoint[1] = pointaccum[1] / pointaccum[3]; masspoint[2] = pointaccum[2] / pointaccum[3]; qef_vec3 A_mp; svd_vmul_sym(A_mp, ATA, masspoint); svd_vec_sub(A_mp, ATb, A_mp); svd_solve_ATA_ATb(ATA, A_mp, x); float result = qef_calc_error(ATA, x, ATb); x[0] += masspoint[0]; x[1] += masspoint[1]; x[2] += masspoint[2]; return result; } QEFData qef_construct( const qef_vec3* positions, const qef_vec3* normals, const size_t count) { QEFData data; for (size_t i = 0; i < count; i++) { const qef_vec3& p = positions[i]; const qef_vec3& n = normals[i]; data.ATA[0] += n[0] * n[0]; data.ATA[1] += n[0] * n[1]; data.ATA[2] += n[0] * n[2]; data.ATA[3] += n[1] * n[1]; data.ATA[4] += n[1] * n[2]; data.ATA[5] += n[2] * n[2]; const float b = svd_dot(p, n); data.ATb[0] += n[0] * b; data.ATb[1] += n[1] * b; data.ATb[2] += n[2] * b; data.masspoint[0] += p[0]; data.masspoint[1] += p[1]; data.masspoint[2] += p[2]; data.masspoint[3] += 1.f; } data.masspoint[0] = data.masspoint[0] / data.masspoint[3]; data.masspoint[1] = data.masspoint[1] / data.masspoint[3]; data.masspoint[2] = data.masspoint[2] / data.masspoint[3]; data.masspoint[3] = 1.f; return data; } void qef_add(QEFData& a, const QEFData& b) { a.ATA[0] += b.ATA[0]; a.ATA[1] += b.ATA[1]; a.ATA[2] += b.ATA[2]; a.ATA[3] += b.ATA[3]; a.ATA[4] += b.ATA[4]; a.ATA[5] += b.ATA[5]; a.ATb[0] += b.ATb[0]; a.ATb[1] += b.ATb[1]; a.ATb[2] += b.ATb[2]; a.masspoint[0] += b.masspoint[0]; a.masspoint[1] += b.masspoint[1]; a.masspoint[2] += b.masspoint[2]; a.masspoint[3] += 1.f; } float qef_solve( const QEFData& data, qef_vec3& solved_position) { qef_vec3 ATb, solved_p; qef_vec4 masspoint; ATb[0] = data.ATb[0]; ATb[1] = data.ATb[1]; ATb[2] = data.ATb[2]; masspoint[0] = data.masspoint[0]; masspoint[1] = data.masspoint[1]; masspoint[2] = data.masspoint[2]; masspoint[3] = data.masspoint[3]; auto error = qef_solve(data.ATA, ATb, masspoint, solved_p); solved_position[0] = solved_p[0]; solved_position[1] = solved_p[1]; solved_position[2] = solved_p[2]; return error; } float qef_solve_from_points( const qef_vec3* positions, const qef_vec3* normals, const size_t count, qef_vec3& solved_position) { qef_vec4 pointaccum(0.f); qef_vec3 ATb(0.f); mat_upper_tri ATA = {0.f}; qef_vec3 n[12], p[12]; for (int i = 0; i < count; i++) { p[i][0] = positions[i][0]; p[i][1] = positions[i][1]; p[i][2] = positions[i][2]; n[i][0] = normals[i][0]; n[i][1] = normals[i][1]; n[i][2] = normals[i][2]; } for (int i= 0; i < count; ++i) { qef_add(n[i],p[i],ATA,ATb,pointaccum); } return qef_solve(ATA,ATb,pointaccum,solved_position); } // Test //////////////////////////////////////////////////////////////////////////////// #if USE_GLSL void main(void) { } #else #if DEBUG_SVD #undef sqrt #undef abs #undef rsqrt #undef max #if SVD_COMPARE_REFERENCE #include "qr_solve.h" #include "r8lib.h" #include "qr_solve.c" #include "r8lib.c" #endif int main(void) { vec4 pointaccum = vec4(0.0); mat3 ATA = mat3(0.0); vec3 ATb = vec3(0.0); #define COUNT 5 vec3 normals[COUNT] = { normalize(vec3( 1.0,1.0,0.0)), normalize(vec3( 1.0,1.0,0.0)), normalize(vec3(-1.0,1.0,0.0)), normalize(vec3(-1.0,2.0,1.0)), //normalize(vec3(-1.0,1.0,0.0)), normalize(vec3(-1.0,1.0,0.0)), }; vec3 points[COUNT] = { vec3( 1.0,0.0,0.3), vec3( 0.9,0.1,-0.5), vec3( -0.8,0.2,0.6), vec3( -1.0,0.0,0.01), vec3( -1.1,-0.1,-0.5), }; for (int i= 0; i < COUNT; ++i) { qef_add(normals[i],points[i],ATA,ATb,pointaccum); } vec3 com = SWIZZLE_XYZ(pointaccum) / pointaccum.w; vec3 x; float error = qef_solve(ATA,ATb,pointaccum,x); printf("masspoint = (%.5f %.5f %.5f)\n", com.x, com.y, com.z); printf("point = (%.5f %.5f %.5f)\n", x.x, x.y, x.z); printf("error = %.5f\n", error); #if SVD_COMPARE_REFERENCE double a[COUNT*3]; double b[COUNT]; for (int i = 0; i < COUNT; ++i) { b[i] = (points[i].x - com.x)*normals[i].x + (points[i].y - com.y)*normals[i].y + (points[i].z - com.z)*normals[i].z; a[i] = normals[i].x; a[i+COUNT] = normals[i].y; a[i+2*COUNT] = normals[i].z; } double *c = svd_solve(5,3,a,b,0.1); vec3 result = com + vec3(c[0], c[1], c[2]); r8_free(c); printf("reference="); dump_vec3(result); #endif return 0; } #endif #endif
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_GLM_HASH_H_BEEN_INCLUDED #define HAS_GLM_HASH_H_BEEN_INCLUDED #include <glm/glm.hpp> namespace std { template <> struct hash<glm::ivec4> { std::size_t operator()(const glm::ivec4& min) const { auto x = std::hash<int>()(min.x); auto y = std::hash<int>()(min.y); auto z = std::hash<int>()(min.z); auto w = std::hash<int>()(min.w); return x ^ (((y >> 3) ^ (z << 5)) ^ (w << 8)); } }; template <> struct hash<glm::ivec3> { std::size_t operator()(const glm::ivec3& min) const { auto x = std::hash<int>()(min.x); auto y = std::hash<int>()(min.y); auto z = std::hash<int>()(min.z); return x ^ ((y >> 3) ^ (z << 5)); } }; template <> struct hash<glm::ivec2> { std::size_t operator()(const glm::ivec2& min) const { auto x = std::hash<int>()(min.x); auto y = std::hash<int>()(min.y); return x ^ (y >> 3); } }; } #endif // HAS_GLM_HASH_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "render_debug.h" #include "render_local.h" #include "render_program.h" #include "pool_allocator.h" #include "render_shapes.h" #include "sdl_wrapper.h" #include <glm/glm.hpp> #include <unordered_set> using glm::vec4; using glm::vec3; using glm::mat4; // ---------------------------------------------------------------------------- const int MAX_DEBUG_DRAW_CMD_BUFFERS = 1024; IndexPoolAllocator g_debugDrawCmdAlloc; DebugDrawBuffer* g_debugDrawCmdBuffers; std::unordered_set<DebugDrawBuffer*> g_enabledDebugDrawBuffers; GLSLProgram g_debugProgram; void InitialiseDebugDraw() { g_debugDrawCmdAlloc.initialise(MAX_DEBUG_DRAW_CMD_BUFFERS); g_debugDrawCmdBuffers = new DebugDrawBuffer[MAX_DEBUG_DRAW_CMD_BUFFERS]; if (!g_debugProgram.initialise() || !g_debugProgram.compileShader(GL_VERTEX_SHADER, "shaders/debug.vert") || !g_debugProgram.compileShader(GL_FRAGMENT_SHADER, "shaders/debug.frag") || !g_debugProgram.link()) { // TODO proper error handling LVN_ALWAYS_ASSERT("Debug GLSL program build failed", false); } } // ---------------------------------------------------------------------------- void DestroyDebugDraw() { g_debugDrawCmdAlloc.clear(); delete[] g_debugDrawCmdBuffers; g_debugDrawCmdBuffers = nullptr; } // ---------------------------------------------------------------------------- int CreateDebugDrawBuffer(const int bufferIndex) { LVN_ASSERT(bufferIndex >= 0 && bufferIndex < MAX_DEBUG_DRAW_CMD_BUFFERS); DebugDrawBuffer& buffer = g_debugDrawCmdBuffers[bufferIndex]; glGenBuffers(1, &buffer.vertexBuffer); glGenBuffers(1, &buffer.colourBuffer); glGenBuffers(1, &buffer.indexBuffer); glGenVertexArrays(1, &buffer.vao); glBindVertexArray(buffer.vao); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffer.vertexBuffer); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, buffer.colourBuffer); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.indexBuffer); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return LVN_SUCCESS; } // ---------------------------------------------------------------------------- int UpdateDebugDrawBuffer(const int bufferIndex, const RenderDebugCmdBuffer& cmdBuffer) { LVN_ASSERT(bufferIndex >= 0 && bufferIndex < MAX_DEBUG_DRAW_CMD_BUFFERS); DebugDrawBuffer& buffer = g_debugDrawCmdBuffers[bufferIndex]; int vertexBufferSize = 0; int indexBufferSize = 0; auto& cmds = cmdBuffer.commands(); for (int i = cmds.size() - 1; i >= 0; i--) { int vertices = 0; int indices = 0; const auto& cmd = cmds[i]; switch (cmd.shape) { case RenderShape_Cube: GetCubeDataSizes(&vertices, &indices); break; case RenderShape_Sphere: GetSphereDataSizes(&vertices, &indices); break; case RenderShape_Line: GetLineDataSizes(&vertices, &indices); break; } vertexBufferSize += vertices; indexBufferSize += indices; } vec4* vertexBuffer = new vec4[vertexBufferSize]; vec4* colourBuffer = new vec4[vertexBufferSize]; u16* indexBuffer = new u16[indexBufferSize]; u32 numVertices = 0; u32 numIndices = 0; for (int i = cmds.size() - 1; i >= 0; i--) { auto& cmd = cmds[i]; const vec4 colour = vec4(cmd.rgb, cmd.alpha); const u32 numVerticesBefore = numVertices; // TODO storing triangles and lines in the same buffer is broken unless we track it switch (cmd.shape) { case RenderShape_Cube: { const vec3 min(cmd.cube.min[0], cmd.cube.min[1], cmd.cube.min[2]); const vec3 max(cmd.cube.max[0], cmd.cube.max[1], cmd.cube.max[2]); GetCubeData(min, max, &vertexBuffer[numVertices], &indexBuffer[numIndices], &numVertices, &numIndices); break; } case RenderShape_Sphere: { const vec3 origin(cmd.sphere.origin[0], cmd.sphere.origin[1], cmd.sphere.origin[2]); GetSphereData(origin, cmd.sphere.radius, &vertexBuffer[numVertices], &indexBuffer[numIndices], &numVertices, &numIndices); break; } case RenderShape_Line: { const vec3 start(cmd.line.start[0], cmd.line.start[1], cmd.line.start[2]); const vec3 end(cmd.line.end[0], cmd.line.end[1], cmd.line.end[2]); GetLineData(start, end, &vertexBuffer[numVertices], &indexBuffer[numIndices], &numVertices, &numIndices); break; } } for (u32 i = numVerticesBefore; i < numVertices; i++) { colourBuffer[i] = colour; } } LVN_ASSERT(numVertices == vertexBufferSize); LVN_ASSERT(numIndices == indexBufferSize); // TODO broken buffer.shape = cmds[0].shape; glBindBuffer(GL_ARRAY_BUFFER, buffer.vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * buffer.numVertices, nullptr, GL_DYNAMIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * numVertices, &vertexBuffer[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, buffer.colourBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * buffer.numVertices, nullptr, GL_DYNAMIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4) * numVertices, &colourBuffer[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * buffer.numIndices, nullptr, GL_DYNAMIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * numIndices, &indexBuffer[0], GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); buffer.numVertices = numVertices; buffer.numIndices = numIndices; delete[] vertexBuffer; delete[] colourBuffer; delete[] indexBuffer;; return LVN_SUCCESS; } // ---------------------------------------------------------------------------- int FreeDebugDrawBuffer(int bufferIndex) { if (!bufferIndex || bufferIndex < 0 || bufferIndex >= MAX_DEBUG_DRAW_CMD_BUFFERS) { return LVN_ERR_INVALID_PARAM; } DebugDrawBuffer* buffer = &g_debugDrawCmdBuffers[bufferIndex]; glDeleteBuffers(1, &buffer->vertexBuffer); glDeleteBuffers(1, &buffer->colourBuffer); glDeleteBuffers(1, &buffer->indexBuffer); glDeleteVertexArrays(1, &buffer->vao); buffer->vertexBuffer = 0; buffer->colourBuffer = 0; buffer->indexBuffer = 0; buffer->vao = 0; buffer->numIndices = 0; g_debugDrawCmdAlloc.free(&bufferIndex); return LVN_SUCCESS; } // ---------------------------------------------------------------------------- int Render_SetDebugDrawCmds(const int id, const RenderDebugCmdBuffer& cmds) { if (id < 0 || id >= MAX_DEBUG_DRAW_CMD_BUFFERS || cmds.empty()) { return LVN_ERR_INVALID_PARAM; } PushRenderCommand([=]() { return UpdateDebugDrawBuffer(id, cmds) == LVN_SUCCESS; }); return LVN_SUCCESS; } // ---------------------------------------------------------------------------- int Render_AllocDebugDrawBuffer() { const int allocIndex = g_debugDrawCmdAlloc.alloc(); if (allocIndex != -1) { PushRenderCommand([=]() { return CreateDebugDrawBuffer(allocIndex) == LVN_SUCCESS; }); DebugDrawBuffer* buffer = &g_debugDrawCmdBuffers[allocIndex]; g_enabledDebugDrawBuffers.insert(&g_debugDrawCmdBuffers[allocIndex]); } return allocIndex; } // ---------------------------------------------------------------------------- int Render_FreeDebugDrawBuffer(int* id) { if (!id || *id < 0 || *id >= MAX_DEBUG_DRAW_CMD_BUFFERS) { return LVN_ERR_INVALID_PARAM; } DebugDrawBuffer* buffer = &g_debugDrawCmdBuffers[*id]; g_enabledDebugDrawBuffers.erase(buffer); PushRenderCommand([=]() { return FreeDebugDrawBuffer(*id) == LVN_SUCCESS; }); *id = -1; return LVN_SUCCESS; } // ---------------------------------------------------------------------------- int Render_EnableDebugDrawBuffer(int id) { if (id < 0 || id >= MAX_DEBUG_DRAW_CMD_BUFFERS) { return LVN_ERR_INVALID_PARAM; } g_enabledDebugDrawBuffers.insert(&g_debugDrawCmdBuffers[id]); return LVN_SUCCESS; } // ---------------------------------------------------------------------------- int Render_DisableDebugDrawBuffer(int id) { if (id < 0 || id >= MAX_DEBUG_DRAW_CMD_BUFFERS) { return LVN_ERR_INVALID_PARAM; } g_enabledDebugDrawBuffers.erase(&g_debugDrawCmdBuffers[id]); return LVN_SUCCESS; } // ---------------------------------------------------------------------------- std::vector<DebugDrawBuffer*> GetEnabledDebugDrawBuffers() { std::vector<DebugDrawBuffer*> buffers(g_enabledDebugDrawBuffers.size()); int i = 0; for (auto b: g_enabledDebugDrawBuffers) { buffers[i++] = b; } return buffers; } // ---------------------------------------------------------------------------- void DrawDebugBuffers(const mat4& projection, const mat4& worldView) { GLSLProgramView view(&g_debugProgram); const mat4 model = mat4(1.f); g_debugProgram.setUniform("MVP", projection * (worldView * model)); glPolygonMode(GL_FRONT, GL_FILL); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glDisable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); const auto debugBuffers = GetEnabledDebugDrawBuffers(); for (const auto& buffer: debugBuffers) { glBindVertexArray(buffer->vao); glDrawElements(buffer->shape != RenderShape_Line ? GL_TRIANGLES : GL_LINES, buffer->numIndices, GL_UNSIGNED_SHORT, (void*)0); } glBindVertexArray(0); glDisable(GL_BLEND); } // ----------------------------------------------------------------------------
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RENDER_LOCAL_H_BEEN_INCLUDED #define HAS_RENDER_LOCAL_H_BEEN_INCLUDED #include <functional> #include <vector> #include "render.h" // ---------------------------------------------------------------------------- typedef std::function<bool(void)> RenderCommand; void PushRenderCommand(RenderCommand cmd); // ---------------------------------------------------------------------------- struct DebugDrawBuffer { RenderShape shape = RenderShape_Cube; // TODO broken need to support multiple shapes per buffer GLuint vertexBuffer = 0; GLuint colourBuffer = 0; GLuint indexBuffer = 0; GLuint vao = 0; u32 numVertices = 0; u32 numIndices = 0; }; void InitialiseDebugDraw(); void DestroyDebugDraw(); void DrawDebugBuffers(const glm::mat4& projection, const glm::mat4& worldView); // ---------------------------------------------------------------------------- void InitialiseRenderMesh(); void DestroyRenderMesh(); // ---------------------------------------------------------------------------- #endif // HAS_RENDER_LOCAL_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include <catch.hpp> #include "cuckoo.h" TEST_CASE("CuckooHashTable", "[hashtable]") { struct TestData { int numUniqueKeys; int hashTableSize; float minInsertSuccess; }; const int TEST_SIZE_SMALL = 1 << 5; const int TEST_SIZE_MEDIUM = 1 << 14; const int TEST_SIZE_LARGE = 1 << 20; const float NORMAL_SUCCESS_RATIO = 0.98f; const float HIGH_SUCCESS_RATIO = 0.99f; const TestData tests[] = { { TEST_SIZE_SMALL, TEST_SIZE_SMALL, NORMAL_SUCCESS_RATIO }, { TEST_SIZE_MEDIUM, TEST_SIZE_MEDIUM, NORMAL_SUCCESS_RATIO }, { TEST_SIZE_LARGE, TEST_SIZE_LARGE, NORMAL_SUCCESS_RATIO }, { TEST_SIZE_SMALL, TEST_SIZE_SMALL, NORMAL_SUCCESS_RATIO }, { TEST_SIZE_SMALL, TEST_SIZE_MEDIUM, HIGH_SUCCESS_RATIO }, { TEST_SIZE_SMALL, TEST_SIZE_LARGE, 1.f }, { TEST_SIZE_MEDIUM, TEST_SIZE_SMALL, 0.01f }, { TEST_SIZE_MEDIUM, TEST_SIZE_MEDIUM, NORMAL_SUCCESS_RATIO }, { TEST_SIZE_MEDIUM, TEST_SIZE_LARGE, HIGH_SUCCESS_RATIO }, { -1, -1, false } }; INFO("CuckooHashTable test..."); std::mt19937 generator; std::uniform_int_distribution<uint32_t> distribution; std::unordered_set<uint32_t> testKeys; INFO("Generating " << TEST_SIZE_LARGE << " unique keys"); while (testKeys.size() < TEST_SIZE_LARGE) { uint32_t k = distribution(generator); if (testKeys.find(k) == end(testKeys)) { testKeys.insert(k); } } int counter = 0; for (auto test = tests; test->numUniqueKeys != -1; test++, counter++) { INFO("Test case: " << counter); CuckooHashTable cuckoo(test->hashTableSize); int numInserted = 0; auto iter = begin(testKeys); for (int i = 0; i < test->numUniqueKeys; i++) { const uint32_t k = *iter; iter++; if (cuckoo.insert(k, 0)) { numInserted++; } } const float insertRatio = (float)numInserted / (float)test->numUniqueKeys; REQUIRE(insertRatio >= test->minInsertSuccess); // for test where most values will not inserted this test won't work // as a lot of the "successfully" inserted values actually end up in the // stash and get evicted during the unsuccessful insert operations if (test->minInsertSuccess >= NORMAL_SUCCESS_RATIO) { int numFound = 0; int numCorrectValue = 0; iter = begin(testKeys); for (int i = 0; i < test->numUniqueKeys; i++) { const uint32_t k = *iter; iter++; uint32_t value = ~0; if (cuckoo.find(k, &value)) { if (value == 0) { numCorrectValue++; } numFound++; } } REQUIRE(numFound == numInserted); REQUIRE(numFound == numCorrectValue); } } } #include "testdata/octree_keys_184.cpp" #include "testdata/octree_keys_168.cpp" #include "testdata/octree_keys_146.cpp" #include "testdata/octree_keys_141.cpp" #include "testdata/octree_keys_136.cpp" #include "testdata/octree_keys_122.cpp" #include "testdata/octree_keys_119.cpp" #include "testdata/octree_keys_109.cpp" #include "testdata/octree_keys_91.cpp" #include "testdata/octree_keys_42.cpp" #include "testdata/octree_keys_28.cpp" #include "testdata/octree_keys_3.cpp" TEST_CASE("CuckooHashTable (Octree data)", "[hashtable] [octree]") { struct TestData { const uint32_t* keys; uint32_t count; }; const TestData testSets[] = { { OCTREE_KEYS_184, sizeof(OCTREE_KEYS_184) / sizeof(uint32_t) }, { OCTREE_KEYS_168, sizeof(OCTREE_KEYS_168) / sizeof(uint32_t) }, { OCTREE_KEYS_146, sizeof(OCTREE_KEYS_146) / sizeof(uint32_t) }, { OCTREE_KEYS_141, sizeof(OCTREE_KEYS_141) / sizeof(uint32_t) }, { OCTREE_KEYS_136, sizeof(OCTREE_KEYS_136) / sizeof(uint32_t) }, { OCTREE_KEYS_122, sizeof(OCTREE_KEYS_122) / sizeof(uint32_t) }, { OCTREE_KEYS_119, sizeof(OCTREE_KEYS_119) / sizeof(uint32_t) }, { OCTREE_KEYS_109, sizeof(OCTREE_KEYS_109) / sizeof(uint32_t) }, { OCTREE_KEYS_91, sizeof(OCTREE_KEYS_91) / sizeof(uint32_t) }, { OCTREE_KEYS_42, sizeof(OCTREE_KEYS_42) / sizeof(uint32_t) }, { OCTREE_KEYS_28, sizeof(OCTREE_KEYS_28) / sizeof(uint32_t) }, { OCTREE_KEYS_3, sizeof(OCTREE_KEYS_3) / sizeof(uint32_t) }, { nullptr, 0 }, }; for (int test = 0; testSets[test].keys != nullptr; test++) { INFO("Test: " << test); CuckooHashTable cuckoo(testSets[test].count); int totalCount = 0, insertedCount = 0; for (const uint32_t* code = testSets[test].keys; *code != ~0; code++) { if (cuckoo.insert(*code, 42)) { insertedCount++; } else { WARN("Failed to insert code: " << *code); } totalCount++; } REQUIRE(totalCount == insertedCount); bool allFound = true; bool all42 = true; for (const uint32_t* code = testSets[test].keys; *code != ~0; code++) { uint32_t value = ~0; allFound = allFound && cuckoo.find(*code, &value); all42 = all42 && value == 42; } REQUIRE(allFound); REQUIRE(all42); } }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_RENDER_H_BEEN_INCLUDED #define HAS_RENDER_H_BEEN_INCLUDED #include "render_types.h" #include "render_debug.h" #include "render_mesh.h" #include "render_actor.h" #include "materials.h" #include <string> #include <glm/glm.hpp> #include <stdint.h> #include <vector> // ---------------------------------------------------------------------------- struct ViewParams { float nearDistance, farDistance, fov, aspectRatio; }; bool Render_Initialise( const int width, const int height, const bool useShadows, const int shadowMapSize, const ViewParams& viewParams, MaterialSet& materials); void Render_Reset(); void Render_Shutdown(); bool Render_DispatchCommands(); void Render_FrameBegin(); void Render_FrameAddMesh(RenderMesh* mesh); void Render_FrameAddActorMesh(RenderMesh* mesh); void Render_DrawFrame(); void Render_FrameEnd(int* numTriangles); void Render_SetWorldBounds(const glm::ivec3& worldMin, const glm::ivec3& worldMax); void Render_ToggleWireframe(); void Render_ToggleShadowView(); void Render_SetDrawUI(const bool enable); void Render_ToggleLighting(); void Render_ToggleNormals(); void Render_RandomLightDir(); void Render_UpdatePreviewMaterial(const int materialID); void Render_UnprojectPoint(const glm::ivec2& point, glm::vec3& worldspaceNear, glm::vec3& worldspaceFar); const glm::mat4& Render_GetProjectionMatrix(); const glm::mat4& Render_GetWorldViewMatrix(); int Render_GetScreenWidth(); int Render_GetScreenHeight(); void Render_PrintStats(); void Render_DebugPrintFrameNumber(); #endif // HAS_RENDER_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_VOLUME_CONSTANTS_H_BEEN_INCLUDED #define HAS_VOLUME_CONSTANTS_H_BEEN_INCLUDED #include <glm/glm.hpp> // Not sure if I want to use the nodes with size==1 for the min size const int LEAF_SIZE_LOG2 = 2; const int LEAF_SIZE_SCALE = 1 << LEAF_SIZE_LOG2; // 64^3 or 128^3 seems a good size, 256^3 works // 512^3 and above starts running into problems with buffer sizes etc // 64^3 seems to be preferable due to clipmap limations (can't display part of an octree) // and CSG ops seem more responsive with 64^3 -- worth testing both when upgrading things in future const int CLIPMAP_VOXELS_PER_CHUNK = 64; const int CLIPMAP_LEAF_SIZE = LEAF_SIZE_SCALE * CLIPMAP_VOXELS_PER_CHUNK; // TODO there is an implicit leaf size scaling here that should be handled explicitly // think that requires removal of LEAF_SIZE_SCALE from the compute_ files (i.e. // the compute module should have no knowledge of the sizing, which can be handled // separately by the calling code) const int COLLISION_VOXELS_PER_CHUNK = 128 / 2; const int COLLISION_NODE_SIZE = CLIPMAP_LEAF_SIZE * (4 / 2); const glm::ivec3 CHILD_MIN_OFFSETS[] = { // needs to match the vertMap from Dual Contouring impl glm::ivec3( 0, 0, 0 ), glm::ivec3( 0, 0, 1 ), glm::ivec3( 0, 1, 0 ), glm::ivec3( 0, 1, 1 ), glm::ivec3( 1, 0, 0 ), glm::ivec3( 1, 0, 1 ), glm::ivec3( 1, 1, 0 ), glm::ivec3( 1, 1, 1 ), }; #endif // HAS_VOLUME_CONSTANTS_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef __RENDER_VERTEX_H__ #define __RENDER_VERTEX_H__ #if 0 #include <GL/glew.h> #include <SDL.h> #include <GL/GL.h> #include <GL/GLu.h> #include <glm/glm.hpp> typedef unsigned short Index; struct BillboardVertex { BillboardVertex() { p[0] = p[1] = p[2] = 0.f; p[3] = 1.f; c[0] = c[1] = c[2] = 1.f; c[3] = 0.3f; } BillboardVertex(const BillboardVertex& other) { p[0] = other.p[0]; p[1] = other.p[1]; p[2] = other.p[2]; p[3] = other.p[3]; c[0] = other.c[0]; c[1] = other.c[1]; c[2] = other.c[2]; c[3] = other.c[3]; } BillboardVertex(float pX, float pY, float pZ, float cR, float cG, float cB) { p[0] = pX; p[1] = pY; p[2] = pZ; p[3] = 1.f; c[0] = cR; c[1] = cG; c[2] = cB; c[3] = 0.3f; } float p[4]; float c[4]; }; struct GeometryVertex { GeometryVertex(const GeometryVertex& other) { p[0] = other.p[0]; p[1] = other.p[1]; p[2] = other.p[2]; p[3] = other.p[3]; n[0] = other.n[0]; n[1] = other.n[1]; n[2] = other.n[2]; n[3] = other.n[3]; st[0] = other.st[0]; st[1] = other.st[1]; } GeometryVertex() { p[0] = p[1] = p[2] = p[3] = 0.f; n[0] = n[1] = n[2] = n[3] = 0.f; st[0] = st[1] = 0.f; } GeometryVertex(float pX, float pY, float pZ, float pW=1.f) { p[0] = pX; p[1] = pY; p[2] = pZ; p[3] = pW; n[0] = n[1] = n[2] = n[3] = 0.f; st[0] = st[1] = 0.f; // TODO remove me int *p = 0; *p = 0; } GeometryVertex(float pX, float pY, float pZ, float s, float t) { p[0] = pX; p[1] = pY; p[2] = pZ; p[3] = 1.f; st[0] = s; st[1] = t; n[0] = n[1] = n[2] = n[3] = 0.f; } GeometryVertex(float pX, float pY, float pZ, float nX, float nY, float nZ) { p[0] = pX; p[1] = pY; p[2] = pZ; p[3] = 1.f; n[0] = nX; n[1] = nY; n[2] = nZ; n[3] = 1.f; st[0] = st[1] = 0.f; } GeometryVertex(float pX, float pY, float pZ, float pW, float nX, float nY, float nZ, float nW) { p[0] = pX; p[1] = pY; p[2] = pZ; p[3] = pW; n[0] = nX; n[1] = nY; n[2] = nZ; n[3] = nW; st[0] = st[1] = 0.f; } float p[4]; float n[4]; float st[2]; }; void Vertex_SetNormal(GeometryVertex& v, const glm::vec3& normal); const glm::vec3 Vertex_GetPosition(GeometryVertex& v); template <typename T> void Vertex_SetGLState(); template <typename T> void Vertex_ResetGLState(); template <typename VertexType> struct VertexBuffer { VertexBuffer() : vertex_(0) { glGenVertexArrays(1, &arrayObj_); glGenBuffers(1, &vertex_); glGenBuffers(1, &index_); } ~VertexBuffer() { glDeleteBuffers(1, &index_); glDeleteBuffers(1, &vertex_); glDeleteVertexArrays(1, &arrayObj_); } void setData(const VertexType* vertices, size_t vertexDataSize, const Index* indices, size_t indexDataSize) { glBindVertexArray(arrayObj_); glBindBuffer(GL_ARRAY_BUFFER, vertex_); glBufferData(GL_ARRAY_BUFFER, vertexDataSize, (float*)(&vertices[0].p), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexDataSize, (Index*)(&indices[0]), GL_STATIC_DRAW); Vertex_SetGLState<VertexType>(); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); Vertex_ResetGLState<VertexType>(); } struct View { View(const VertexBuffer<VertexType>& buffer) { // note the ordering here matters, we need to bind a buffer first glBindVertexArray(buffer.arrayObj_); } ~View() { glBindVertexArray(0); } }; GLuint arrayObj_; GLuint vertex_; GLuint index_; }; #endif #endif // __RENDER_VERTEX_H__
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
/* stbi-1.33 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c when you control the images you're loading no warranty implied; use at your own risk QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline (no JPEG progressive) PNG 8-bit-per-channel only TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE PSD (composited view only, no extra channels) GIF (*comp always reports as 4-channel) HDR (radiance rgbE format) PIC (Softimage PIC) - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - decode from arbitrary I/O callbacks - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD) Latest revisions: 1.33 (2011-07-14) minor fixes suggested by Dave Moore 1.32 (2011-07-13) info support for all filetypes (SpartanJ) 1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-uint8 to fix warnings (Laurent Gomila) allow trailing 0s at end of image data (Laurent Gomila) 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ See end of file for full revision history. TODO: stbi_info support for BMP,PSD,HDR,PIC ============================ Contributors ========================= Image formats Optimizations & bugfixes Sean Barrett (jpeg, png, bmp) Fabian "ryg" Giesen Nicolas Schulz (hdr, psd) Jonathan Dummer (tga) Bug fixes & warning fixes Jean-Marc Lienher (gif) Marc LeBlanc Tom Seddon (pic) Christpher Lloyd Thatcher Ulrich (psd) Dave Moore Won Chun the Horde3D community Extensions, features Janez Zemva Jetro Lauha (stbi_info) Jonathan Blow James "moose2000" Brown (iPhone PNG) Laurent Gomila Ben "Disch" Wenger (io callbacks) Aruelien Pocheville Martin "SpartanJ" Golini Ryamond Barbiero David Woo If your name should be here but isn't, let Sean know. */ #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H // To get a header file for this, either cut and paste the header, // or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and // then include stb_image.c from it. //// begin header file //////////////////////////////////////////////////// // // Limitations: // - no jpeg progressive support // - non-HDR formats support 8-bit samples only (jpeg, png) // - no delayed line count (jpeg) -- IJG doesn't support either // - no 1-bit BMP // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 // stbi_image_free(data) // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *comp -- outputs # of image components in image file // int req_comp -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. // If req_comp is non-zero, *comp has the number of components that _would_ // have been output otherwise. E.g. if you set req_comp to 4, you will always // get RGBA output, but you can check *comp to easily see if it's opaque. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *comp will be unchanged. The function stbi_failure_reason() // can be queried for an extremely brief, end-user unfriendly explanation // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // // =========================================================================== // // iPhone PNG support: // // By default we convert iphone-formatted PNGs back to RGB; nominally they // would silently load as BGR, except the existing code should have just // failed on such iPhone PNGs. But you can disable this conversion by // by calling stbi_convert_iphone_png_to_rgb(0), in which case // you will always just get the native iphone "format" through. // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image now supports loading HDR images in general, and currently // the Radiance .HDR file format, although the support is provided // generically. You can still load any file through the existing interface; // if you attempt to load an HDR file, it will be automatically remapped to // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); // // =========================================================================== // // I/O callbacks // // I/O callbacks allow you to read from arbitrary sources, like packaged // files or some other source. Data read from callbacks are processed // through a small internal buffer (currently 128 bytes) to try to reduce // overhead. // // The three functions you must define are "read" (reads some bytes of data), // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). #ifndef STBI_NO_STDIO #if defined(_MSC_VER) && _MSC_VER >= 0x1400 #define _CRT_SECURE_NO_WARNINGS // suppress bogus warnings about fopen() #endif #include <stdio.h> #endif #define STBI_VERSION 1 enum { STBI_default = 0, // only used for req_comp STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4 }; typedef unsigned char stbi_uc; #ifdef __cplusplus extern "C" { #endif ////////////////////////////////////////////////////////////////////////////// // // PRIMARY API - works on images of any type // // // load image by filename, open file, or memory buffer // extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif typedef struct { int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read void (*skip) (void *user,unsigned n); // skip the next 'n' bytes int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; extern stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_HDR extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); #ifndef STBI_NO_STDIO extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); #endif extern float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); extern void stbi_hdr_to_ldr_gamma(float gamma); extern void stbi_hdr_to_ldr_scale(float scale); extern void stbi_ldr_to_hdr_gamma(float gamma); extern void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_HDR // stbi_is_hdr is always defined extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO extern int stbi_is_hdr (char const *filename); extern int stbi_is_hdr_from_file(FILE *f); #endif // STBI_NO_STDIO // get a VERY brief reason for failure // NOT THREADSAFE extern const char *stbi_failure_reason (void); // free the loaded image -- this is just free() extern void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); extern int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); #ifndef STBI_NO_STDIO extern int stbi_info (char const *filename, int *x, int *y, int *comp); extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); #endif // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. extern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // ZLIB client - used by PNG, available for other purposes extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); // define faster low-level operations (typically SIMD support) #ifdef STBI_SIMD typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize); // compute an integer IDCT on "input" // input[x] = data[x] * dequantize[x] // write results to 'out': 64 samples, each run of 8 spaced by 'out_stride' // CLAMP results to 0..255 typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step); // compute a conversion from YCbCr to RGB // 'count' pixels // write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B // y: Y input channel // cb: Cb input channel; scale/biased to be 0..255 // cr: Cr input channel; scale/biased to be 0..255 extern void stbi_install_idct(stbi_idct_8x8 func); extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func); #endif // STBI_SIMD #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H #ifndef STBI_HEADER_FILE_ONLY #ifndef STBI_NO_HDR #include <math.h> // ldexp #include <string.h> // strcmp, strtok #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #include <stdlib.h> #include <memory.h> #include <assert.h> #include <stdarg.h> #ifndef _MSC_VER #ifdef __cplusplus #define stbi_inline inline #else #define stbi_inline #endif #else #define stbi_inline __forceinline #endif // implementation: typedef unsigned char uint8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; typedef unsigned int uint; // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(uint32)==4 ? 1 : -1]; #if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE) #define STBI_NO_WRITE #endif #define STBI_NOTUSED(v) (void)sizeof(v) #ifdef _MSC_VER #define STBI_HAS_LROTL #endif #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) #endif /////////////////////////////////////////////// // // stbi struct and start_xxx functions // stbi structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information typedef struct { uint32 img_x, img_y; int img_n, img_out_n; stbi_io_callbacks io; void *io_user_data; int read_from_callbacks; int buflen; uint8 buffer_start[128]; uint8 *img_buffer, *img_buffer_end; uint8 *img_buffer_original; } stbi; static void refill_buffer(stbi *s); // initialize a memory-decode context static void start_mem(stbi *s, uint8 const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->img_buffer = s->img_buffer_original = (uint8 *) buffer; s->img_buffer_end = (uint8 *) buffer+len; } // initialize a callback-based context static void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; s->img_buffer_original = s->buffer_start; refill_buffer(s); } #ifndef STBI_NO_STDIO static int stdio_read(void *user, char *data, int size) { return (int) fread(data,1,size,(FILE*) user); } static void stdio_skip(void *user, unsigned n) { fseek((FILE*) user, n, SEEK_CUR); } static int stdio_eof(void *user) { return feof((FILE*) user); } static stbi_io_callbacks stbi_stdio_callbacks = { stdio_read, stdio_skip, stdio_eof, }; static void start_file(stbi *s, FILE *f) { start_callbacks(s, &stbi_stdio_callbacks, (void *) f); } //static void stop_file(stbi *s) { } #endif // !STBI_NO_STDIO static void stbi_rewind(stbi *s) { // conceptually rewind SHOULD rewind to the beginning of the stream, // but we just rewind to the beginning of the initial buffer, because // we only use it after doing 'test', which only ever looks at at most 92 bytes s->img_buffer = s->img_buffer_original; } static int stbi_jpeg_test(stbi *s); static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp); static int stbi_png_test(stbi *s); static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_png_info(stbi *s, int *x, int *y, int *comp); static int stbi_bmp_test(stbi *s); static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_tga_test(stbi *s); static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_tga_info(stbi *s, int *x, int *y, int *comp); static int stbi_psd_test(stbi *s); static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_hdr_test(stbi *s); static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_pic_test(stbi *s); static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_gif_test(stbi *s); static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp); static int stbi_gif_info(stbi *s, int *x, int *y, int *comp); // this is not threadsafe static const char *failure_reason; const char *stbi_failure_reason(void) { return failure_reason; } static int e(const char *str) { failure_reason = str; return 0; } // e - error // epf - error returning pointer to float // epuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS #define e(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define e(x,y) e(y) #else #define e(x,y) e(x) #endif #define epf(x,y) ((float *) (e(x,y)?NULL:NULL)) #define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL)) void stbi_image_free(void *retval_from_stbi_load) { free(retval_from_stbi_load); } #ifndef STBI_NO_HDR static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp); static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp); #endif static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp) { if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp); if (stbi_png_test(s)) return stbi_png_load(s,x,y,comp,req_comp); if (stbi_bmp_test(s)) return stbi_bmp_load(s,x,y,comp,req_comp); if (stbi_gif_test(s)) return stbi_gif_load(s,x,y,comp,req_comp); if (stbi_psd_test(s)) return stbi_psd_load(s,x,y,comp,req_comp); if (stbi_pic_test(s)) return stbi_pic_load(s,x,y,comp,req_comp); #ifndef STBI_NO_HDR if (stbi_hdr_test(s)) { float *hdr = stbi_hdr_load(s, x,y,comp,req_comp); return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif // test tga last because it's a crappy test! if (stbi_tga_test(s)) return stbi_tga_load(s,x,y,comp,req_comp); return epuc("unknown image type", "Image not of any known type, or corrupt"); } #ifndef STBI_NO_STDIO unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = fopen(filename, "rb"); unsigned char *result; if (!f) return epuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f,x,y,comp,req_comp); fclose(f); return result; } unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s,f); return stbi_load_main(&s,x,y,comp,req_comp); } #endif //!STBI_NO_STDIO unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s,buffer,len); return stbi_load_main(&s,x,y,comp,req_comp); } unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi s; start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi_load_main(&s,x,y,comp,req_comp); } #ifndef STBI_NO_HDR float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi_hdr_test(s)) return stbi_hdr_load(s,x,y,comp,req_comp); #endif data = stbi_load_main(s, x, y, comp, req_comp); if (data) return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return epf("unknown image type", "Image not of any known type, or corrupt"); } float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi s; start_mem(&s,buffer,len); return stbi_loadf_main(&s,x,y,comp,req_comp); } float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi s; start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi_loadf_main(&s,x,y,comp,req_comp); } #ifndef STBI_NO_STDIO float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = fopen(filename, "rb"); float *result; if (!f) return epf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f,x,y,comp,req_comp); fclose(f); return result; } float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi s; start_file(&s,f); return stbi_loadf_main(&s,x,y,comp,req_comp); } #endif // !STBI_NO_STDIO #endif // !STBI_NO_HDR // these is-hdr-or-not is defined independent of whether STBI_NO_HDR is // defined, for API simplicity; if STBI_NO_HDR is defined, it always // reports false! int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR stbi s; start_mem(&s,buffer,len); return stbi_hdr_test(&s); #else STBI_NOTUSED(buffer); STBI_NOTUSED(len); return 0; #endif } #ifndef STBI_NO_STDIO extern int stbi_is_hdr (char const *filename) { FILE *f = fopen(filename, "rb"); int result=0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } extern int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR stbi s; start_file(&s,f); return stbi_hdr_test(&s); #else return 0; #endif } #endif // !STBI_NO_STDIO extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) { #ifndef STBI_NO_HDR stbi s; start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi_hdr_test(&s); #else return 0; #endif } #ifndef STBI_NO_HDR static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f; static float l2h_gamma=2.2f, l2h_scale=1.0f; void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; } void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; } void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; } void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; } #endif ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { SCAN_load=0, SCAN_type, SCAN_header }; static void refill_buffer(stbi *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); if (n == 0) { // at end of file, treat same as if from memory s->read_from_callbacks = 0; s->img_buffer = s->img_buffer_end-1; *s->img_buffer = 0; } else { s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + n; } } stbi_inline static int get8(stbi *s) { if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; if (s->read_from_callbacks) { refill_buffer(s); return *s->img_buffer++; } return 0; } stbi_inline static int at_eof(stbi *s) { if (s->io.read) { if (!(s->io.eof)(s->io_user_data)) return 0; // if feof() is true, check if buffer = end // special case: we've only got the special 0 character at the end if (s->read_from_callbacks == 0) return 1; } return s->img_buffer >= s->img_buffer_end; } stbi_inline static uint8 get8u(stbi *s) { return (uint8) get8(s); } static void skip(stbi *s, int n) { if (s->io.read) { int blen = s->img_buffer_end - s->img_buffer; if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); return; } } s->img_buffer += n; } static int getn(stbi *s, stbi_uc *buffer, int n) { if (s->io.read) { int blen = s->img_buffer_end - s->img_buffer; if (blen < n) { int res, count; memcpy(buffer, s->img_buffer, blen); count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); res = (count == (n-blen)); s->img_buffer = s->img_buffer_end; return res; } } if (s->img_buffer+n <= s->img_buffer_end) { memcpy(buffer, s->img_buffer, n); s->img_buffer += n; return 1; } else return 0; } static int get16(stbi *s) { int z = get8(s); return (z << 8) + get8(s); } static uint32 get32(stbi *s) { uint32 z = get16(s); return (z << 16) + get16(s); } static int get16le(stbi *s) { int z = get8(s); return z + (get8(s) << 8); } static uint32 get32le(stbi *s) { uint32 z = get16le(s); return z + (get16le(s) << 16); } ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static uint8 compute_y(int r, int g, int b) { return (uint8) (((r*77) + (g*150) + (29*b)) >> 8); } static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y) { int i,j; unsigned char *good; if (req_comp == img_n) return data; assert(req_comp >= 1 && req_comp <= 4); good = (unsigned char *) malloc(req_comp * x * y); if (good == NULL) { free(data); return epuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; #define COMBO(a,b) ((a)*8+(b)) #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (COMBO(img_n, req_comp)) { CASE(1,2) dest[0]=src[0], dest[1]=255; break; CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; CASE(2,1) dest[0]=src[0]; break; CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break; CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break; CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break; CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; default: assert(0); } #undef CASE } free(data); return good; } #ifndef STBI_NO_HDR static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; float *output = (float *) malloc(x * y * comp * sizeof(float)); if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale; } if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; } free(data); return output; } #define float2int(x) ((int) (x)) static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; stbi_uc *output = (stbi_uc *) malloc(x * y * comp); if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (uint8) float2int(z); } if (k < comp) { float z = data[i*comp+k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (uint8) float2int(z); } } free(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder (not actually fully baseline implementation) // // simple implementation // - channel subsampling of at most 2 in each dimension // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - uses a lot of intermediate memory, could cache poorly // - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4 // stb_jpeg: 1.34 seconds (MSVC6, default release build) // stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro) // IJL11.dll: 1.08 seconds (compiled by intel) // IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG) // IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro) // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { uint8 fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win uint16 code[256]; uint8 values[256]; uint8 size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } huffman; typedef struct { #ifdef STBI_SIMD unsigned short dequant2[4][64]; #endif stbi *s; huffman huff_dc[4]; huffman huff_ac[4]; uint8 dequant[4][64]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h,v; int tq; int hd,ha; int dc_pred; int x,y,w2,h2; uint8 *data; void *raw_data; uint8 *linebuf; } img_comp[4]; uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int scan_n, order[4]; int restart_interval, todo; } jpeg; static int build_huffman(huffman *h, int *count) { int i,j,k=0,code; // build size list for each symbol (from JPEG spec) for (i=0; i < 16; ++i) for (j=0; j < count[i]; ++j) h->size[k++] = (uint8) (i+1); h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for(j=1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (uint16) (code++); if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS-s); int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (uint8) i; } } } return 1; } static void grow_buffer_unsafe(jpeg *j) { do { int b = j->nomore ? 0 : get8(j->s); if (b == 0xff) { int c = get8(j->s); if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; return; } } j->code_buffer |= b << (24 - j->code_bits); j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int decode(jpeg *j, huffman *h) { unsigned int temp; int c,k; if (j->code_bits < 16) grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; j->code_bits -= s; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. temp = j->code_buffer >> 16; for (k=FAST_BITS+1 ; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k]; assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; j->code_buffer <<= k; return h->values[c]; } // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. stbi_inline static int extend_receive(jpeg *j, int n) { unsigned int m = 1 << (n-1); unsigned int k; if (j->code_bits < n) grow_buffer_unsafe(j); #if 1 k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~bmask[n]; k &= bmask[n]; j->code_bits -= n; #else k = (j->code_buffer >> (32 - n)) & bmask[n]; j->code_bits -= n; j->code_buffer <<= n; #endif // the following test is probably a random branch that won't // predict well. I tried to table accelerate it but failed. // maybe it's compiling as a conditional move? if (k < m) return (-1 << n) + k + 1; else return k; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static uint8 dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b) { int diff,dc,k; int t = decode(j, hdc); if (t < 0) return e("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) dc; // decode AC components, see JPEG spec k = 1; do { int r,s; int rs = decode(j, hac); if (rs < 0) return e("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location data[dezigzag[k++]] = (short) extend_receive(j,s); } } while (k < 64); return 1; } // take a -128..127 value and clamp it and convert to 0..255 stbi_inline static uint8 clamp(int x) { // trick to use a single test to catch both cases if ((unsigned int) x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (uint8) x; } #define f2f(x) (int) (((x) * 4096 + 0.5)) #define fsh(x) ((x) << 12) // derived from jidctint -- DCT_ISLOW #define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * f2f(0.5411961f); \ t2 = p1 + p3*f2f(-1.847759065f); \ t3 = p1 + p2*f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = fsh(p2+p3); \ t1 = fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*f2f( 1.175875602f); \ t0 = t0*f2f( 0.298631336f); \ t1 = t1*f2f( 2.053119869f); \ t2 = t2*f2f( 3.072711026f); \ t3 = t3*f2f( 1.501321110f); \ p1 = p5 + p1*f2f(-0.899976223f); \ p2 = p5 + p2*f2f(-2.562915447f); \ p3 = p3*f2f(-1.961570560f); \ p4 = p4*f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; #ifdef STBI_SIMD typedef unsigned short stbi_dequantize_t; #else typedef uint8 stbi_dequantize_t; #endif // .344 seconds on 3*anemones.jpg static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize) { int i,val[64],*v=val; stbi_dequantize_t *dq = dequantize; uint8 *o; short *d = data; // columns for (i=0; i < 8; ++i,++d,++dq, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0] * dq[0] << 2; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24], d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. // so we want to round that, which means adding 0.5 * 1<<17, // aka 65536. Also, we'll end up with -128 to 127 that we want // to encode as 0..255 by adding 128, so we'll add that before the shift x0 += 65536 + (128<<17); x1 += 65536 + (128<<17); x2 += 65536 + (128<<17); x3 += 65536 + (128<<17); // tried computing the shifts into temps, or'ing the temps to see // if any were out of range, but that was slower o[0] = clamp((x0+t3) >> 17); o[7] = clamp((x0-t3) >> 17); o[1] = clamp((x1+t2) >> 17); o[6] = clamp((x1-t2) >> 17); o[2] = clamp((x2+t1) >> 17); o[5] = clamp((x2-t1) >> 17); o[3] = clamp((x3+t0) >> 17); o[4] = clamp((x3-t0) >> 17); } } #ifdef STBI_SIMD static stbi_idct_8x8 stbi_idct_installed = idct_block; void stbi_install_idct(stbi_idct_8x8 func) { stbi_idct_installed = func; } #endif #define MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static uint8 get_marker(jpeg *j) { uint8 x; if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; } x = get8u(j->s); if (x != 0xff) return MARKER_none; while (x == 0xff) x = get8u(j->s); return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, reset the entropy decoder and // the dc prediction static void reset(jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; j->marker = MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int parse_entropy_coded_data(jpeg *z) { reset(z); if (z->scan_n == 1) { int i,j; #ifdef STBI_SIMD __declspec(align(16)) #endif short data[64]; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0; #ifdef STBI_SIMD stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]); #else idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]); #endif // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!RESTART(z->marker)) return 1; reset(z); } } } } else { // interleaved! int i,j,k,x,y; short data[64]; for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x)*8; int y2 = (j*z->img_comp[n].v + y)*8; if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0; #ifdef STBI_SIMD stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]); #else idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]); #endif } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!RESTART(z->marker)) return 1; reset(z); } } } } return 1; } static int process_marker(jpeg *z, int m) { int L; switch (m) { case MARKER_none: // no marker found return e("expected marker","Corrupt JPEG"); case 0xC2: // SOF - progressive return e("progressive jpeg","JPEG format not supported (progressive)"); case 0xDD: // DRI - specify restart interval if (get16(z->s) != 4) return e("bad DRI len","Corrupt JPEG"); z->restart_interval = get16(z->s); return 1; case 0xDB: // DQT - define quantization table L = get16(z->s)-2; while (L > 0) { int q = get8(z->s); int p = q >> 4; int t = q & 15,i; if (p != 0) return e("bad DQT type","Corrupt JPEG"); if (t > 3) return e("bad DQT table","Corrupt JPEG"); for (i=0; i < 64; ++i) z->dequant[t][dezigzag[i]] = get8u(z->s); #ifdef STBI_SIMD for (i=0; i < 64; ++i) z->dequant2[t][i] = z->dequant[t][i]; #endif L -= 65; } return L==0; case 0xC4: // DHT - define huffman table L = get16(z->s)-2; while (L > 0) { uint8 *v; int sizes[16],i,m=0; int q = get8(z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = get8(z->s); m += sizes[i]; } L -= 17; if (tc == 0) { if (!build_huffman(z->huff_dc+th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!build_huffman(z->huff_ac+th, sizes)) return 0; v = z->huff_ac[th].values; } for (i=0; i < m; ++i) v[i] = get8u(z->s); L -= m; } return L==0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { skip(z->s, get16(z->s)-2); return 1; } return 0; } // after we see SOS static int process_scan_header(jpeg *z) { int i; int Ls = get16(z->s); z->scan_n = get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return e("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = get8(z->s), which; int q = get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG"); z->order[i] = which; } if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG"); get8(z->s); // should be 63, but might be 0 if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG"); return 1; } static int process_frame_header(jpeg *z, int scan) { stbi *s = z->s; int Lf,p,i,q, h_max=1,v_max=1,c; Lf = get16(s); if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG p = get8(s); if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = get16(s); if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = get16(s); if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires c = get8(s); if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG"); // JFIF requires s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG"); for (i=0; i < s->img_n; ++i) { z->img_comp[i].id = get8(s); if (z->img_comp[i].id != i+1) // JFIF requires if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! return e("bad component ID","Corrupt JPEG"); q = get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG"); z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG"); } if (scan != SCAN_load) return 1; if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; for (i=0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); if (z->img_comp[i].raw_data == NULL) { for(--i; i >= 0; --i) { free(z->img_comp[i].raw_data); z->img_comp[i].data = NULL; } return e("outofmem", "Out of memory"); } // align blocks for installable-idct using mmx/sse z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); z->img_comp[i].linebuf = NULL; } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define DNL(x) ((x) == 0xdc) #define SOI(x) ((x) == 0xd8) #define EOI(x) ((x) == 0xd9) #define SOF(x) ((x) == 0xc0 || (x) == 0xc1) #define SOS(x) ((x) == 0xda) static int decode_jpeg_header(jpeg *z, int scan) { int m; z->marker = MARKER_none; // initialize cached marker to empty m = get_marker(z); if (!SOI(m)) return e("no SOI","Corrupt JPEG"); if (scan == SCAN_type) return 1; m = get_marker(z); while (!SOF(m)) { if (!process_marker(z,m)) return 0; m = get_marker(z); while (m == MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (at_eof(z->s)) return e("no SOF", "Corrupt JPEG"); m = get_marker(z); } } if (!process_frame_header(z, scan)) return 0; return 1; } static int decode_jpeg_image(jpeg *j) { int m; j->restart_interval = 0; if (!decode_jpeg_header(j, SCAN_load)) return 0; m = get_marker(j); while (!EOI(m)) { if (SOS(m)) { if (!process_scan_header(j)) return 0; if (!parse_entropy_coded_data(j)) return 0; if (j->marker == MARKER_none ) { // handle 0s at the end of image data from IP Kamera 9060 while (!at_eof(j->s)) { int x = get8(j->s); if (x == 255) { j->marker = get8u(j->s); break; } else if (x != 0) { return 0; } } // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0 } } else { if (!process_marker(j, m)) return 0; } m = get_marker(j); } return 1; } // static jfif-centered resampling (across block boundaries) typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1, int w, int hs); #define div4(x) ((uint8) ((x) >> 2)) static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); STBI_NOTUSED(hs); return in_near; } static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); for (i=0; i < w; ++i) out[i] = div4(3*in_near[i] + in_far[i] + 2); return out; } static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; uint8 *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { int n = 3*input[i]+2; out[i*2+0] = div4(n+input[i-1]); out[i*2+1] = div4(n+input[i+1]); } out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2); out[i*2+1] = input[w-1]; STBI_NOTUSED(in_far); STBI_NOTUSED(hs); return out; } #define div16(x) ((uint8) ((x) >> 4)) static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i,t0,t1; if (w == 1) { out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; out[0] = div4(t1+2); for (i=1; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = div16(3*t0 + t1 + 8); out[i*2 ] = div16(3*t1 + t0 + 8); } out[w*2-1] = div4(t1+2); STBI_NOTUSED(hs); return out; } static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs) { // resample with nearest-neighbor int i,j; in_far = in_far; for (i=0; i < w; ++i) for (j=0; j < hs; ++j) out[i*hs+j] = in_near[i]; return out; } #define float2fixed(x) ((int) ((x) * 65536 + 0.5)) // 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro) // VC6 without processor=Pro is generating multiple LEAs per multiply! static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 16) + 32768; // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr*float2fixed(1.40200f); g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); b = y_fixed + cb*float2fixed(1.77200f); r >>= 16; g >>= 16; b >>= 16; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (uint8)r; out[1] = (uint8)g; out[2] = (uint8)b; out[3] = 255; out += step; } } #ifdef STBI_SIMD static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row; void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func) { stbi_YCbCr_installed = func; } #endif // clean up the temporary component buffers static void cleanup_jpeg(jpeg *j) { int i; for (i=0; i < j->s->img_n; ++i) { if (j->img_comp[i].data) { free(j->img_comp[i].raw_data); j->img_comp[i].data = NULL; } if (j->img_comp[i].linebuf) { free(j->img_comp[i].linebuf); j->img_comp[i].linebuf = NULL; } } } typedef struct { resample_row_func resample; uint8 *line0,*line1; int hs,vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi_resample; static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n; // validate req_comp if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error"); z->s->img_n = 0; // load a jpeg image from whichever source if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n; if (z->s->img_n == 3 && n < 3) decode_n = 1; else decode_n = z->s->img_n; // resample and color-convert { int k; uint i,j; uint8 *output; uint8 *coutput[4]; stbi_resample res_comp[4]; for (k=0; k < decode_n; ++k) { stbi_resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (uint8 *) malloc(z->s->img_x + 3); if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s->img_x + r->hs-1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2; else r->resample = resample_row_generic; } // can't error after this so, this is safe output = (uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1); if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); } // now go ahead and resample for (j=0; j < z->s->img_y; ++j) { uint8 *out = output + n * z->s->img_x * j; for (k=0; k < decode_n; ++k) { stbi_resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { uint8 *y = coutput[0]; if (z->s->img_n == 3) { #ifdef STBI_SIMD stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n); #else YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n); #endif } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { uint8 *y = coutput[0]; if (n == 1) for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; else for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; } } cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; if (comp) *comp = z->s->img_n; // report original components, not output return output; } } static unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp) { jpeg j; j.s = s; return load_jpeg_image(&j, x,y,comp,req_comp); } static int stbi_jpeg_test(stbi *s) { int r; jpeg j; j.s = s; r = decode_jpeg_header(&j, SCAN_type); stbi_rewind(s); return r; } static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp) { if (!decode_jpeg_header(j, SCAN_header)) { stbi_rewind( j->s ); return 0; } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; if (comp) *comp = j->s->img_n; return 1; } static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp) { jpeg j; j.s = s; return stbi_jpeg_info_raw(&j, x, y, comp); } // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman // fast-way is faster to check than jpeg huffman, but slow way is slower #define ZFAST_BITS 9 // accelerate all cases in default tables #define ZFAST_MASK ((1 << ZFAST_BITS) - 1) // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { uint16 fast[1 << ZFAST_BITS]; uint16 firstcode[16]; int maxcode[17]; uint16 firstsymbol[16]; uint8 size[288]; uint16 value[288]; } zhuffman; stbi_inline static int bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } stbi_inline static int bit_reverse(int v, int bits) { assert(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return bitreverse16(v) >> (16-bits); } static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 255, sizeof(z->fast)); for (i=0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i=1; i < 16; ++i) assert(sizes[i] <= (1 << i)); code = 0; for (i=1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (uint16) code; z->firstsymbol[i] = (uint16) k; code = (code + sizes[i]); if (sizes[i]) if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG"); z->maxcode[i] = code << (16-i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; z->size[c] = (uint8)s; z->value[c] = (uint16)i; if (s <= ZFAST_BITS) { int k = bit_reverse(next_code[s],s); while (k < (1 << ZFAST_BITS)) { z->fast[k] = (uint16) c; k += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { uint8 *zbuffer, *zbuffer_end; int num_bits; uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; zhuffman z_length, z_distance; } zbuf; stbi_inline static int zget8(zbuf *z) { if (z->zbuffer >= z->zbuffer_end) return 0; return *z->zbuffer++; } static void fill_bits(zbuf *z) { do { assert(z->code_buffer < (1U << z->num_bits)); z->code_buffer |= zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } stbi_inline static unsigned int zreceive(zbuf *z, int n) { unsigned int k; if (z->num_bits < n) fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z) { int b,s,k; if (a->num_bits < 16) fill_bits(a); b = z->fast[a->code_buffer & ZFAST_MASK]; if (b < 0xffff) { s = z->size[b]; a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = bit_reverse(a->code_buffer, 16); for (s=ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; if (s == 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; assert(z->size[b] == s); a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } static int expand(zbuf *z, int n) // need to make room for n bytes { char *q; int cur, limit; if (!z->z_expandable) return e("output buffer limit","Corrupt PNG"); cur = (int) (z->zout - z->zout_start); limit = (int) (z->zout_end - z->zout_start); while (cur + n > limit) limit *= 2; q = (char *) realloc(z->zout_start, limit); if (q == NULL) return e("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static int length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static int length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static int dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int parse_huffman_block(zbuf *a) { for(;;) { int z = zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0; *a->zout++ = (char) z; } else { uint8 *p; int len,dist; if (z == 256) return 1; z -= 257; len = length_base[z]; if (length_extra[z]) len += zreceive(a, length_extra[z]); z = zhuffman_decode(a, &a->z_distance); if (z < 0) return e("bad huffman code","Corrupt PNG"); dist = dist_base[z]; if (dist_extra[z]) dist += zreceive(a, dist_extra[z]); if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0; p = (uint8 *) (a->zout - dist); while (len--) *a->zout++ = *p++; } } } static int compute_huffman_codes(zbuf *a) { static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; zhuffman z_codelength; uint8 lencodes[286+32+137];//padding for maximum single op uint8 codelength_sizes[19]; int i,n; int hlit = zreceive(a,5) + 257; int hdist = zreceive(a,5) + 1; int hclen = zreceive(a,4) + 4; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { int s = zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (uint8) s; } if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < hlit + hdist) { int c = zhuffman_decode(a, &z_codelength); assert(c >= 0 && c < 19); if (c < 16) lencodes[n++] = (uint8) c; else if (c == 16) { c = zreceive(a,2)+3; memset(lencodes+n, lencodes[n-1], c); n += c; } else if (c == 17) { c = zreceive(a,3)+3; memset(lencodes+n, 0, c); n += c; } else { assert(c == 18); c = zreceive(a,7)+11; memset(lencodes+n, 0, c); n += c; } } if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG"); if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } static int parse_uncompressed_block(zbuf *a) { uint8 header[4]; int len,nlen,k; if (a->num_bits & 7) zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns? a->code_buffer >>= 8; a->num_bits -= 8; } assert(a->num_bits == 0); // now fill header the normal way while (k < 4) header[k++] = (uint8) zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int parse_zlib_header(zbuf *a) { int cmf = zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = zget8(a); if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } // @TODO: should statically initialize these for optimal thread safety static uint8 default_length[288], default_distance[32]; static void init_defaults(void) { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) default_length[i] = 8; for ( ; i <= 255; ++i) default_length[i] = 9; for ( ; i <= 279; ++i) default_length[i] = 7; for ( ; i <= 287; ++i) default_length[i] = 8; for (i=0; i <= 31; ++i) default_distance[i] = 5; } int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead static int parse_zlib(zbuf *a, int parse_header) { int final, type; if (parse_header) if (!parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = zreceive(a,1); type = zreceive(a,2); if (type == 0) { if (!parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!default_distance[31]) init_defaults(); if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0; if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0; } else { if (!compute_huffman_codes(a)) return 0; } if (!parse_huffman_block(a)) return 0; } if (stbi_png_partial && a->zout - a->zout_start > 65536) break; } while (!final); return 1; } static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return parse_zlib(a, parse_header); } char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { zbuf a; char *p = (char *) malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (uint8 *) buffer; a.zbuffer_end = (uint8 *) buffer + len; if (do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { free(a.zout_start); return NULL; } } char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) { zbuf a; char *p = (char *) malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (uint8 *) buffer; a.zbuffer_end = (uint8 *) buffer + len; if (do_zlib(&a, p, initial_size, 1, parse_header)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { free(a.zout_start); return NULL; } } int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { zbuf a; a.zbuffer = (uint8 *) ibuffer; a.zbuffer_end = (uint8 *) ibuffer + ilen; if (do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { zbuf a; char *p = (char *) malloc(16384); if (p == NULL) return NULL; a.zbuffer = (uint8 *) buffer; a.zbuffer_end = (uint8 *) buffer+len; if (do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { free(a.zout_start); return NULL; } } int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { zbuf a; a.zbuffer = (uint8 *) ibuffer; a.zbuffer_end = (uint8 *) ibuffer + ilen; if (do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding typedef struct { uint32 length; uint32 type; } chunk; #define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) static chunk get_chunk_header(stbi *s) { chunk c; c.length = get32(s); c.type = get32(s); return c; } static int check_png_header(stbi *s) { static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (get8u(s) != png_sig[i]) return e("bad png sig","Not a PNG"); return 1; } typedef struct { stbi *s; uint8 *idata, *expanded, *out; } png; enum { F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4, F_avg_first, F_paeth_first }; static uint8 first_row_filter[5] = { F_none, F_sub, F_none, F_avg_first, F_paeth_first }; static int paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p-a); int pb = abs(p-b); int pc = abs(p-c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } // create the png data from post-deflated data static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y) { stbi *s = a->s; uint32 i,j,stride = x*out_n; int k; int img_n = s->img_n; // copy it into a local for later assert(out_n == s->img_n || out_n == s->img_n+1); if (stbi_png_partial) y = 1; a->out = (uint8 *) malloc(x * y * out_n); if (!a->out) return e("outofmem", "Out of memory"); if (!stbi_png_partial) { if (s->img_x == x && s->img_y == y) { if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG"); } else { // interlaced: if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG"); } } for (j=0; j < y; ++j) { uint8 *cur = a->out + stride*j; uint8 *prior = cur - stride; int filter = *raw++; if (filter > 4) return e("invalid filter","Corrupt PNG"); // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first pixel explicitly for (k=0; k < img_n; ++k) { switch (filter) { case F_none : cur[k] = raw[k]; break; case F_sub : cur[k] = raw[k]; break; case F_up : cur[k] = raw[k] + prior[k]; break; case F_avg : cur[k] = raw[k] + (prior[k]>>1); break; case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break; case F_avg_first : cur[k] = raw[k]; break; case F_paeth_first: cur[k] = raw[k]; break; } } if (img_n != out_n) cur[img_n] = 255; raw += img_n; cur += out_n; prior += out_n; // this is a little gross, so that we don't switch per-pixel or per-component if (img_n == out_n) { #define CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \ for (k=0; k < img_n; ++k) switch (filter) { CASE(F_none) cur[k] = raw[k]; break; CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break; CASE(F_up) cur[k] = raw[k] + prior[k]; break; CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break; CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break; CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break; CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break; } #undef CASE } else { assert(img_n+1 == out_n); #define CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \ for (k=0; k < img_n; ++k) switch (filter) { CASE(F_none) cur[k] = raw[k]; break; CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break; CASE(F_up) cur[k] = raw[k] + prior[k]; break; CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break; CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break; CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break; } #undef CASE } } return 1; } static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced) { uint8 *final; int p; int save; if (!interlaced) return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y); save = stbi_png_partial; stbi_png_partial = 0; // de-interlacing final = (uint8 *) malloc(a->s->img_x * a->s->img_y * out_n); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; int xspc[] = { 8,8,4,4,2,2,1 }; int yspc[] = { 8,8,8,4,4,2,2 }; int i,j,x,y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; if (x && y) { if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) { free(final); return 0; } for (j=0; j < y; ++j) for (i=0; i < x; ++i) memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n, a->out + (j*x+i)*out_n, out_n); free(a->out); raw += (x*out_n+1)*y; raw_len -= (x*out_n+1)*y; } } a->out = final; stbi_png_partial = save; return 1; } static int compute_transparency(png *z, uint8 tc[3], int out_n) { stbi *s = z->s; uint32 i, pixel_count = s->img_x * s->img_y; uint8 *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output assert(out_n == 2 || out_n == 4); if (out_n == 2) { for (i=0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i=0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n) { uint32 i, pixel_count = a->s->img_x * a->s->img_y; uint8 *p, *temp_out, *orig = a->out; p = (uint8 *) malloc(pixel_count * pal_img_n); if (p == NULL) return e("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p += 3; } } else { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p[3] = palette[n+3]; p += 4; } } free(a->out); a->out = temp_out; STBI_NOTUSED(len); return 1; } static int stbi_unpremultiply_on_load = 0; static int stbi_de_iphone_flag = 0; void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply; } void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { stbi_de_iphone_flag = flag_true_if_should_convert; } static void stbi_de_iphone(png *z) { stbi *s = z->s; uint32 i, pixel_count = s->img_x * s->img_y; uint8 *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { uint8 t = p[0]; p[0] = p[2]; p[2] = t; p += 3; } } else { assert(s->img_out_n == 4); if (stbi_unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i=0; i < pixel_count; ++i) { uint8 a = p[3]; uint8 t = p[0]; if (a) { p[0] = p[2] * 255 / a; p[1] = p[1] * 255 / a; p[2] = t * 255 / a; } else { p[0] = p[2]; p[2] = t; } p += 4; } } else { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { uint8 t = p[0]; p[0] = p[2]; p[2] = t; p += 4; } } } } static int parse_png_file(png *z, int scan, int req_comp) { uint8 palette[1024], pal_img_n=0; uint8 has_trans=0, tc[3]; uint32 ioff=0, idata_limit=0, i, pal_len=0; int first=1,k,interlace=0, iphone=0; stbi *s = z->s; z->expanded = NULL; z->idata = NULL; z->out = NULL; if (!check_png_header(s)) return 0; if (scan == SCAN_type) return 1; for (;;) { chunk c = get_chunk_header(s); switch (c.type) { case PNG_TYPE('C','g','B','I'): iphone = stbi_de_iphone_flag; skip(s, c.length); break; case PNG_TYPE('I','H','D','R'): { int depth,color,comp,filter; if (!first) return e("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return e("bad IHDR len","Corrupt PNG"); s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)"); s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)"); depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only"); color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG"); comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG"); filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG"); interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG"); if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode"); if (scan == SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG"); // if SCAN_header, have to scan to see if we have a tRNS } break; } case PNG_TYPE('P','L','T','E'): { if (first) return e("first not IHDR", "Corrupt PNG"); if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG"); for (i=0; i < pal_len; ++i) { palette[i*4+0] = get8u(s); palette[i*4+1] = get8u(s); palette[i*4+2] = get8u(s); palette[i*4+3] = 255; } break; } case PNG_TYPE('t','R','N','S'): { if (first) return e("first not IHDR", "Corrupt PNG"); if (z->idata) return e("tRNS after IDAT","Corrupt PNG"); if (pal_img_n) { if (scan == SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG"); if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG"); pal_img_n = 4; for (i=0; i < c.length; ++i) palette[i*4+3] = get8u(s); } else { if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG"); if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG"); has_trans = 1; for (k=0; k < s->img_n; ++k) tc[k] = (uint8) get16(s); // non 8-bit images will be larger } break; } case PNG_TYPE('I','D','A','T'): { if (first) return e("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG"); if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; } if (ioff + c.length > idata_limit) { uint8 *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory"); z->idata = p; } if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG"); ioff += c.length; break; } case PNG_TYPE('I','E','N','D'): { uint32 raw_len; if (first) return e("first not IHDR", "Corrupt PNG"); if (scan != SCAN_load) return 1; if (z->idata == NULL) return e("no IDAT","Corrupt PNG"); z->expanded = (uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone); if (z->expanded == NULL) return 0; // zlib should set error free(z->idata); z->idata = NULL; if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0; if (has_trans) if (!compute_transparency(z, tc, s->img_out_n)) return 0; if (iphone && s->img_out_n > 2) stbi_de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!expand_palette(z, palette, pal_len, s->img_out_n)) return 0; } free(z->expanded); z->expanded = NULL; return 1; } default: // if critical, fail if (first) return e("first not IHDR", "Corrupt PNG"); if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX chunk not known"; invalid_chunk[0] = (uint8) (c.type >> 24); invalid_chunk[1] = (uint8) (c.type >> 16); invalid_chunk[2] = (uint8) (c.type >> 8); invalid_chunk[3] = (uint8) (c.type >> 0); #endif return e(invalid_chunk, "PNG not supported: unknown chunk type"); } skip(s, c.length); break; } // end of chunk, read and skip CRC get32(s); } } static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp) { unsigned char *result=NULL; if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error"); if (parse_png_file(p, SCAN_load, req_comp)) { result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; if (n) *n = p->s->img_n; } free(p->out); p->out = NULL; free(p->expanded); p->expanded = NULL; free(p->idata); p->idata = NULL; return result; } static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp) { png p; p.s = s; return do_png(&p, x,y,comp,req_comp); } static int stbi_png_test(stbi *s) { int r; r = check_png_header(s); stbi_rewind(s); return r; } static int stbi_png_info_raw(png *p, int *x, int *y, int *comp) { if (!parse_png_file(p, SCAN_header, 0)) { stbi_rewind( p->s ); return 0; } if (x) *x = p->s->img_x; if (y) *y = p->s->img_y; if (comp) *comp = p->s->img_n; return 1; } static int stbi_png_info(stbi *s, int *x, int *y, int *comp) { png p; p.s = s; return stbi_png_info_raw(&p, x, y, comp); } // Microsoft/Windows BMP image static int bmp_test(stbi *s) { int sz; if (get8(s) != 'B') return 0; if (get8(s) != 'M') return 0; get32le(s); // discard filesize get16le(s); // discard reserved get16le(s); // discard reserved get32le(s); // discard data offset sz = get32le(s); if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1; return 0; } static int stbi_bmp_test(stbi *s) { int r = bmp_test(s); stbi_rewind(s); return r; } // returns 0..31 for the highest set bit static int high_bit(unsigned int z) { int n=0; if (z == 0) return -1; if (z >= 0x10000) n += 16, z >>= 16; if (z >= 0x00100) n += 8, z >>= 8; if (z >= 0x00010) n += 4, z >>= 4; if (z >= 0x00004) n += 2, z >>= 2; if (z >= 0x00002) n += 1, z >>= 1; return n; } static int bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } static int shiftsigned(int v, int shift, int bits) { int result; int z=0; if (shift < 0) v <<= -shift; else v >>= shift; result = v; z = bits; while (z < 8) { result += v >> z; z += bits; } return result; } static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp) { uint8 *out; unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0; stbi_uc pal[256][4]; int psize=0,i,j,compress=0,width; int bpp, flip_vertically, pad, target, offset, hsz; if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP"); get32le(s); // discard filesize get16le(s); // discard reserved get16le(s); // discard reserved offset = get32le(s); hsz = get32le(s); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = get16le(s); s->img_y = get16le(s); } else { s->img_x = get32le(s); s->img_y = get32le(s); } if (get16le(s) != 1) return epuc("bad BMP", "bad BMP"); bpp = get16le(s); if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit"); flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); if (hsz == 12) { if (bpp < 24) psize = (offset - 14 - 24) / 3; } else { compress = get32le(s); if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE"); get32le(s); // discard sizeof get32le(s); // discard hres get32le(s); // discard vres get32le(s); // discard colorsused get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { get32le(s); get32le(s); get32le(s); get32le(s); } if (bpp == 16 || bpp == 32) { mr = mg = mb = 0; if (compress == 0) { if (bpp == 32) { mr = 0xffu << 16; mg = 0xffu << 8; mb = 0xffu << 0; ma = 0xffu << 24; fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255 } else { mr = 31u << 10; mg = 31u << 5; mb = 31u << 0; } } else if (compress == 3) { mr = get32le(s); mg = get32le(s); mb = get32le(s); // not documented, but generated by photoshop and handled by mspaint if (mr == mg && mg == mb) { // ?!?!? return epuc("bad BMP", "bad BMP"); } } else return epuc("bad BMP", "bad BMP"); } } else { assert(hsz == 108); mr = get32le(s); mg = get32le(s); mb = get32le(s); ma = get32le(s); get32le(s); // discard color space for (i=0; i < 12; ++i) get32le(s); // discard color space parameters } if (bpp < 16) psize = (offset - 14 - hsz) >> 2; } s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert out = (stbi_uc *) malloc(target * s->img_x * s->img_y); if (!out) return epuc("outofmem", "Out of memory"); if (bpp < 16) { int z=0; if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = get8u(s); pal[i][1] = get8u(s); pal[i][0] = get8u(s); if (hsz != 12) get8(s); pal[i][3] = 255; } skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4)); if (bpp == 4) width = (s->img_x + 1) >> 1; else if (bpp == 8) width = s->img_x; else { free(out); return epuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; for (j=0; j < (int) s->img_y; ++j) { for (i=0; i < (int) s->img_x; i += 2) { int v=get8(s),v2=0; if (bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; v = (bpp == 8) ? get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } skip(s, pad); } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; skip(s, offset - 14 - hsz); if (bpp == 24) width = 3 * s->img_x; else if (bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; if (bpp == 24) { easy = 1; } else if (bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { free(out); return epuc("bad masks", "Corrupt BMP"); } // right shift amt to put high bit in position #7 rshift = high_bit(mr)-7; rcount = bitcount(mr); gshift = high_bit(mg)-7; gcount = bitcount(mr); bshift = high_bit(mb)-7; bcount = bitcount(mr); ashift = high_bit(ma)-7; acount = bitcount(mr); } for (j=0; j < (int) s->img_y; ++j) { if (easy) { for (i=0; i < (int) s->img_x; ++i) { int a; out[z+2] = get8u(s); out[z+1] = get8u(s); out[z+0] = get8u(s); z += 3; a = (easy == 2 ? get8(s) : 255); if (target == 4) out[z++] = (uint8) a; } } else { for (i=0; i < (int) s->img_x; ++i) { uint32 v = (bpp == 16 ? get16le(s) : get32le(s)); int a; out[z++] = (uint8) shiftsigned(v & mr, rshift, rcount); out[z++] = (uint8) shiftsigned(v & mg, gshift, gcount); out[z++] = (uint8) shiftsigned(v & mb, bshift, bcount); a = (ma ? shiftsigned(v & ma, ashift, acount) : 255); if (target == 4) out[z++] = (uint8) a; } } skip(s, pad); } } if (flip_vertically) { stbi_uc t; for (j=0; j < (int) s->img_y>>1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { t = p1[i], p1[i] = p2[i], p2[i] = t; } } } if (req_comp && req_comp != target) { out = convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; return out; } static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp) { return bmp_load(s, x,y,comp,req_comp); } // Targa Truevision - TGA // by Jonathan Dummer static int tga_info(stbi *s, int *x, int *y, int *comp) { int tga_w, tga_h, tga_comp; int sz; get8u(s); // discard Offset sz = get8u(s); // color type if( sz > 1 ) { stbi_rewind(s); return 0; // only RGB or indexed allowed } sz = get8u(s); // image type // only RGB or grey allowed, +/- RLE if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0; skip(s,9); tga_w = get16le(s); if( tga_w < 1 ) { stbi_rewind(s); return 0; // test width } tga_h = get16le(s); if( tga_h < 1 ) { stbi_rewind(s); return 0; // test height } sz = get8(s); // bits per pixel // only RGB or RGBA or grey allowed if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) { stbi_rewind(s); return 0; } tga_comp = sz; if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp / 8; return 1; // seems to have passed everything } int stbi_tga_info(stbi *s, int *x, int *y, int *comp) { return tga_info(s, x, y, comp); } static int tga_test(stbi *s) { int sz; get8u(s); // discard Offset sz = get8u(s); // color type if ( sz > 1 ) return 0; // only RGB or indexed allowed sz = get8u(s); // image type if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE get16(s); // discard palette start get16(s); // discard palette length get8(s); // discard bits per palette color entry get16(s); // discard x origin get16(s); // discard y origin if ( get16(s) < 1 ) return 0; // test width if ( get16(s) < 1 ) return 0; // test height sz = get8(s); // bits per pixel if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed return 1; // seems to have passed everything } static int stbi_tga_test(stbi *s) { int res = tga_test(s); stbi_rewind(s); return res; } static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp) { // read in the TGA header stuff int tga_offset = get8u(s); int tga_indexed = get8u(s); int tga_image_type = get8u(s); int tga_is_RLE = 0; int tga_palette_start = get16le(s); int tga_palette_len = get16le(s); int tga_palette_bits = get8u(s); int tga_x_origin = get16le(s); int tga_y_origin = get16le(s); int tga_width = get16le(s); int tga_height = get16le(s); int tga_bits_per_pixel = get8u(s); int tga_inverted = get8u(s); // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4]; unsigned char trans_data[4]; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } /* int tga_alpha_bits = tga_inverted & 15; */ tga_inverted = 1 - ((tga_inverted >> 5) & 1); // error check if ( //(tga_indexed) || (tga_width < 1) || (tga_height < 1) || (tga_image_type < 1) || (tga_image_type > 3) || ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) && (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32)) ) { return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA } // If I'm paletted, then I'll use the number of bits from the palette if ( tga_indexed ) { tga_bits_per_pixel = tga_palette_bits; } // tga info *x = tga_width; *y = tga_height; if ( (req_comp < 1) || (req_comp > 4) ) { // just use whatever the file was req_comp = tga_bits_per_pixel / 8; *comp = req_comp; } else { // force a new number of components *comp = tga_bits_per_pixel/8; } tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp ); if (!tga_data) return epuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) skip(s, tga_offset ); // do I need to load a palette? if ( tga_indexed ) { // any data to skip? (offset usually = 0) skip(s, tga_palette_start ); // load the palette tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 ); if (!tga_palette) return epuc("outofmem", "Out of memory"); if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) { free(tga_data); free(tga_palette); return epuc("bad palette", "Corrupt TGA"); } } // load the data trans_data[0] = trans_data[1] = trans_data[2] = trans_data[3] = 0; for (i=0; i < tga_width * tga_height; ++i) { // if I'm in RLE mode, do I need to get a RLE chunk? if ( tga_is_RLE ) { if ( RLE_count == 0 ) { // yep, get the next byte as a RLE command int RLE_cmd = get8u(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if ( !RLE_repeating ) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if ( read_next_pixel ) { // load however much data we did have if ( tga_indexed ) { // read in 1 byte, then perform the lookup int pal_idx = get8u(s); if ( pal_idx >= tga_palette_len ) { // invalid index pal_idx = 0; } pal_idx *= tga_bits_per_pixel / 8; for (j = 0; j*8 < tga_bits_per_pixel; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } } else { // read in the data raw for (j = 0; j*8 < tga_bits_per_pixel; ++j) { raw_data[j] = get8u(s); } } // convert raw to the intermediate format switch (tga_bits_per_pixel) { case 8: // Luminous => RGBA trans_data[0] = raw_data[0]; trans_data[1] = raw_data[0]; trans_data[2] = raw_data[0]; trans_data[3] = 255; break; case 16: // Luminous,Alpha => RGBA trans_data[0] = raw_data[0]; trans_data[1] = raw_data[0]; trans_data[2] = raw_data[0]; trans_data[3] = raw_data[1]; break; case 24: // BGR => RGBA trans_data[0] = raw_data[2]; trans_data[1] = raw_data[1]; trans_data[2] = raw_data[0]; trans_data[3] = 255; break; case 32: // BGRA => RGBA trans_data[0] = raw_data[2]; trans_data[1] = raw_data[1]; trans_data[2] = raw_data[0]; trans_data[3] = raw_data[3]; break; } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // convert to final format switch (req_comp) { case 1: // RGBA => Luminance tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]); break; case 2: // RGBA => Luminance,Alpha tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]); tga_data[i*req_comp+1] = trans_data[3]; break; case 3: // RGBA => RGB tga_data[i*req_comp+0] = trans_data[0]; tga_data[i*req_comp+1] = trans_data[1]; tga_data[i*req_comp+2] = trans_data[2]; break; case 4: // RGBA => RGBA tga_data[i*req_comp+0] = trans_data[0]; tga_data[i*req_comp+1] = trans_data[1]; tga_data[i*req_comp+2] = trans_data[2]; tga_data[i*req_comp+3] = trans_data[3]; break; } // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if ( tga_inverted ) { for (j = 0; j*2 < tga_height; ++j) { int index1 = j * tga_width * req_comp; int index2 = (tga_height - 1 - j) * tga_width * req_comp; for (i = tga_width * req_comp; i > 0; --i) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if ( tga_palette != NULL ) { free( tga_palette ); } // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; // OK, done return tga_data; } static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp) { return tga_load(s,x,y,comp,req_comp); } // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB static int psd_test(stbi *s) { if (get32(s) != 0x38425053) return 0; // "8BPS" else return 1; } static int stbi_psd_test(stbi *s) { int r = psd_test(s); stbi_rewind(s); return r; } static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp) { int pixelCount; int channelCount, compression; int channel, i, count, len; int w,h; uint8 *out; // Check identifier if (get32(s) != 0x38425053) // "8BPS" return epuc("not PSD", "Corrupt PSD image"); // Check file type version. if (get16(s) != 1) return epuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. skip(s, 6 ); // Read the number of channels (R, G, B, A, etc). channelCount = get16(s); if (channelCount < 0 || channelCount > 16) return epuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = get32(s); w = get32(s); // Make sure the depth is 8 bits. if (get16(s) != 8) return epuc("unsupported bit depth", "PSD bit depth is not 8 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (get16(s) != 3) return epuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) skip(s,get32(s) ); // Skip the image resources. (resolution, pen tool paths, etc) skip(s, get32(s) ); // Skip the reserved data. skip(s, get32(s) ); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = get16(s); if (compression > 1) return epuc("bad compression", "PSD has an unknown compression format"); // Create the destination image. out = (stbi_uc *) malloc(4 * w*h); if (!out) return epuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, // which we're going to just skip. skip(s, h * channelCount * 2 ); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { uint8 *p; p = out+channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4; } else { // Read the RLE data. count = 0; while (count < pixelCount) { len = get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; count += len; while (len) { *p = get8u(s); p += 4; len--; } } else if (len > 128) { uint8 val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len ^= 0x0FF; len += 2; val = get8u(s); count += len; while (len) { *p = val; p += 4; len--; } } } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { uint8 *p; p = out + channel; if (channel > channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4; } else { // Read the data. for (i = 0; i < pixelCount; i++) *p = get8u(s), p += 4; } } } if (req_comp && req_comp != 4) { out = convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // convert_format frees input on failure } if (comp) *comp = channelCount; *y = h; *x = w; return out; } static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp) { return psd_load(s,x,y,comp,req_comp); } // ************************************************************************************************* // Softimage PIC loader // by Tom Seddon // // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ static int pic_is4(stbi *s,const char *str) { int i; for (i=0; i<4; ++i) if (get8(s) != (stbi_uc)str[i]) return 0; return 1; } static int pic_test(stbi *s) { int i; if (!pic_is4(s,"\x53\x80\xF6\x34")) return 0; for(i=0;i<84;++i) get8(s); if (!pic_is4(s,"PICT")) return 0; return 1; } typedef struct { stbi_uc size,type,channel; } pic_packet_t; static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest) { int mask=0x80, i; for (i=0; i<4; ++i, mask>>=1) { if (channel & mask) { if (at_eof(s)) return epuc("bad file","PIC file too short"); dest[i]=get8u(s); } } return dest; } static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src) { int mask=0x80,i; for (i=0;i<4; ++i, mask>>=1) if (channel&mask) dest[i]=src[i]; } static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result) { int act_comp=0,num_packets=0,y,chained; pic_packet_t packets[10]; // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. do { pic_packet_t *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return epuc("bad format","too many packets"); packet = &packets[num_packets++]; chained = get8(s); packet->size = get8u(s); packet->type = get8u(s); packet->channel = get8u(s); act_comp |= packet->channel; if (at_eof(s)) return epuc("bad file","file too short (reading packets)"); if (packet->size != 8) return epuc("bad format","packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? for(y=0; y<height; ++y) { int packet_idx; for(packet_idx=0; packet_idx < num_packets; ++packet_idx) { pic_packet_t *packet = &packets[packet_idx]; stbi_uc *dest = result+y*width*4; switch (packet->type) { default: return epuc("bad format","packet has bad compression type"); case 0: {//uncompressed int x; for(x=0;x<width;++x, dest+=4) if (!pic_readval(s,packet->channel,dest)) return 0; break; } case 1://Pure RLE { int left=width, i; while (left>0) { stbi_uc count,value[4]; count=get8u(s); if (at_eof(s)) return epuc("bad file","file too short (pure read count)"); if (count > left) count = (uint8) left; if (!pic_readval(s,packet->channel,value)) return 0; for(i=0; i<count; ++i,dest+=4) pic_copyval(packet->channel,dest,value); left -= count; } } break; case 2: {//Mixed RLE int left=width; while (left>0) { int count = get8(s), i; if (at_eof(s)) return epuc("bad file","file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; int i; if (count==128) count = get16(s); else count -= 127; if (count > left) return epuc("bad file","scanline overrun"); if (!pic_readval(s,packet->channel,value)) return 0; for(i=0;i<count;++i, dest += 4) pic_copyval(packet->channel,dest,value); } else { // Raw ++count; if (count>left) return epuc("bad file","scanline overrun"); for(i=0;i<count;++i, dest+=4) if (!pic_readval(s,packet->channel,dest)) return 0; } left-=count; } break; } } } } return result; } static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp) { stbi_uc *result; int i, x,y; for (i=0; i<92; ++i) get8(s); x = get16(s); y = get16(s); if (at_eof(s)) return epuc("bad file","file too short (pic header)"); if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode"); get32(s); //skip `ratio' get16(s); //skip `fields' get16(s); //skip `pad' // intermediate buffer is RGBA result = (stbi_uc *) malloc(x*y*4); memset(result, 0xff, x*y*4); if (!pic_load2(s,x,y,comp, result)) { free(result); result=0; } *px = x; *py = y; if (req_comp == 0) req_comp = *comp; result=convert_format(result,4,req_comp,x,y); return result; } static int stbi_pic_test(stbi *s) { int r = pic_test(s); stbi_rewind(s); return r; } static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp) { return pic_load(s,x,y,comp,req_comp); } // ************************************************************************************************* // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb typedef struct stbi_gif_lzw_struct { int16 prefix; uint8 first; uint8 suffix; } stbi_gif_lzw; typedef struct stbi_gif_struct { int w,h; stbi_uc *out; // output buffer (always 4 components) int flags, bgindex, ratio, transparent, eflags; uint8 pal[256][4]; uint8 lpal[256][4]; stbi_gif_lzw codes[4096]; uint8 *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; } stbi_gif; static int gif_test(stbi *s) { int sz; if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0; sz = get8(s); if (sz != '9' && sz != '7') return 0; if (get8(s) != 'a') return 0; return 1; } static int stbi_gif_test(stbi *s) { int r = gif_test(s); stbi_rewind(s); return r; } static void stbi_gif_parse_colortable(stbi *s, uint8 pal[256][4], int num_entries, int transp) { int i; for (i=0; i < num_entries; ++i) { pal[i][2] = get8u(s); pal[i][1] = get8u(s); pal[i][0] = get8u(s); pal[i][3] = transp ? 0 : 255; } } static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info) { uint8 version; if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return e("not GIF", "Corrupt GIF"); version = get8u(s); if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF"); if (get8(s) != 'a') return e("not GIF", "Corrupt GIF"); failure_reason = ""; g->w = get16le(s); g->h = get16le(s); g->flags = get8(s); g->bgindex = get8(s); g->ratio = get8(s); g->transparent = -1; if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; if (g->flags & 0x80) stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); return 1; } static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp) { stbi_gif g; if (!stbi_gif_header(s, &g, comp, 1)) { stbi_rewind( s ); return 0; } if (x) *x = g.w; if (y) *y = g.h; return 1; } static void stbi_out_gif_code(stbi_gif *g, uint16 code) { uint8 *p, *c; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty if (g->codes[code].prefix >= 0) stbi_out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; p = &g->out[g->cur_x + g->cur_y]; c = &g->color_table[g->codes[code].suffix * 4]; if (c[3] >= 128) { p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } g->cur_x += 4; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g) { uint8 lzw_cs; int32 len, code; uint32 first; int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; stbi_gif_lzw *p; lzw_cs = get8u(s); clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (code = 0; code < clear; code++) { g->codes[code].prefix = -1; g->codes[code].first = (uint8) code; g->codes[code].suffix = (uint8) code; } // support no starting clear code avail = clear+2; oldcode = -1; len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = get8(s); // start new block if (len == 0) return g->out; } --len; bits |= (int32) get8(s) << valid_bits; valid_bits += 8; } else { int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? if (code == clear) { // clear code codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { // end of stream code skip(s, len); while ((len = get8(s)) > 0) skip(s,len); return g->out; } else if (code <= avail) { if (first) return epuc("no clear code", "Corrupt GIF"); if (oldcode >= 0) { p = &g->codes[avail++]; if (avail > 4096) return epuc("too many codes", "Corrupt GIF"); p->prefix = (int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) return epuc("illegal code in raster", "Corrupt GIF"); stbi_out_gif_code(g, (uint16) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { return epuc("illegal code in raster", "Corrupt GIF"); } } } } static void stbi_fill_gif_background(stbi_gif *g) { int i; uint8 *c = g->pal[g->bgindex]; // @OPTIMIZE: write a dword at a time for (i = 0; i < g->w * g->h * 4; i += 4) { uint8 *p = &g->out[i]; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } } // this function is designed to support animated gifs, although stb_image doesn't support it static uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp) { int i; uint8 *old_out = 0; if (g->out == 0) { if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header g->out = (uint8 *) malloc(4 * g->w * g->h); if (g->out == 0) return epuc("outofmem", "Out of memory"); stbi_fill_gif_background(g); } else { // animated-gif-only path if (((g->eflags & 0x1C) >> 2) == 3) { old_out = g->out; g->out = (uint8 *) malloc(4 * g->w * g->h); if (g->out == 0) return epuc("outofmem", "Out of memory"); memcpy(g->out, old_out, g->w*g->h*4); } } for (;;) { switch (get8(s)) { case 0x2C: /* Image Descriptor */ { int32 x, y, w, h; uint8 *o; x = get16le(s); y = get16le(s); w = get16le(s); h = get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) return epuc("bad Image Descriptor", "Corrupt GIF"); g->line_size = g->w * 4; g->start_x = x * 4; g->start_y = y * g->line_size; g->max_x = g->start_x + w * 4; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; g->lflags = get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; // first interlaced spacing g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (uint8 *) g->lpal; } else if (g->flags & 0x80) { for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent g->pal[i][3] = 255; if (g->transparent >= 0 && (g->eflags & 0x01)) g->pal[g->transparent][3] = 0; g->color_table = (uint8 *) g->pal; } else return epuc("missing color table", "Corrupt GIF"); o = stbi_process_gif_raster(s, g); if (o == NULL) return NULL; if (req_comp && req_comp != 4) o = convert_format(o, 4, req_comp, g->w, g->h); return o; } case 0x21: // Comment Extension. { int len; if (get8(s) == 0xF9) { // Graphic Control Extension. len = get8(s); if (len == 4) { g->eflags = get8(s); get16le(s); // delay g->transparent = get8(s); } else { skip(s, len); break; } } while ((len = get8(s)) != 0) skip(s, len); break; } case 0x3B: // gif stream termination code return (uint8 *) 1; default: return epuc("unknown code", "Corrupt GIF"); } } } static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp) { uint8 *u = 0; stbi_gif g={0}; u = stbi_gif_load_next(s, &g, comp, req_comp); if (u == (void *) 1) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; } return u; } static int stbi_gif_info(stbi *s, int *x, int *y, int *comp) { return stbi_gif_info_raw(s,x,y,comp); } // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int hdr_test(stbi *s) { const char *signature = "#?RADIANCE\n"; int i; for (i=0; signature[i]; ++i) if (get8(s) != signature[i]) return 0; return 1; } static int stbi_hdr_test(stbi* s) { int r = hdr_test(s); stbi_rewind(s); return r; } #define HDR_BUFLEN 1024 static char *hdr_gettoken(stbi *z, char *buffer) { int len=0; char c = '\0'; c = (char) get8(z); while (!at_eof(z) && c != '\n') { buffer[len++] = c; if (len == HDR_BUFLEN-1) { // flush to end of line while (!at_eof(z) && get8(z) != '\n') ; break; } c = (char) get8(z); } buffer[len] = 0; return buffer; } static void hdr_convert(float *output, stbi_uc *input, int req_comp) { if ( input[3] != 0 ) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp) { char buffer[HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; // Check identifier if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) return epf("not HDR", "Corrupt HDR image"); // Parse header for(;;) { token = hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return epf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format"); token += 3; height = strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format"); token += 3; width = strtol(token, NULL, 10); *x = width; *y = height; *comp = 3; if (req_comp == 0) req_comp = 3; // Read data hdr_data = (float *) malloc(height * width * req_comp * sizeof(float)); // Load image data // image data is stored as some number of sca if ( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: getn(s, rgbe, 4); hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = get8(s); c2 = get8(s); len = get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) uint8 rgbe[4]; rgbe[0] = (uint8) c1; rgbe[1] = (uint8) c2; rgbe[2] = (uint8) len; rgbe[3] = (uint8) get8u(s); hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; free(scanline); goto main_decode_loop; // yes, this makes no sense } len <<= 8; len |= get8(s); if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4); for (k = 0; k < 4; ++k) { i = 0; while (i < width) { count = get8u(s); if (count > 128) { // Run value = get8u(s); count -= 128; for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = get8u(s); } } } for (i=0; i < width; ++i) hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } free(scanline); } return hdr_data; } static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp) { return hdr_load(s,x,y,comp,req_comp); } static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp) { char buffer[HDR_BUFLEN]; char *token; int valid = 0; if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) { stbi_rewind( s ); return 0; } for(;;) { token = hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) { stbi_rewind( s ); return 0; } token = hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) { stbi_rewind( s ); return 0; } token += 3; *y = strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) { stbi_rewind( s ); return 0; } token += 3; *x = strtol(token, NULL, 10); *comp = 3; return 1; } #endif // STBI_NO_HDR static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp) { int hsz; if (get8(s) != 'B' || get8(s) != 'M') { stbi_rewind( s ); return 0; } skip(s,12); hsz = get32le(s); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) { stbi_rewind( s ); return 0; } if (hsz == 12) { *x = get16le(s); *y = get16le(s); } else { *x = get32le(s); *y = get32le(s); } if (get16le(s) != 1) { stbi_rewind( s ); return 0; } *comp = get16le(s) / 8; return 1; } static int stbi_psd_info(stbi *s, int *x, int *y, int *comp) { int channelCount; if (get32(s) != 0x38425053) { stbi_rewind( s ); return 0; } if (get16(s) != 1) { stbi_rewind( s ); return 0; } skip(s, 6); channelCount = get16(s); if (channelCount < 0 || channelCount > 16) { stbi_rewind( s ); return 0; } *y = get32(s); *x = get32(s); if (get16(s) != 8) { stbi_rewind( s ); return 0; } if (get16(s) != 3) { stbi_rewind( s ); return 0; } *comp = 4; return 1; } static int stbi_pic_info(stbi *s, int *x, int *y, int *comp) { int act_comp=0,num_packets=0,chained; pic_packet_t packets[10]; skip(s, 92); *x = get16(s); *y = get16(s); if (at_eof(s)) return 0; if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { stbi_rewind( s ); return 0; } skip(s, 8); do { pic_packet_t *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return 0; packet = &packets[num_packets++]; chained = get8(s); packet->size = get8u(s); packet->type = get8u(s); packet->channel = get8u(s); act_comp |= packet->channel; if (at_eof(s)) { stbi_rewind( s ); return 0; } if (packet->size != 8) { stbi_rewind( s ); return 0; } } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); return 1; } static int stbi_info_main(stbi *s, int *x, int *y, int *comp) { if (stbi_jpeg_info(s, x, y, comp)) return 1; if (stbi_png_info(s, x, y, comp)) return 1; if (stbi_gif_info(s, x, y, comp)) return 1; if (stbi_bmp_info(s, x, y, comp)) return 1; if (stbi_psd_info(s, x, y, comp)) return 1; if (stbi_pic_info(s, x, y, comp)) return 1; #ifndef STBI_NO_HDR if (stbi_hdr_info(s, x, y, comp)) return 1; #endif // test tga last because it's a crappy test! if (stbi_tga_info(s, x, y, comp)) return 1; return e("unknown image type", "Image not of any known type, or corrupt"); } #ifndef STBI_NO_STDIO int stbi_info(char const *filename, int *x, int *y, int *comp) { FILE *f = fopen(filename, "rb"); int result; if (!f) return e("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); fclose(f); return result; } int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi s; long pos = ftell(f); start_file(&s, f); r = stbi_info_main(&s,x,y,comp); fseek(f,pos,SEEK_SET); return r; } #endif // !STBI_NO_STDIO int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) { stbi s; start_mem(&s,buffer,len); return stbi_info_main(&s,x,y,comp); } int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) { stbi s; start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi_info_main(&s,x,y,comp); } #endif // STBI_HEADER_FILE_ONLY /* revision history: 1.33 (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements 1.32 (2011-07-13) support for "info" function for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-uint8 to fix warnings 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf improvements reading from files on platforms with lock-heavy fgetc() minor perf improvements for jpeg deprecated type-specific functions so we'll get feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva) 1.21 fix use of 'uint8' in header (reported by jon blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in interlaced PNG corruption check (found by ryg) 1.18 2008-08-02 fix a threading bug (local mutable static) 1.17 support interlaced PNG 1.16 major bugfix - convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant 0.50 first released version */
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "random.h" #include <random> std::mt19937 g_prng; s32 RandomS32(const s32 min, const s32 max) { std::uniform_int_distribution<s32> dist(min, max); return dist(g_prng); } float RandomF32(const float min, const float max) { std::uniform_real_distribution<float> dist(min, max); return dist(g_prng); } glm::vec3 RandomColour() { std::uniform_real_distribution<float> dist(0.f, 1.f); return glm::vec3(dist(g_prng), dist(g_prng), dist(g_prng)); }
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_CONFIG_H_BEEN_INCLUDED #define HAS_CONFIG_H_BEEN_INCLUDED #include <string> struct Config { Config() : windowWidth(-1) , windowHeight(-1) , fullscreen(false) , threadpoolCount(6) , gridSize(0) , noiseSeed(0) , useShadows(true) , shadowMapSize(2048) { } int windowWidth, windowHeight; bool fullscreen; int threadpoolCount; int gridSize; int noiseSeed; bool useShadows; int shadowMapSize; }; bool Config_Load(Config& cfg, const std::string& filepath); #endif // HAS_CONFIG_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_VOLUME_H_BEEN_INCLUDED #define HAS_VOLUME_H_BEEN_INCLUDED #include <stdint.h> #include <unordered_map> #include <vector> #include <memory> #include <mutex> #include <functional> #include <glm/glm.hpp> using glm::vec3; using glm::ivec3; using glm::ivec2; #include "aabb.h" #include "volume_materials.h" #include "volume_constants.h" #include "lrucache.h" #include "pool_allocator.h" #include "clipmap.h" #include "frustum.h" #undef near #undef far // ---------------------------------------------------------------------------- const ivec3 ChunkMinForPosition(const ivec3& p); const ivec3 ChunkMinForPosition(const int x, const int y, const int z); // ---------------------------------------------------------------------------- class Volume { public: void initialise(const glm::ivec3& cameraPosition, const AABB& worldBounds); void destroy(); void updateChunkLOD(const glm::vec3& currentPos, const Frustum& frustum); // ---------------------------------------------------------------------------- std::vector<RenderMesh*> findVisibleMeshes(const Frustum& frustum) { return clipmap_.findVisibleNodes(frustum); } // ---------------------------------------------------------------------------- void applyCSGOperation( const vec3& origin, const glm::vec3& brushSize, const RenderShape renderShape, const int brushMaterial, const bool rotateToCamera, const bool isAddOperation); void processCSGOperations(); private: void Task_UpdateChunkLOD(const glm::vec3 currentPos, const Frustum frustum); void processCSGOperationsImpl(); Clipmap clipmap_; }; #endif // HAS_VOLUME_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#ifndef HAS_CLIPMAP_H_BEEN_INCLUDED #define HAS_CLIPMAP_H_BEEN_INCLUDED // ---------------------------------------------------------------------------- #include "octree.h" #include "aabb.h" #include "frustum.h" #include "physics.h" #include <unordered_set> #include <vector> #include <glm/glm.hpp> using glm::ivec3; using glm::vec3; class RenderMesh; // ---------------------------------------------------------------------------- struct ClipmapNode { ClipmapNode() { for (int i = 0; i < 8; i++) { children_[i] = nullptr; } } bool active_ = false; // TODO pack into size_? bool invalidated_ = false; bool empty_ = false; ivec3 min_; int size_ = -1; RenderMesh* renderMesh = nullptr; RenderMesh* seamMesh = nullptr; OctreeNode* seamNodes = nullptr; int numSeamNodes = 0; ClipmapNode* children_[8]; }; // ---------------------------------------------------------------------------- // maintain a separate octree of the currently 'active' nodes' meshes to allow // a separation of the rendering activity and the clipmap being updated struct ClipmapViewNode { ClipmapViewNode() { for (int i = 0; i < 8; i++) { children[i] = nullptr; } } ivec3 min; int size = -1; RenderMesh* mainMesh = nullptr; RenderMesh* seamMesh = nullptr; ClipmapViewNode* children[8]; }; // ---------------------------------------------------------------------------- const vec3 ColourForMinLeafSize(const int minLeafSize); // ---------------------------------------------------------------------------- class Clipmap; struct ClipmapCollisionNode; typedef SlabAllocator<ClipmapViewNode, 512> ClipmapViewNodeAlloc; struct ClipmapViewTree { ClipmapViewNode* root = nullptr; ClipmapViewNodeAlloc* allocator = nullptr; }; // ---------------------------------------------------------------------------- class Compute_MeshGenContext; class Clipmap { public: void initialise( const AABB& worldBounds); void clear(); std::vector<RenderMesh*> findVisibleNodes(const Frustum& frustum); ClipmapNode* findNode(const ivec3& min, const int size) const; std::vector<ClipmapNode*> findNodesOnPath(const ivec3& endNodeMin, const int endNodeSize); void update( const glm::vec3& cameraPosition, const Frustum& frustum); void updateRenderState(); ClipmapNode* findNodeContainingChunk(const ivec3& min) const; std::vector<ClipmapNode*> findActiveNodes(const ClipmapNode* node) const; ClipmapNode* findNodeForChunk(const glm::ivec3& min) const; void findIntersectingCollisionVolumes( const vec3& rayOrigin, const vec3& rayDir, std::vector<ivec3>& volumes, std::vector<vec3>& intersectPositions); std::vector<ClipmapNode*> findNodesInsideAABB( const AABB& aabb) const; void queueCSGOperation( const vec3& origin, const glm::vec3& brushSize, const RenderShape brushShape, const int brushMaterial, const bool isAddOperation); void processCSGOperations(); private: void constructTree(); void processCSGOperationsImpl(); void loadCollisionNodes( const std::vector<glm::ivec3>& requestedNodes, const std::vector<glm::ivec3>& requestedSeamNodes); ClipmapNode* root_ = nullptr; ClipmapViewTree viewTree_; AABB worldBounds_; Compute_MeshGenContext* clipmapMeshGen_ = nullptr; Compute_MeshGenContext* physicsMeshGen_ = nullptr; }; // ---------------------------------------------------------------------------- #endif // HAS_CLIPMAP_H_BEEN_INCLUDED
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }
#include "physics.h" #include "render.h" // TODO remove #include "camera.h" #include "timer.h" #include "volume_constants.h" #include "aabb.h" #include "slab_allocator.h" #include "double_buffer.h" #include "pool_allocator.h" #include "glm_hash.h" #include "threadpool.h" #include <btBulletCollisionCommon.h> #include <btBulletDynamicsCommon.h> #include <BulletCollision/NarrowPhaseCollision/btRaycastCallback.h> #include <BulletDynamics/Character/btKinematicCharacterController.h> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <stdio.h> #include <vector> #include <functional> #include <deque> #include <mutex> #include <thread> #include <condition_variable> #include <atomic> #include "sdl_wrapper.h" #include <Remotery.h> #include <unordered_map> using glm::vec3; using glm::vec4; using glm::ivec3; using glm::mat3; static const s16 PHYSICS_GROUP_WORLD = 1; static const s16 PHYSICS_GROUP_ACTOR = 2; static const s16 PHYSICS_GROUP_PLAYER = 4; static const s16 PHYSICS_FILTER_ALL = PHYSICS_GROUP_WORLD | PHYSICS_GROUP_ACTOR | PHYSICS_GROUP_PLAYER; static const s16 PHYSICS_FILTER_NOT_PLAYER = PHYSICS_FILTER_ALL & ~PHYSICS_GROUP_PLAYER; // ---------------------------------------------------------------------------- struct PhysicsBody { vec3 position; mat3 transform {1.f}; }; const int MAX_PHYSICS_BODY = 4 * 1024; btAlignedObjectArray<btRigidBody*> g_rigidBodies; PoolAllocator<PhysicsBody> g_bodyAlloc; std::mutex g_bodyMutex; // ---------------------------------------------------------------------------- struct PhysicsMeshData; struct WorldCollisionNode { ivec3 min; PhysicsMeshData* mainMesh = nullptr; PhysicsMeshData* seamMesh = nullptr; RenderMesh* renderMainMesh = nullptr; RenderMesh* renderSeamMesh = nullptr; }; SlabAllocator<WorldCollisionNode, 512> g_worldNodeAlloc; std::unordered_map<ivec3, WorldCollisionNode*> g_worldNodes; AABB g_worldBounds; DoubleBuffer<std::vector<RenderMesh*>> g_worldRenderMeshes; // ---------------------------------------------------------------------------- // i.e. 1 voxel is PHYSICS_SCALE meters const float PHYSICS_SCALE = 0.05f; template <typename T> T Scale_WorldToPhysics(const T& worldValue) { return worldValue * PHYSICS_SCALE; } template <typename T> T Scale_PhysicsToWorld(const T& worldValue) { return worldValue / PHYSICS_SCALE; } // ---------------------------------------------------------------------------- btBroadphaseInterface* g_broadphase = nullptr; btCollisionDispatcher* g_dispatcher = nullptr; btConstraintSolver* g_solver = nullptr; btDefaultCollisionConfiguration* g_collisionCfg = nullptr; btDiscreteDynamicsWorld* g_dynamicsWorld = nullptr; struct PhysicsMeshData { glm::vec4* vertices = nullptr; int numVertices = 0; int* triangles = nullptr; int numTriangles = 0; btTriangleIndexVertexArray* buffer = nullptr; btBvhTriangleMeshShape* shape = nullptr; btRigidBody* body = nullptr; }; const int MAX_PHYSICS_MESHES = 4 * 1024; PoolAllocator<PhysicsMeshData> g_meshAlloc; std::mutex g_meshAllocMutex; static PhysicsMeshData* AllocMeshData() { PhysicsMeshData* data = nullptr; { std::lock_guard<std::mutex> lock(g_meshAllocMutex); data = g_meshAlloc.alloc(); } *data = PhysicsMeshData(); return data; } static void FreeMeshData(PhysicsMeshData* meshData) { std::lock_guard<std::mutex> lock(g_meshAllocMutex); g_meshAlloc.free(meshData); } vec3 g_rayHitPosition[2]; vec3 g_rayHitNormal[2]; std::atomic<int> g_rayHitPositionCounter = 0; // ---------------------------------------------------------------------------- typedef std::function<void(void)> PhysicsOperation; typedef std::deque<PhysicsOperation> PhysicsOperationQueue; PhysicsOperationQueue g_operationQueue; std::mutex g_operationMutex; enum PhysicsOperationType { PhysicsOp_RayCast, PhysicsOp_WorldUpdate }; void EnqueuePhysicsOperation(const PhysicsOperationType opType, const PhysicsOperation& op) { std::lock_guard<std::mutex> lock(g_operationMutex); g_operationQueue.push_back(op); } // ---------------------------------------------------------------------------- const float PLAYER_WIDTH = 48.f; const float PLAYER_HEIGHT = 120.f - PLAYER_WIDTH; // the capsule height is (2 * radius + height) struct Player { btRigidBody* body = nullptr; btPairCachingGhostObject* ghost = nullptr; vec3 velocity; bool falling = true; bool noclip = false; bool jump = false; }; Player g_player; // ---------------------------------------------------------------------------- void SpawnPlayerImpl(const glm::vec3& origin) { LVN_ASSERT(g_player.body == nullptr); LVN_ASSERT(g_player.ghost == nullptr); if (g_player.body || g_player.ghost) { return; } btCapsuleShape* collisionShape = new btCapsuleShape( Scale_WorldToPhysics(PLAYER_WIDTH / 2), Scale_WorldToPhysics(PLAYER_HEIGHT)); btTransform transform; transform.setIdentity(); transform.setOrigin(Scale_WorldToPhysics(btVector3(origin.x, origin.y, origin.z))); const float mass = 10.f; btVector3 ineritia; btMotionState* motionState = new btDefaultMotionState(transform); collisionShape->calculateLocalInertia(mass, ineritia); btRigidBody::btRigidBodyConstructionInfo bodyInfo(mass, motionState, collisionShape, ineritia); bodyInfo.m_friction = 0.5f; bodyInfo.m_restitution = 0.f; bodyInfo.m_linearDamping = 0.f; g_player.body = new btRigidBody(bodyInfo); g_player.body->setActivationState(DISABLE_DEACTIVATION); g_player.body->setAngularFactor(0.f); g_dynamicsWorld->addRigidBody(g_player.body, PHYSICS_GROUP_PLAYER, PHYSICS_FILTER_ALL); g_player.ghost = new btPairCachingGhostObject; g_player.ghost->setCollisionShape(collisionShape); g_player.ghost->setCollisionFlags(btCollisionObject::CF_NO_CONTACT_RESPONSE); g_player.ghost->setWorldTransform(transform); g_dynamicsWorld->addCollisionObject(g_player.ghost, PHYSICS_GROUP_PLAYER, PHYSICS_FILTER_NOT_PLAYER); g_dynamicsWorld->getPairCache()->setInternalGhostPairCallback(new btGhostPairCallback()); } // ---------------------------------------------------------------------------- void UpdatePlayer(const float deltaT, const float elapsedTime) { rmt_ScopedCPUSample(UpdatePlayer); if (!g_player.body || !g_player.ghost) { return; } btVector3 origin = g_player.body->getWorldTransform().getOrigin(); // origin = g_player.body->getCenterOfMassPosition(); const float bottomOffset = (PLAYER_WIDTH / 2.f) + (PLAYER_HEIGHT / 2.f); const btVector3 rayEnd = origin - Scale_WorldToPhysics(btVector3(0.f, bottomOffset + 0.f, 0.f)); btCollisionWorld::ClosestRayResultCallback callback(origin, rayEnd); g_dynamicsWorld->rayTest(origin, rayEnd, callback); bool onGround = false; float onGroundDot = 0.f; auto pairs = g_player.ghost->getOverlappingPairCache()->getOverlappingPairArray(); btManifoldArray manifolds; for (int i = 0; i < pairs.size(); i++) { manifolds.clear(); const auto& p = pairs[i]; btBroadphasePair* pair = g_dynamicsWorld->getPairCache()->findPair(p.m_pProxy0, p.m_pProxy1); if (!pair) { continue; } if (pair->m_algorithm) { pair->m_algorithm->getAllContactManifolds(manifolds); } for (int j = 0; j < manifolds.size(); j++) { auto* m = manifolds[j]; const bool isFirstBody = m->getBody0() == g_player.ghost; const float dir = isFirstBody ? -1.f : 1.f; for (int c = 0; c < m->getNumContacts(); c++) { const auto& pt = m->getContactPoint(c); if (pt.getDistance() <= 1e-3) { const btVector3 p = isFirstBody ? pt.getPositionWorldOnA() : pt.getPositionWorldOnB(); const btVector3 d = (origin - p).normalize(); onGroundDot = glm::max(onGroundDot, d.dot(btVector3(0.f, 1.f, 0.f))); } } } } static float checkGroundTime = 0.f; if (g_player.falling && checkGroundTime < elapsedTime) { if (onGroundDot > 0.85f) { onGround = true; g_player.falling = false; } } /* printf("onGroundDot=%.2f falling=%s\n", onGroundDot, g_player.falling ? "True" : "False"); */ const btVector3 currentVelocty = g_player.body->getLinearVelocity(); vec3 inputVelocity = g_player.velocity * 750.f; if (!g_player.noclip) { float velocity = currentVelocty.y(); if (!g_player.falling) { velocity = glm::min(0.f, velocity) - (10 * deltaT); } if (!g_player.falling && g_player.jump) { // printf("jump\n"); g_player.body->applyCentralImpulse(btVector3(0, 65, 0)); g_player.jump = false; g_player.falling = true; checkGroundTime = elapsedTime + 0.1f; } else { g_player.body->setLinearVelocity(btVector3(inputVelocity.x, velocity, inputVelocity.z)); } } else { g_player.body->setLinearVelocity(btVector3(inputVelocity.x, inputVelocity.y, inputVelocity.z)); } g_player.ghost->getWorldTransform().setOrigin(g_player.body->getWorldTransform().getOrigin()); } // ---------------------------------------------------------------------------- std::thread g_physicsThread; bool g_physicsQuit = false; void PhysicsThreadFunction() { u32 prevTime = SDL_GetTicks(); const float startTime = (float)prevTime / 1000.f; bool dirty = false; while (!g_physicsQuit) { PhysicsOperationQueue queuedOperations; { std::lock_guard<std::mutex> lock(g_operationMutex); queuedOperations = g_operationQueue; g_operationQueue.clear(); } for (auto& op: queuedOperations) { dirty = true; op(); } const u32 deltaTime = SDL_GetTicks() - prevTime; const float dt = deltaTime / 1000.f; const float updatePeriod = 1 / 60.f; if (dt < updatePeriod) { continue; } prevTime = SDL_GetTicks(); const float elapsedTime = ((float)prevTime / 1000.f) - startTime; { rmt_ScopedCPUSample(Physics_BulletStep); g_dynamicsWorld->stepSimulation(dt); } if (dirty) { std::vector<RenderMesh*>* meshes = g_worldRenderMeshes.next(); meshes->clear(); meshes->reserve(g_worldNodes.size()); for (const auto& pair: g_worldNodes) { const WorldCollisionNode* node = pair.second; if (node) { if (node->renderMainMesh) { meshes->push_back(node->renderMainMesh); } if (node->renderSeamMesh) { meshes->push_back(node->renderSeamMesh); } } } g_worldRenderMeshes.increment(); dirty = false; } { rmt_ScopedCPUSample(UpdateBodies); for (int i = 0; i < g_rigidBodies.size(); i++) { btRigidBody* body = g_rigidBodies[i]; LVN_ASSERT(body); PhysicsBody* physicsBody = (PhysicsBody*)body->getUserPointer(); LVN_ASSERT(physicsBody); const btTransform& transform = body->getInterpolationWorldTransform(); const btVector3& o = transform.getOrigin(); physicsBody->position = Scale_PhysicsToWorld(vec3(o.x(), o.y(), o.z())); btScalar matrix[4][4]; transform.getOpenGLMatrix(&matrix[0][0]); physicsBody->transform = mat3( vec3(matrix[0][0], matrix[0][1], matrix[0][2]), vec3(matrix[1][0], matrix[1][1], matrix[1][2]), vec3(matrix[2][0], matrix[2][1], matrix[2][2])); } } UpdatePlayer(dt, elapsedTime); } } // ---------------------------------------------------------------------------- void InitialiseWorldNodes() { for (int x = g_worldBounds.min.x; x < g_worldBounds.max.x; x += COLLISION_NODE_SIZE) for (int y = g_worldBounds.min.y; y < g_worldBounds.max.y; y += COLLISION_NODE_SIZE) for (int z = g_worldBounds.min.z; z < g_worldBounds.max.z; z += COLLISION_NODE_SIZE) { WorldCollisionNode* node = g_worldNodeAlloc.alloc(); node->min = ivec3(x, y, z); LVN_ASSERT(g_worldNodes.find(node->min) == end(g_worldNodes)); g_worldNodes[node->min] = node; } } // ---------------------------------------------------------------------------- void ReleaseWorldNodes() { for (auto pair: g_worldNodes) { WorldCollisionNode* node = pair.second; FreeMeshData(node->mainMesh); FreeMeshData(node->seamMesh); if (node->renderMainMesh) Render_FreeRenderMesh(&node->renderMainMesh); if (node->renderSeamMesh) Render_FreeRenderMesh(&node->renderSeamMesh); } g_worldNodes.clear(); g_worldNodeAlloc.clear(); } // ---------------------------------------------------------------------------- bool Physics_Initialise(const AABB& worldBounds) { g_worldBounds = worldBounds; g_meshAlloc.initialise(MAX_PHYSICS_MESHES); btDefaultCollisionConstructionInfo cci; cci.m_defaultMaxPersistentManifoldPoolSize = 1 << 15; g_collisionCfg = new btDefaultCollisionConfiguration(cci); g_dispatcher = new btCollisionDispatcher(g_collisionCfg); btHashedOverlappingPairCache* pairCache = new btHashedOverlappingPairCache; const btVector3 worldMin = btVector3(g_worldBounds.min.x, g_worldBounds.min.y, g_worldBounds.min.z); const btVector3 worldMax = btVector3(g_worldBounds.max.x, g_worldBounds.max.y, g_worldBounds.max.z); const short maxHandles = 3500; g_broadphase = new btAxisSweep3(Scale_WorldToPhysics(worldMin), Scale_WorldToPhysics(worldMax), maxHandles, pairCache); g_solver = new btSequentialImpulseConstraintSolver; g_dynamicsWorld = new btDiscreteDynamicsWorld(g_dispatcher, g_broadphase, g_solver, g_collisionCfg); g_dynamicsWorld->setGravity(btVector3(0, -9.8f, 0)); g_dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_ENABLE_FRICTION_DIRECTION_CACHING; g_dynamicsWorld->getSolverInfo().m_numIterations = 5; g_physicsQuit = false; g_physicsThread = std::thread(PhysicsThreadFunction); InitialiseWorldNodes(); g_bodyAlloc.initialise(MAX_PHYSICS_BODY); return true; } // ---------------------------------------------------------------------------- void Physics_Shutdown() { { std::lock_guard<std::mutex> lock(g_operationMutex); g_operationQueue.clear(); } g_physicsQuit = true; g_physicsThread.join(); g_dynamicsWorld->removeRigidBody(g_player.body); g_dynamicsWorld->removeCollisionObject(g_player.ghost); delete g_player.body; delete g_player.ghost; g_player = Player(); g_worldRenderMeshes.clear(); for (int i = 0; i < g_rigidBodies.size(); i++) { delete g_rigidBodies[i]; } g_rigidBodies.clear(); g_bodyAlloc.clear(); ReleaseWorldNodes(); g_meshAlloc.clear(); delete g_dynamicsWorld; g_dynamicsWorld = nullptr; delete g_solver; g_solver = nullptr; delete g_broadphase; g_broadphase = nullptr; delete g_dispatcher; g_dispatcher = nullptr; delete g_collisionCfg; g_collisionCfg = nullptr; } // ---------------------------------------------------------------------------- std::vector<RenderMesh*> Physics_GetRenderData(const Frustum& frustum) { // Important that we return a COPY here not the actual collection return *g_worldRenderMeshes.current(); } // ---------------------------------------------------------------------------- void AddMeshToWorldImpl(const glm::vec3& origin, MeshBuffer* buffer, PhysicsMeshData* meshData) { rmt_ScopedCPUSample(Physics_AddMeshToWorld); // TODO meshData->vertices and meshData->triangles should be created on the GPU { rmt_ScopedCPUSample(Copy); LVN_ASSERT(!meshData->vertices); LVN_ASSERT(meshData->numVertices == 0); meshData->vertices = new vec4[buffer->numVertices]; meshData->numVertices = buffer->numVertices; const vec4 offset(origin, 0.f); for (int i = 0; i < buffer->numVertices; i++) { meshData->vertices[i] = Scale_WorldToPhysics(buffer->vertices[i].xyz - offset); } LVN_ASSERT(!meshData->triangles); LVN_ASSERT(meshData->numTriangles == 0); meshData->triangles = new int[buffer->numTriangles * 3]; meshData->numTriangles = buffer->numTriangles; memcpy(meshData->triangles, buffer->triangles, sizeof(int) * 3 * buffer->numTriangles); } { rmt_ScopedCPUSample(Bullet); btIndexedMesh indexedMesh; indexedMesh.m_vertexBase = (const unsigned char*)&meshData->vertices[0]; indexedMesh.m_vertexStride = sizeof(vec4); indexedMesh.m_numVertices = meshData->numVertices; indexedMesh.m_triangleIndexBase = (const unsigned char*)&meshData->triangles[0]; indexedMesh.m_triangleIndexStride = sizeof(int) * 3; indexedMesh.m_numTriangles = meshData->numTriangles; indexedMesh.m_indexType = PHY_INTEGER; meshData->buffer = new btTriangleIndexVertexArray; meshData->buffer->addIndexedMesh(indexedMesh); meshData->shape = new btBvhTriangleMeshShape(meshData->buffer, true, true); const float mass = 0.f; meshData->body = new btRigidBody(mass, nullptr, meshData->shape); meshData->body->setFriction(0.9f); btTransform transform; transform.setIdentity(); transform.setOrigin(Scale_WorldToPhysics(btVector3(origin.x, origin.y, origin.z))); meshData->body->setWorldTransform(transform); meshData->body->setCollisionFlags(meshData->body->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT); } } // ---------------------------------------------------------------------------- void RemoveMeshData(PhysicsMeshData* meshData) { rmt_ScopedCPUSample(RemoveMeshData); LVN_ASSERT(meshData); LVN_ASSERT(std::this_thread::get_id() == g_physicsThread.get_id()); g_dynamicsWorld->removeRigidBody(meshData->body); delete meshData->body; meshData->body = nullptr; delete meshData->shape; meshData->shape = nullptr; delete meshData->buffer; meshData->buffer = nullptr; delete[] meshData->vertices; meshData->vertices = nullptr; meshData->numVertices = 0; delete[] meshData->triangles; meshData->triangles = nullptr; meshData->numTriangles = 0; } // ---------------------------------------------------------------------------- void ReplaceCollisionNodeMesh( const bool replaceMainMesh, WorldCollisionNode* node, PhysicsMeshData* newMesh) { rmt_ScopedCPUSample(ReplaceCollisionMeshes); LVN_ASSERT(std::this_thread::get_id() == g_physicsThread.get_id()); PhysicsMeshData* oldMesh = nullptr; if (replaceMainMesh) { oldMesh = node->mainMesh; node->mainMesh = newMesh; } else { oldMesh = node->seamMesh; node->seamMesh = newMesh; } if (newMesh) { g_dynamicsWorld->addRigidBody(newMesh->body, PHYSICS_GROUP_WORLD, PHYSICS_FILTER_ALL); } if (oldMesh) { RemoveMeshData(oldMesh); FreeMeshData(oldMesh); } { rmt_ScopedCPUSample(ActivateeBodies); const AABB nodeBounds(node->min, COLLISION_NODE_SIZE); // TODO getting the lock here is terrible std::lock_guard<std::mutex> lock(g_bodyMutex); for (int i = 0; i < g_rigidBodies.size(); i++) { btRigidBody* body = g_rigidBodies[i]; LVN_ASSERT(body); PhysicsBody* physicsBody = (PhysicsBody*)body->getUserPointer(); LVN_ASSERT(physicsBody); if (nodeBounds.pointIsInside(ivec3(physicsBody->position))) { body->activate(); } } } } // ---------------------------------------------------------------------------- void UpdateCollisionNode(const bool updateMain, WorldCollisionNode* node, MeshBuffer* meshBuffer) { LVN_ASSERT(node); LVN_ASSERT(std::this_thread::get_id() == g_physicsThread.get_id()); ThreadPool_ScheduleJob([=]() { PhysicsMeshData* newMesh = nullptr; const vec3 origin = vec3(node->min + ivec3(COLLISION_NODE_SIZE) / 2); if (meshBuffer) { newMesh = AllocMeshData(); AddMeshToWorldImpl(origin, meshBuffer, newMesh); } if (updateMain) { node->renderMainMesh = Render_AllocRenderMesh("collision_main", meshBuffer, origin); if (!node->renderMainMesh) { Render_FreeMeshBuffer(meshBuffer); } } else { node->renderSeamMesh = Render_AllocRenderMesh("collision_seam", meshBuffer, origin); if (!node->renderSeamMesh) { Render_FreeMeshBuffer(meshBuffer); } } EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, std::bind(ReplaceCollisionNodeMesh, updateMain, node, newMesh)); }); } // ---------------------------------------------------------------------------- WorldCollisionNode* FindCollisionNode(const ivec3& min) { const auto iter = g_worldNodes.find(min); if (iter != end(g_worldNodes)) { return iter->second; } return nullptr; } // ---------------------------------------------------------------------------- void Physics_UpdateWorldNodeMainMesh( const ivec3& min, MeshBuffer* mainMesh) { if (!g_worldBounds.pointIsInside(min)) { Render_FreeMeshBuffer(mainMesh); return; } WorldCollisionNode* worldNode = FindCollisionNode(min); if (!worldNode) { printf("Error: Unable to find collision node for min [%d %d %d]\n", min.x, min.y, min.z); return; } EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, std::bind(UpdateCollisionNode, true, worldNode, mainMesh)); } // ---------------------------------------------------------------------------- void Physics_UpdateWorldNodeSeamMesh( const ivec3& min, MeshBuffer* seamMesh) { if (!g_worldBounds.pointIsInside(min)) { Render_FreeMeshBuffer(seamMesh); return; } WorldCollisionNode* worldNode = FindCollisionNode(min); if (!worldNode) { printf("Error: Unable to find collision node for min [%d %d %d]\n", min.x, min.y, min.z); return; } EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, std::bind(UpdateCollisionNode, false, worldNode, seamMesh)); } // ---------------------------------------------------------------------------- std::atomic<bool> g_rayCastPending = false; void CastRayImpl(const glm::vec3& start, const glm::vec3& end) { rmt_ScopedCPUSample(Physics_CastRay); LVN_ASSERT(std::this_thread::get_id() == g_physicsThread.get_id()); const btVector3 rayStart = Scale_WorldToPhysics(btVector3(start.x, start.y, start.z)); const btVector3 rayEnd = Scale_WorldToPhysics(btVector3(end.x, end.y, end.z)); btCollisionWorld::AllHitsRayResultCallback callback(rayStart, rayEnd); callback.m_flags |= btTriangleRaycastCallback::kF_FilterBackfaces; g_dynamicsWorld->rayTest(rayStart, rayEnd, callback); float minFraction = FLT_MAX; for (int i = 0; i < callback.m_collisionObjects.size(); i++) { const btCollisionObject* object = callback.m_collisionObjects[i]; if (callback.m_hitFractions[i] < minFraction && object->getCollisionFlags() & PHYSICS_GROUP_WORLD) { minFraction = callback.m_hitFractions[i]; const btVector3 p = callback.m_hitPointWorld[i]; const btVector3 n = callback.m_hitNormalWorld[i]; const int index = ++g_rayHitPositionCounter & 1; g_rayHitPosition[index] = Scale_PhysicsToWorld(vec3(p.x(), p.y(), p.z())); g_rayHitNormal[index] = glm::vec3(n.x(), n.y(), n.z()); } } g_rayCastPending = false; } void Physics_CastRay(const glm::vec3& start, const glm::vec3& end) { if (!g_rayCastPending) { g_rayCastPending = true; EnqueuePhysicsOperation(PhysicsOp_RayCast, std::bind(CastRayImpl, start, end)); } } vec3 Physics_LastHitPosition() { return g_rayHitPosition[g_rayHitPositionCounter & 1]; } vec3 Physics_LastHitNormal() { return g_rayHitNormal[g_rayHitPositionCounter & 1]; } // ---------------------------------------------------------------------------- btRigidBody* SpawnShape(btCollisionShape* shape, const float mass, const vec3& origin) { rmt_ScopedCPUSample(SpawnShape); btVector3 localInertia; shape->calculateLocalInertia(mass, localInertia); btTransform transform; transform.setIdentity(); transform.setOrigin(Scale_WorldToPhysics(btVector3(origin.x, origin.y, origin.z))); btRigidBody::btRigidBodyConstructionInfo info(mass, new btDefaultMotionState(transform), shape, localInertia); btRigidBody* body = new btRigidBody(info); body->setWorldTransform(transform); std::lock_guard<std::mutex> lock(g_bodyMutex); g_rigidBodies.push_back(body); return body; } // ---------------------------------------------------------------------------- PhysicsHandle Physics_SpawnSphere(const float radius, const float mass, const glm::vec3& origin) { PhysicsBody* body = nullptr; { std::lock_guard<std::mutex> lock(g_bodyMutex); body = g_bodyAlloc.alloc(); } if (body) { body->position = origin; btSphereShape* shape = new btSphereShape(Scale_WorldToPhysics(radius)); btRigidBody* rigidBody = SpawnShape(shape, mass, origin); rigidBody->setUserPointer(body); EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, [=]() { g_dynamicsWorld->addRigidBody(rigidBody, PHYSICS_GROUP_WORLD, PHYSICS_FILTER_ALL); }); return rigidBody; } return nullptr; } // ---------------------------------------------------------------------------- PhysicsHandle Physics_SpawnCube(const vec3& halfSize, const float mass, const glm::vec3& origin) { PhysicsBody* body = nullptr; { std::lock_guard<std::mutex> lock(g_bodyMutex); body = g_bodyAlloc.alloc(); } if (body) { body->position = origin; btBoxShape* shape = new btBoxShape(Scale_WorldToPhysics(btVector3(halfSize.x, halfSize.y, halfSize.z))); btRigidBody* rigidBody = SpawnShape(shape, mass, origin); rigidBody->setUserPointer(body); EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, [=]() { g_dynamicsWorld->addRigidBody(rigidBody, PHYSICS_GROUP_WORLD, PHYSICS_FILTER_ALL); }); return rigidBody; } return nullptr; } // ---------------------------------------------------------------------------- glm::vec3 PhysicsBody_GetPosition(PhysicsHandle handle) { if (!handle) { return vec3(0.f); } btRigidBody* body = (btRigidBody*)handle; PhysicsBody* physicsBody = (PhysicsBody*)body->getUserPointer(); LVN_ASSERT(physicsBody); return physicsBody->position; } // ---------------------------------------------------------------------------- glm::mat3 PhysicsBody_GetTransform(PhysicsHandle handle) { btRigidBody* body = (btRigidBody*)handle; PhysicsBody* physicsBody = (PhysicsBody*)body->getUserPointer(); LVN_ASSERT(physicsBody); return physicsBody->transform; } // ---------------------------------------------------------------------------- void FreeBodyImpl(btRigidBody* body) { LVN_ASSERT(body); LVN_ASSERT(std::this_thread::get_id() == g_physicsThread.get_id()); g_dynamicsWorld->removeRigidBody(body); delete body; } // ---------------------------------------------------------------------------- void PhysicsBody_Free(PhysicsHandle handle) { btRigidBody* body = (btRigidBody*)handle; PhysicsBody* physicsBody = (PhysicsBody*)body->getUserPointer(); LVN_ASSERT(physicsBody); { std::lock_guard<std::mutex> lock(g_bodyMutex); g_bodyAlloc.free(physicsBody); g_rigidBodies.remove(body); } EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, std::bind(FreeBodyImpl, body)); } // ---------------------------------------------------------------------------- void Physics_SpawnPlayer(const vec3& origin) { EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, std::bind(SpawnPlayerImpl, origin)); } // ---------------------------------------------------------------------------- vec3 Physics_GetPlayerPosition() { // TODO not thread safe if (g_player.body) { const btVector3 origin = g_player.body->getWorldTransform().getOrigin(); vec3 position = Scale_PhysicsToWorld(vec3(origin.x(), origin.y(), origin.z())); const float eyeOffset = (PLAYER_HEIGHT / 2.f) - 10.f; position.y += eyeOffset; return position; } return vec3(0.f); } // ---------------------------------------------------------------------------- void Physics_SetPlayerVelocity(const vec3& velocity) { EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, [=]() { g_player.velocity = velocity; }); } // ---------------------------------------------------------------------------- void Physics_PlayerJump() { EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, []() { g_player.jump = true; }); } // ---------------------------------------------------------------------------- void Physics_TogglePlayerNoClip() { printf("noclip\n"); EnqueuePhysicsOperation(PhysicsOp_WorldUpdate, []() { g_player.noclip = !g_player.noclip; }); } // ----------------------------------------------------------------------------
{ "repo_name": "nickgildea/leven", "stars": "102", "repo_language": "C++", "file_name": "skybox.vert", "mime_type": "text/x-c" }