Computing: различия между версиями

Материал из Dwarf Fortress Wiki
Перейти к навигацииПерейти к поиску
Нет описания правки
Строка 1: Строка 1:
{{elven}}
Компьютеризацией в '''Dwarf Fortress''' называют практику создания сложных механических устройств реализующих логические и численные операции. В идеале, это делается для автоматизации какой-либо функции вашей крепости. Пусть даже сейчас это уже и не новая идея, но она все ещё оставляет достаточно простора для улучшений и исследований. В том числе и по той причине, что одну и ту же проблему можно решить разными способами. Изобретения и усовершенствования только приветствуются!
=== Двоичная информация ===
Информация, представленная в двоичном виде, может принимать всего два состояния: истину или ложь, что соотвествует 1 или 0. В '''Dwarf Fortress''' эти состояния можно хранить разными способами:
* состояние вкл/выкл или сигнал от [[trigger|триггера]] (pressure plate, lever)
* запитанность энергией или состояние подключенния [[machine component|механизма]]
* закрытость или открытость [[door|двери]] или подобных ей обьектов
* нажата или отжата [[pressure plate|нажимная плита]]
* [[water|жидкость]] [[flow|движется или стоит]]
* наличие/отсутствие [[creature|существ]] или [[dwarf|дварфов]]
Это элементарное представление информации лежит в основе всех электронных устройств и компьютеров. Поэтому если уж вы захотели заняться компьютеростроением то с этим нужно обязательно ознакомиться. [http://ru.wikipedia.org/wiki/%D0%9B%D0%BE%D0%B3%D0%B8%D0%BA%D0%B0_%D0%B2%D1%8B%D1%81%D0%BA%D0%B0%D0%B7%D1%8B%D0%B2%D0%B0%D0%BD%D0%B8%D0%B9 Логика высказываний]
=== Ввод/вывод ===
Устройством ввода может служить любой механизм, который можно связать с другими устройствами. К такими механизмам относятся [[lever|рычаги]] и [[pressure plate|нажимные плиты]]. Нажимная плита, при её установке, может быть настроена, на какой вес воды, лавы и существ она должна реагировать. Так же её можно настроить так, чтобы она могла реагировать и на ваших дварфов тоже. Указав минимальное и максимальное значение уровня воды и лавы для нажимной плиты, вы всегда будете получать от нее состояние ВКЛ (on) для этого интервала, а для всех остальных значений — состояние ВЫКЛ (off). Независимо от уровня воды, лавы или веса существа, действующих на нажимную плиту, это устройство всегда будет посылать или 1 или 0 на другие "элементы" сети. А это значит, что нажимные плиты могут служить основой для двоичных запоминающих устройств.
==== Виды ввода ====
* Ручное переключение: [[lever|Рычаг]] -> двоичный 1 или 0.
* Автоматическое переключение: [[pressure plate|Нажимная плита]] -> двоичный 1 или 0.
В качестве ввода/вывода может служить все что угодно, что умеет реагировать на изменение сигнала. Это могут быть двери, мосты, шлюзы пропускающие или препятствующие течению жидкостей, шестерни связанные с насосами и многое другое. В некоторых случаях — когда используется [[mechanical logic|машинная логика]] — в качестве вывода требуется не сигнал ВКЛ/ВЫКЛ (on/off), а подключение/отключение механизмов от источника энергии.
Для обратного преобразования состояния подключенности к источнику энергии в сигнал ВКЛ/ВЫКЛ (on/off) известен (на данный момент) только один способ. Этот способ предполагает использование насоса с неограниченным источником воды и неограниченным сливом. Для обнаружения факта, включен ли насос (т.е.  подключен ли он к источнику энергии) используется нажимная плита размещенная у слива. Она реагирует на наличие потока перекачиваемой жидкости.
==== Виды вывода  ====
* сигнал: [[pressure plate|нажимная плита]] -> на выходе сигнал ВКЛ/ВЫКЛ (on/off) -> сигнал может поступать на все объекты обладающие способностью подлючаться к источнику сигнала и реагировать на его изменение
* энергия: [[gear assembly|комплекс шестерней]] -> на выходе энергия или её отсутствие (состояния подключен к источнику энергии / отключен от источника энергии) -> энергия может поступать на механизмы, потребляющие энергию
=== Бинарная логика ===
Операции бинарной логики осуществляют вычисление значения бита на выходе, полученного в результате некоторых операций со значениями одного или двух битов на входе. Устройства, которые умеют выполнять такие операции, обычно называют '''логическими вентилями'''<br />
* NOT — принимает на вход один бит и возвращает бит с противоположным значением<br /><br />
{| class="wikitable" border=1
|-
! вход A
! NOT
|-
| 0
| 1
|-
| 1
| 0
|}<br />
все остальные операции получают на вход два бита
* AND — возвращает true если они оба имеют значение true
* OR — возвращает true если хотя бы один из них имеет значение true
* XOR — возвращает true если только один из них имеет значение true
* NAND — возвращает true если как минимум один из них имеет значение false
* NOR — возвращает true если они оба имеют значение false
* NXOR — возвращает true если они оба имеют одинаковые значения<br /><br />
{| class="wikitable" border=1
|-
! вход A
! вход B
! AND
! OR
! XOR
! NAND
! NOR
! NXOR
|-
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 1
|-
| 0
| 1
| 0
| 1
| 1
| 1
| 0
| 0
|-
| 1
| 0
| 0
| 1
| 1
| 1
| 0
| 0
|-
| 1
| 1
| 1
| 1
| 0
| 0
| 0
| 1
|}<br />
Логические выражения, которые используют операции НЕ(NOT), И(AND) и ИЛИ(OR) наиболее легки для понимания человеком. Однако, оказывается, что все возможные логические операции можно реализовать используя только NAND или только NOR вентили. Некоторые логические вентили сделать проще и они потребуют меньше компонентов чем другие. Хотя это зависит от того, какой подход вы используете при построении логических схем. В общем случае, самостоятельное проектирование каждого логического вентиля, который вам действительно необходим (или использование уже придуманных схем) предпочтительнее, чем строительство множества NAND вентилей, так как в результате ваш '''дфарф'''путер будет и быстрее работать и потребует меньше ресурсов на его создание (энергии, воды, котят, строительных материалов и всего остального, что вы задумаете использовать).
=== Сложные вентили ===
* [[Latch|Latch]] — записывает и считывает одно двоичное значение.
* [[Repeater|Repeater]] — посылает перниодический сигнал.
* [[Counter|Counter]]/[[Adder|Adder]] — двоичные вычисления.
{{заготовка}}
== Disciplines ==
Historically, prior to DF2010 there have been 3 main disciplines of dwarfputing, depending on what would drive the dwarfputer. Each of them had its assets and drawbacks. So far, DF2010 at 0.31.01 appears to be essentially the same as far as power transmission goes, barring some differences with pump vertical power transmission (they don’t without the floor between being channeled, apparently). Science! will determine what, if anything, differs as far as water flow, falling, and animal pathfinding.
The three disciplines are:
=== Fluid logic ===
[[Infinite flow fluid logic|Infinite flow fluid logic]] is controlling the ''flow of fluid'' over different pressure plates. Fluid logic can be easily constructed and every known logic gate in dwarf fortress has already been built with it. On the other hand this discipline depends on a somehow unlimited source of the used fluid to deal with its [[evaporation|evaporation]] and [[Water#Water in Fortress Mode|destruction]].
=== Mechanical logic ===
[[Mechanical logic|Mechanical logic]] uses systems of axles and [[gear assemblies|gear assemblies]] to build logical gates. Mechanical logic reacts very fast and can be easily constructed, except for the need for a fluid-pump-based power->signal converter in every gate. Since every gear can itself be linked to a trigger (or multiple triggers), and automatically connect to adjacent gears for transferring either power or load, mechanical logic gates are very flexible and don’t require anywhere near the number of different devices that tend to be used in fluid logic gates (except, again, for the requirement for a fluid-pump-based power->signal converter in every gate, unless you intend to use it to control a pump). On the other hand this discipline uses a LOT of mechanical power, and due to the lack of a power->signal converter, also referred to as a «rotation sensor» (a device to convert from power to on/off link signals), you need to build one using fluid logic components if you want to connect multiple mechanical logic gates together or connect a mechanical logic gate to any output other than a pump. There is, however, now a fully functional fluid preserving rotation sensor design. So, in truth, current mechanical logic is more correctly termed mechanical-fluid hybrid logic, as you need some source of fluid to «prime» the rotation sensors your design will need. Along with new techniques to construct logic gates by «pre-toggling» a gear assembly (see [[Pre-Toggled Mechanical Logic|Pre-Toggled Mechanical Logic]]), any logical circuit can be built, given enough space in the game to do it.
=== Animal logic ===
[[Animal logic|Animal logic]] places animals in an enclosed room, with a door blocking the path to where they desire to go, and a pressure plate below a hatch, with obstacles which are controlled by triggers. The animal thinks it can walk through the door, and if it has a path to the door will walk up to it and stand on the hatch. When the hatch is opened by a trigger, it falls onto the pressure plate. As long as the hatch is open, or other obstacles block its path to the door it remains on the pressure plate and the output is 'on'. Once it sees a path to the door it will leave the pressure plate. Generally this is made possibly by the fact that animals try to go to their parent while they’re children, or to the meeting area. There are also be designs which use captured hostiles.
There was a fourth, theoretical, discipline, Borg Logic, but there was never any reported success inventing any functioning and useful borg logic systems.
=== Examples of things you could do with logic gates ===
* Repeater: Repeatedly toggling hatches open and closed, or spikes up and down.
* Latch: Making resettable one-use pressure plates which are reset by a lever.
* NOT gate: Reversing the effect of a switch or creature-sensing pressure plate, generally linked to a latch device. You can, of course, mod the latch device to send the opposite signal instead of using a NOT gate.
* AND gate: Requiring more than one condition to be true for something to occur. For instance, you could have a group of AND gates, with a system on/off switch, and and other triggers, with each trigger linked to a different AND gate with the system on/off switch linked to the the second input on all the AND gates, so that when the system on/off switch is OFF the output will be OFF on all the AND gates.
* OR gate: You could link two 1-7 water sensors to an OR gate, and link that to a NOT gate, and link that to some floodgates or doors which act as emergency bulkheads, closing when water is detected in the area. Or, link the OR gate to bridges which raise instead (but you may crush things, and bridges are slower than doors).
* XOR gate: You could use pressure plates hooked to latches at different points in your fort to detect enemy intrusion, and set them up to seal off the area with both an interior and exterior bulkhead when the intrusion occurs, but hook your latches up with an XOR gate and hook the output to the interior bulkhead to unseal that one if your pressure plates have detected that the enemy has gotten past it.
* NOR gate: A NOR gate returns TRUE (ON) only if both inputs are FALSE. Instead of using the OR gate example with a NOT gate, you could use a NOR gate linked to two 1-7 water sensors, whose output goes to doors or floodgates. When the pressure plates are both waterless, the floodgates will be open. When one detects water, the floodgates close. (If you used 0-0 pressure plates with an OR, you would get an OFF signal if both plates detected water, or an ON signal otherwise (which is the same as 1-7 NAND 1-7))
* NAND gate: A NAND gate returns TRUE (ON) whenever both inputs are not both TRUE (e.g. ON NAND ON is OFF, but every other combination is ON). Instead of the OR NOT or NOR example, you could link two 0-0 water sensors to a NAND gate, and link the NAND gate’s output to raising bridges. 0-0 NAND 0-0 is the same as 1-7 OR 1-7. If there is no water on both pressure plates, the NAND gate will output an OFF signal. If, however, either has water, it will output an ON signal.
* And here’s a more complicated example, omitting the details of what gates to use: An automated swimming training room, where you pull a lever to close exit doors and open hatches to drop water into it, then pressure plates detect when there’s enough water and close the hatches, and after a certain amount of time (using a very slow repeater, for instance), drains and exit doors open and the system resets until you pull the lever again. Or, the lever could be taken out entirely and the system could be made fully automatic (with dwarves set to train in the room, for instance) using the repeater.
== Примеры ==
== Примеры ==
Здесь приведены примеры нескольких реально работающих схем и некоторые концепции ,которые в принципе могут быть использованы. Но в большинстве случаев они создавались просто для веселья. Это нисколько не умаляет заслуги их разработчиков т.к. их создание в целом  может оказаться очень сложным.<br />Пока что неизвестны примеры основанные на животной или борг логике.
Здесь приведены примеры нескольких реально работающих дварфопьютеров и некоторые концепции, которые в принципе могут быть использованы. Но в большинстве случаев они создавались просто для веселья. Это нисколько не умаляет заслуги их разработчиков т.к. их создание в целом  может оказаться очень сложным.<br />Пока что неизвестны примеры схем основанные на животной или борг логике.


=== Полезное ===
=== Полезное ===
* Magma trap
* Магменная ловушка
** This is an example of a useful dwarfputer controlling a magma trap. It automatically floods an area with lava, cleans up and resets afterwards. The timing is perfectly adjusted to let the victims vanish only leaving their valuable metal behind.<br />video: http://mkv25.net/dfma/movie-1808-perfectmagmatrap<br />design: http://i576.photobucket.com/albums/ss208/kanddak/magmatrap.png
** Пример рабочего дварфопьютера управляющего магменной ловушкой. Она автоматически наводняет местность лавой, а через некоторое время избавляется от неё. Таймер специально рассчитан так, чтобы жертва после себя оставляла только ценные металлы.<br />видео: http://mkv25.net/dfma/movie-1808-perfectmagmatrap<br />устройство: http://i576.photobucket.com/albums/ss208/kanddak/magmatrap.png


=== Идеи ===
=== Идеи ===
* repeater
* повторитель
** mechanical logic http://mkv25.net/dfma/movie-1370-pump-basedautorepeater
** на механической логике http://mkv25.net/dfma/movie-1370-pump-basedautorepeater
* adding machine
* арифмометр
** mechanical logic, 6-bit: http://mkv25.net/dfma/movie-1561-addingmachine
** на механической логике, 6-битный(6-bit): http://mkv25.net/dfma/movie-1561-addingmachine
** fluid logic, 8-bit: http://mkv25.net/dfma/movie-1084-numberabbeydemonstration
** на жидкостной логике, 8-битный(8-bit): http://mkv25.net/dfma/movie-1084-numberabbeydemonstration


=== Раз плюнуть ===
=== Раз плюнуть ===
* decimal display for 4-bit binary input
* десятичный дисплей с 4-битными двоичными входными данными
** mechanical logic, decimal with overflow-bit: http://mkv25.net/dfma/movie-1745-dwarfputerv01
** на механической логике, десятичный с битом переполнения: http://mkv25.net/dfma/movie-1745-dwarfputerv01
** probably fluid logic: http://mkv25.net/dfma/movie-1657-7segmentlcddisplay
** вероятно жидкостная логика: http://mkv25.net/dfma/movie-1657-7segmentlcddisplay
** fluid logic, hexadecimal: http://mkv25.net/dfma/movie-1092-7-segmentdisplaydemonstration
** жидкостная логика, шестнадцатеричный: http://mkv25.net/dfma/movie-1092-7-segmentdisplaydemonstration
* tic tac toe
* крестики-нолики
** mechanical logic http://mkv25.net/dfma/movie-1813-tictactoev10simple
** на механической логике http://mkv25.net/dfma/movie-1813-tictactoev10simple
 
== Страницы по теме ==
* [http://df.magmawiki.com/index.php/User:BaronW User:BaronW] — The Almighty Dwarven Calculator
* [http://df.magmawiki.com/index.php/User:Jong User:Jong] — The first fully programmable digital Dwarven Computer
* [http://df.magmawiki.com/index.php/User:SL/Logic Gates User:SL/Logic Gates] — These use mechanisms for connecting gates and devices and so forth, but fluid for logic. They’re built on top of a body of water, and require power (for a pump or two per gate).
* [http://df.magmawiki.com/index.php/User:Kyace/Adder User:Kyace/Adder] — A full adder built using fluid logic, with a video of a rough prototype. Trivial to combine 8 of these to make a fluid device capable of adding two 8 bit numbers together.
* [http://df.magmawiki.com/index.php/User:Soundandfury#Logic_Gates User:Soundandfury#Logic_Gates] — These have a water supply reservoir above and a drain below. The drained water can be pumped back to the supply reservoir.
* [http://df.magmawiki.com/index.php/User:Bidok User:Bidok] — Animal logic with all gates, memory, repeater and counter. All powered by kittens.
* [http://df.magmawiki.com/index.php/User:LordOOTFD#Animal_Logic User:LordOOTFD#Animal_Logic] — Animal logic with fast complex gates, building upon Bidok’s kitten powered systems.
* [http://df.magmawiki.com/index.php/User:Hussell#Assorted_Devices User:Hussell#Assorted_Devices] — Fluid logic
* [http://df.magmawiki.com/index.php/User:Gammon User:Gammon] — Fluid logic. Very detailed CMOS gates.
 
{{buildings}}
 
[[en:Computing]]

Версия от 12:41, 27 февраля 2013

Примеры

Здесь приведены примеры нескольких реально работающих дварфопьютеров и некоторые концепции, которые в принципе могут быть использованы. Но в большинстве случаев они создавались просто для веселья. Это нисколько не умаляет заслуги их разработчиков т.к. их создание в целом может оказаться очень сложным.
Пока что неизвестны примеры схем основанные на животной или борг логике.

Полезное

  • Магменная ловушка
    • Пример рабочего дварфопьютера управляющего магменной ловушкой. Она автоматически наводняет местность лавой, а через некоторое время избавляется от неё. Таймер специально рассчитан так, чтобы жертва после себя оставляла только ценные металлы.
      видео: http://mkv25.net/dfma/movie-1808-perfectmagmatrap
      устройство: http://i576.photobucket.com/albums/ss208/kanddak/magmatrap.png

Идеи

Раз плюнуть